Phalcon Framework 1.2.6

Phalcon\Logger\Exception: Can't open log file at '/var/www/html/ptmu/common/config/../../logs/20170221/sql_slave_profiler.log'

/var/www/html/ptmu/common/config/services.php (166)
#0Phalcon\Logger\Adapter\File->__construct(/var/www/html/ptmu/common/config/../../logs/20170221/sql_slave_profiler.log)
/var/www/html/ptmu/common/config/services.php (166)
<?php
 
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Logger\Adapter\File as LoggerAdapterFile;
use Phalcon\Logger\Adapter\Dummy as LoggerAdapterDummy;
use Phalcon\Logger\Adapter\Stream as StreamAdapter;
use Phalcon\Events\Manager as EventManager;
use Phalcon\Logger\Formatter\Line as LineFormatter;
use PTMU\Models\Taxonomy;
use PTMU\Models\Translations;
use PTMU\Models\Locations;
use Phalcon\Db\Profiler as DBProfiler;
use Phalcon\Cache\Multiple;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Logger as Logger;
use Phalcon\DI;
use PTMU\MDebuger\MDebuger;
use PTMU\SphinxApi\SphinxClient;
use PTMU\Utils\Utils;
 
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault ();
$loggers = array ();
 
/**
 * Register the configuration itself as a service
 */
$di->setShared ('config', $config);
                      
/**
 * Router
 */
$di->setShared ('router', function () use ($di) {
  return include (__DIR__ . "/routes.php");
});
 
/**
* Dispatcher use a default namespace
*/
$di->setShared ('dispatcher', function () use ($di) {
  $dispatcher = new Dispatcher ();       
  
  $eventsManager = new EventManager ();  
  
  $eventsManager->attach ("dispatch", function ($event, $dispatcher, $exception) use ($di) {
    if ($event->getType () == 'beforeNotFoundAction') { 
      $dispatcher->forward (array (
        'controller' => 'index',
        'action'     => 'route404'
      ));
      
      return false;
    }
    
    if ($event->getType() == 'beforeException') { 
      switch ($exception->getCode ()) {
        case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
        case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
          $dispatcher->forward (array (
            'controller' => 'index',
            'action'     => 'route404'
          ));
          
          return false;
      }
    }
  });  
  
  $dispatcher->setEventsManager ($eventsManager);
  
  return $dispatcher;
});
 
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->setShared ('url', function() use ($config) {
  $url = new UrlResolver();
  
  $url->setBaseUri($config->application->baseUri);
  
  return $url;
});
          
/**
* Setting up volt
*/
 $di->setShared ('volt', function ($view, $di) use ($config) {
  $volt = new VoltEngine ($view, $di);                        
  
  $options = array (
    'compiledPath'      => $config->application->voltDir,
    'compiledSeparator' => '_',
    'prefix'            => $config->cache->prefix
  );
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $options ['compileAlways'] = true;
  }
  
  $volt->setOptions ($options);
 
  return $volt;
});
  
/**
* Setting up the view component
*/
$di->setShared ('view', function() use ($di, $config) {
  $view = new View ();
 
  $view->registerEngines(array(
    '.volt' => 'volt',
    '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
  ));
 
  $view->setLayout ('inner');
  
  $debugMode = $di->get ('cookies')->get ('ptmu-debug-mode');  
  
  if (filter_var ($debugMode->getValue (), FILTER_VALIDATE_BOOLEAN)) {
    $eventsManager = new EventManager;
    
    $request = $di->getService ('request');
    
    $eventsManager->attach ("view", function ($event, $view) {
      if ($event->getType() == 'beforeRender') {
        MDebuger::$BeforeRender = (microtime (true) - APP_START_TIME);
      }
      
      if ($event->getType() == 'afterRender') {
        MDebuger::$AfterRender = (microtime (true) - APP_START_TIME);
        
        $profiler = '<div class="debug" style="color: black;text-align: left;"><br clear="all"/><div style="background-color:#EFEFEF; margin: 4px; padding: 4px; border: solid 1px #345487; text-align: center">Script Execution time: <b>' . MDebuger::$AfterRender . '</b> (Clear code: <b>' . (MDebuger::$AfterRender - MDebuger::$SqlTime - (( MDebuger::$AfterRender - MDebuger::$BeforeRender ))) . '</b>, Sphinx: <b>' . $time["sphinx"] . '</b>, SQL: <b>' . MDebuger::$SqlTime . '</b>, Rendering: <b>' . ( MDebuger::$AfterRender - MDebuger::$BeforeRender ) . '</b>) &nbsp; [ <b>' . MDebuger::$SqlCount . '</b> queries used ]&nbsp; [ <b>' . Utils::toHumanBytes (memory_get_usage ()) . '</b> used ]</div>';
        $profiler .= MDebuger::RenderSmall ();
        $view->setContent (str_replace ('<!--debug-->', $profiler, $view->getContent ()));
      }
    });
    
    $view->setEventsManager ($eventsManager);  
  }
  
  return $view;
});
 
/**
* Setting up the logger component
*/
$di->set ('fileLogger', function () use ($config) {
  $arguments   = func_get_args ();  
  $logfileName = isset ($arguments [0]) ? $arguments [0] : 'application';
  $dirName     = $config->application->logDir . date ('Ymd');  
  
  if (!is_dir ($dirName)) {
    umask (0);
    mkdir ($dirName, 0774);    
    umask (002);      
  }
  
  $logger = new LoggerAdapterFile ($dirName . "/{$logfileName}.log");
  $logger->setFormatter (new LineFormatter ("[%date%][%type%] %message%", "Y-m-d H:i:s O"));      
  
  return $logger;
});
 
/**
* Setting up the logger component
*/
$di->setShared ('logger', function () use ($di, $config) {
  if ($config->logging->app) {
    return $di->get ('fileLogger', 'application');
  } else {
    return new LoggerAdapterDummy ();
  }
});
 
 
/**
 * Setting up the sphinxApi component
 */
$di->set ('sphinxApi', function () use ($di, $config) {
   $cl = new PTMU\SphinxApi\SphinxClient ();
   
   $cl->SetServer ($config->database->sphinx->host, $config->database->sphinx->portApi);
   $cl->SetConnectTimeout (1);
   $cl->SetArrayResult (true);
 
  return $cl;
});
 
/**
* Database event manager
*/
$di->set ('dbEventManager', function() use ($config, $di) {
  $arguments      = func_get_args ();
  $logFileName    = isset ($arguments [0]) ? $arguments [0] : 'sql';
  $logger         = null;
  $profiler       = null;
  $sqlLogger      = null;
  $profilerLogger = null;
 
  $eventsManager = new EventManager (); 
  
  if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $profiler       = new DBProfiler ();        
    $profilerLogger = $di->get ('fileLogger', array ("{$logFileName}_profiler"));
  }
  
  if ($config->logging->sql) {
    $sqlLogger = $di->get ('fileLogger', array ($logFileName));
  }
 
  //Listen all the database events
  $eventsManager->attach ("db", function ($event, $connection) use ($sqlLogger, $profilerLogger, $config, $profiler, $logFileName) {
    if ($event->getType () == 'beforeQuery') {
      if ($config->logging->sql) {
        $sqlVariables = $connection->getSqlVariables();          
        
        if (is_array ($sqlVariables)) {
          $sqlLogger->log ($connection->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']', Logger::DEBUG);
        } else {
          $sqlLogger->log ($connection->getSQLStatement (), Logger::DEBUG);            
        }
      }                                                   
      if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
        $profiler->startProfile ($connection->getSQLStatement ());
      }
    }
    
    if ($event->getType () == 'afterQuery') {      
      if ($config->logging->sqlProfiler) {
        $profiler->stopProfile();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables();                  
 
        if (is_array ($sqlVariables)) {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']' . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        } else {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        }
      }  
      
      if( $config->logging->sqlProfilerWeb ){
        $profiler->stopProfile ();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables (); 
        
        MDebuger::$SqlLog [] = array (
          "query"    => $connection->getSQLStatement (),
          "time"     => $profile->getTotalElapsedSeconds(),
          "serverdb" => (strpos ($connection->getSQLStatement (), 'spx_') !== false ? 'sphinx' : $logFileName),
          "heavy"    => intval($profile->getTotalElapsedSeconds() > 0.1),
          "total"    => 1
        );
        
        MDebuger::$SqlTime += $profile->getTotalElapsedSeconds ();
        MDebuger::$SqlCount++;
      }
    }
  });
  
  return $eventsManager;
});
 
/**
* Master database connection
*/
$di->set ('dbMaster', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->master->host,
    'port'       => $config->database->master->port,
    'username'   => $config->database->master->username,
    'password'   => $config->database->master->password,
    'dbname'     => $config->database->master->dbname,
    'charset'    => $config->database->master->charset,
    'persistent' => $config->database->master->persistent
  ));
  
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_master')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSlave', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->slave->host,
    'port'       => $config->database->slave->port,
    'username'   => $config->database->slave->username,
    'password'   => $config->database->slave->password,
    'dbname'     => $config->database->slave->dbname,
    'charset'    => $config->database->slave->charset,
    'persistent' => $config->database->slave->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_slave')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSphinx', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->sphinx->host,
    'port'       => $config->database->sphinx->port,
    'charset'    => $config->database->sphinx->charset,
    'persistent' => $config->database->sphinx->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sphinx')));
  }
  
  return $connection;
});
 
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set ('modelsMetadata', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Mvc\Model\Metadata\Memory ();
  } else {
    return new \Phalcon\Mvc\Model\MetaData\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->cache->lifetime,
    ));
  }
});
 
/**
* Start the session the first time some component request the session service
*/
$di->set ('session', function () use ($config) {
  session_set_cookie_params (0, $config->application->baseUri, '.' . $config->application->mainDomain);
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $session = new \Phalcon\Session\Adapter\Files ();
  } else {
    $session = new \Phalcon\Session\Adapter\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->session->lifetime,      
      'cookie'     => array ('domain' => '.' . $config->application->mainDomain)
    ));
  } 
  
  $session->start ();
  
  return $session;
});
 
/**
* Setting up the cache
*/
$di->setShared ('viewCache', function () use ($config) {
  $frontCache = new \Phalcon\Cache\Frontend\Output (array (
    'lifetime' => $config->cache->lifetime,
  ));
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Cache\Backend\File ($frontCache, array (
      'cacheDir' => $config->application->cacheDir . 'view/',    
      'prefix'   => $config->cache->prefix,    
    ));
  } else {  
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new $adapterClass ($frontCache, array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
    ));
  }
});
 
/**
* Setting up the cache
*/
$di->setShared ('cache', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $frontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->lifetime,
    ));
 
    return new \Phalcon\Cache\Backend\Memory ($frontCache);
  } else {  
    $apcFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->apc->lifetime,
    ));
    
    $memcacheFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->memcache->lifetime,
    ));
    
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new Multiple (array (
      new \Phalcon\Cache\Backend\Apc ($apcFrontCache, array (
        'prefix' => $config->cache->prefix,
      )),
      
      new $adapterClass ($memcacheFrontCache, array (
        'host'       => $config->cache->memcache->host,
        'port'       => $config->cache->memcache->port,
        'persistent' => $config->cache->memcache->persistent,            
        'prefix'     => $config->cache->prefix,
      ))
    ));
  }
});
 
/**
* Setting up the models cache
*/
$di->setShared ('modelsCache', function () use ($di) {
  return $di->getCache ();
});
 
/**
* Setting up the models manager
*/
$di->setShared ('modelsManager', function () use ($di) {
  return new \PTMU\ModelsManager\ModelsManager ();
});
 
/**
 * Custom authentication component
 */
$di->setShared ('auth', function(){
  return new \PTMU\Auth\Auth ();
});
 
/**
* Setting up the authentication component
*/
$di->setShared ('lang', function () use ($di, $config) {
  $eventsManager = new EventManager ();   
  $language      = new \PTMU\Lang\Lang ($config->application->defaults->language);
 
  $eventsManager->attach ("language:afterSetLanguage", function ($event, $component, $code) {
    // Reload translations
    Translations::load (true);
  });
  
  $language->setEventsManager ($eventsManager);
  
  return $language;
});
 
/**
* Setting up the language component
*/
$di->setShared ('location', function () use ($config) {
  $eventsManager = new EventManager (); 
  $location      = new \PTMU\Location\Location ($config->application->defaults->country);
  
  $eventsManager->attach ("location:afterSetLocation", function ($event, $component, $code) {
    // Reload taxonomy
    Taxonomy::load (true);
    
    // Reload locations
    Locations::load (true);
  });
  
  $location->setEventsManager ($eventsManager);
  
  return $location;
});
 
/**
* Setting up forms manager
*/
$di->setShared ('formsManager', function () use ($di) {
  return new \PTMU\Forms\Manager ();
});
 
/**
* Setting up flash service
*/
$di->setShared ('flash', function () {
  return new \Phalcon\Flash\Direct ();
});
 
/**
* Setting up sendmail service
*/
$di->setShared ('mail', function () use ($config) {
  return new \Zend\Mail\Transport\Sendmail ();
});
 
/**
* Setting up cookies service
*/
$di->set('cookies', function() {
  $cookies = new Phalcon\Http\Response\Cookies ();
  $cookies->useEncryption (false);
  
  return $cookies;
});
#1{closure}(sql_slave_profiler)
#2Phalcon\DI\Service->resolve(Array([0] => sql_slave_profiler), Object(Phalcon\DI\FactoryDefault))
#3Phalcon\DI->get(fileLogger, Array([0] => sql_slave_profiler))
/var/www/html/ptmu/common/config/services.php (212)
<?php
 
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Logger\Adapter\File as LoggerAdapterFile;
use Phalcon\Logger\Adapter\Dummy as LoggerAdapterDummy;
use Phalcon\Logger\Adapter\Stream as StreamAdapter;
use Phalcon\Events\Manager as EventManager;
use Phalcon\Logger\Formatter\Line as LineFormatter;
use PTMU\Models\Taxonomy;
use PTMU\Models\Translations;
use PTMU\Models\Locations;
use Phalcon\Db\Profiler as DBProfiler;
use Phalcon\Cache\Multiple;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Logger as Logger;
use Phalcon\DI;
use PTMU\MDebuger\MDebuger;
use PTMU\SphinxApi\SphinxClient;
use PTMU\Utils\Utils;
 
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault ();
$loggers = array ();
 
/**
 * Register the configuration itself as a service
 */
$di->setShared ('config', $config);
                      
/**
 * Router
 */
$di->setShared ('router', function () use ($di) {
  return include (__DIR__ . "/routes.php");
});
 
/**
* Dispatcher use a default namespace
*/
$di->setShared ('dispatcher', function () use ($di) {
  $dispatcher = new Dispatcher ();       
  
  $eventsManager = new EventManager ();  
  
  $eventsManager->attach ("dispatch", function ($event, $dispatcher, $exception) use ($di) {
    if ($event->getType () == 'beforeNotFoundAction') { 
      $dispatcher->forward (array (
        'controller' => 'index',
        'action'     => 'route404'
      ));
      
      return false;
    }
    
    if ($event->getType() == 'beforeException') { 
      switch ($exception->getCode ()) {
        case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
        case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
          $dispatcher->forward (array (
            'controller' => 'index',
            'action'     => 'route404'
          ));
          
          return false;
      }
    }
  });  
  
  $dispatcher->setEventsManager ($eventsManager);
  
  return $dispatcher;
});
 
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->setShared ('url', function() use ($config) {
  $url = new UrlResolver();
  
  $url->setBaseUri($config->application->baseUri);
  
  return $url;
});
          
/**
* Setting up volt
*/
 $di->setShared ('volt', function ($view, $di) use ($config) {
  $volt = new VoltEngine ($view, $di);                        
  
  $options = array (
    'compiledPath'      => $config->application->voltDir,
    'compiledSeparator' => '_',
    'prefix'            => $config->cache->prefix
  );
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $options ['compileAlways'] = true;
  }
  
  $volt->setOptions ($options);
 
  return $volt;
});
  
/**
* Setting up the view component
*/
$di->setShared ('view', function() use ($di, $config) {
  $view = new View ();
 
  $view->registerEngines(array(
    '.volt' => 'volt',
    '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
  ));
 
  $view->setLayout ('inner');
  
  $debugMode = $di->get ('cookies')->get ('ptmu-debug-mode');  
  
  if (filter_var ($debugMode->getValue (), FILTER_VALIDATE_BOOLEAN)) {
    $eventsManager = new EventManager;
    
    $request = $di->getService ('request');
    
    $eventsManager->attach ("view", function ($event, $view) {
      if ($event->getType() == 'beforeRender') {
        MDebuger::$BeforeRender = (microtime (true) - APP_START_TIME);
      }
      
      if ($event->getType() == 'afterRender') {
        MDebuger::$AfterRender = (microtime (true) - APP_START_TIME);
        
        $profiler = '<div class="debug" style="color: black;text-align: left;"><br clear="all"/><div style="background-color:#EFEFEF; margin: 4px; padding: 4px; border: solid 1px #345487; text-align: center">Script Execution time: <b>' . MDebuger::$AfterRender . '</b> (Clear code: <b>' . (MDebuger::$AfterRender - MDebuger::$SqlTime - (( MDebuger::$AfterRender - MDebuger::$BeforeRender ))) . '</b>, Sphinx: <b>' . $time["sphinx"] . '</b>, SQL: <b>' . MDebuger::$SqlTime . '</b>, Rendering: <b>' . ( MDebuger::$AfterRender - MDebuger::$BeforeRender ) . '</b>) &nbsp; [ <b>' . MDebuger::$SqlCount . '</b> queries used ]&nbsp; [ <b>' . Utils::toHumanBytes (memory_get_usage ()) . '</b> used ]</div>';
        $profiler .= MDebuger::RenderSmall ();
        $view->setContent (str_replace ('<!--debug-->', $profiler, $view->getContent ()));
      }
    });
    
    $view->setEventsManager ($eventsManager);  
  }
  
  return $view;
});
 
/**
* Setting up the logger component
*/
$di->set ('fileLogger', function () use ($config) {
  $arguments   = func_get_args ();  
  $logfileName = isset ($arguments [0]) ? $arguments [0] : 'application';
  $dirName     = $config->application->logDir . date ('Ymd');  
  
  if (!is_dir ($dirName)) {
    umask (0);
    mkdir ($dirName, 0774);    
    umask (002);      
  }
  
  $logger = new LoggerAdapterFile ($dirName . "/{$logfileName}.log");
  $logger->setFormatter (new LineFormatter ("[%date%][%type%] %message%", "Y-m-d H:i:s O"));      
  
  return $logger;
});
 
/**
* Setting up the logger component
*/
$di->setShared ('logger', function () use ($di, $config) {
  if ($config->logging->app) {
    return $di->get ('fileLogger', 'application');
  } else {
    return new LoggerAdapterDummy ();
  }
});
 
 
/**
 * Setting up the sphinxApi component
 */
$di->set ('sphinxApi', function () use ($di, $config) {
   $cl = new PTMU\SphinxApi\SphinxClient ();
   
   $cl->SetServer ($config->database->sphinx->host, $config->database->sphinx->portApi);
   $cl->SetConnectTimeout (1);
   $cl->SetArrayResult (true);
 
  return $cl;
});
 
/**
* Database event manager
*/
$di->set ('dbEventManager', function() use ($config, $di) {
  $arguments      = func_get_args ();
  $logFileName    = isset ($arguments [0]) ? $arguments [0] : 'sql';
  $logger         = null;
  $profiler       = null;
  $sqlLogger      = null;
  $profilerLogger = null;
 
  $eventsManager = new EventManager (); 
  
  if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $profiler       = new DBProfiler ();        
    $profilerLogger = $di->get ('fileLogger', array ("{$logFileName}_profiler"));
  }
  
  if ($config->logging->sql) {
    $sqlLogger = $di->get ('fileLogger', array ($logFileName));
  }
 
  //Listen all the database events
  $eventsManager->attach ("db", function ($event, $connection) use ($sqlLogger, $profilerLogger, $config, $profiler, $logFileName) {
    if ($event->getType () == 'beforeQuery') {
      if ($config->logging->sql) {
        $sqlVariables = $connection->getSqlVariables();          
        
        if (is_array ($sqlVariables)) {
          $sqlLogger->log ($connection->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']', Logger::DEBUG);
        } else {
          $sqlLogger->log ($connection->getSQLStatement (), Logger::DEBUG);            
        }
      }                                                   
      if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
        $profiler->startProfile ($connection->getSQLStatement ());
      }
    }
    
    if ($event->getType () == 'afterQuery') {      
      if ($config->logging->sqlProfiler) {
        $profiler->stopProfile();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables();                  
 
        if (is_array ($sqlVariables)) {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']' . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        } else {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        }
      }  
      
      if( $config->logging->sqlProfilerWeb ){
        $profiler->stopProfile ();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables (); 
        
        MDebuger::$SqlLog [] = array (
          "query"    => $connection->getSQLStatement (),
          "time"     => $profile->getTotalElapsedSeconds(),
          "serverdb" => (strpos ($connection->getSQLStatement (), 'spx_') !== false ? 'sphinx' : $logFileName),
          "heavy"    => intval($profile->getTotalElapsedSeconds() > 0.1),
          "total"    => 1
        );
        
        MDebuger::$SqlTime += $profile->getTotalElapsedSeconds ();
        MDebuger::$SqlCount++;
      }
    }
  });
  
  return $eventsManager;
});
 
/**
* Master database connection
*/
$di->set ('dbMaster', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->master->host,
    'port'       => $config->database->master->port,
    'username'   => $config->database->master->username,
    'password'   => $config->database->master->password,
    'dbname'     => $config->database->master->dbname,
    'charset'    => $config->database->master->charset,
    'persistent' => $config->database->master->persistent
  ));
  
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_master')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSlave', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->slave->host,
    'port'       => $config->database->slave->port,
    'username'   => $config->database->slave->username,
    'password'   => $config->database->slave->password,
    'dbname'     => $config->database->slave->dbname,
    'charset'    => $config->database->slave->charset,
    'persistent' => $config->database->slave->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_slave')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSphinx', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->sphinx->host,
    'port'       => $config->database->sphinx->port,
    'charset'    => $config->database->sphinx->charset,
    'persistent' => $config->database->sphinx->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sphinx')));
  }
  
  return $connection;
});
 
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set ('modelsMetadata', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Mvc\Model\Metadata\Memory ();
  } else {
    return new \Phalcon\Mvc\Model\MetaData\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->cache->lifetime,
    ));
  }
});
 
/**
* Start the session the first time some component request the session service
*/
$di->set ('session', function () use ($config) {
  session_set_cookie_params (0, $config->application->baseUri, '.' . $config->application->mainDomain);
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $session = new \Phalcon\Session\Adapter\Files ();
  } else {
    $session = new \Phalcon\Session\Adapter\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->session->lifetime,      
      'cookie'     => array ('domain' => '.' . $config->application->mainDomain)
    ));
  } 
  
  $session->start ();
  
  return $session;
});
 
/**
* Setting up the cache
*/
$di->setShared ('viewCache', function () use ($config) {
  $frontCache = new \Phalcon\Cache\Frontend\Output (array (
    'lifetime' => $config->cache->lifetime,
  ));
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Cache\Backend\File ($frontCache, array (
      'cacheDir' => $config->application->cacheDir . 'view/',    
      'prefix'   => $config->cache->prefix,    
    ));
  } else {  
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new $adapterClass ($frontCache, array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
    ));
  }
});
 
/**
* Setting up the cache
*/
$di->setShared ('cache', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $frontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->lifetime,
    ));
 
    return new \Phalcon\Cache\Backend\Memory ($frontCache);
  } else {  
    $apcFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->apc->lifetime,
    ));
    
    $memcacheFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->memcache->lifetime,
    ));
    
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new Multiple (array (
      new \Phalcon\Cache\Backend\Apc ($apcFrontCache, array (
        'prefix' => $config->cache->prefix,
      )),
      
      new $adapterClass ($memcacheFrontCache, array (
        'host'       => $config->cache->memcache->host,
        'port'       => $config->cache->memcache->port,
        'persistent' => $config->cache->memcache->persistent,            
        'prefix'     => $config->cache->prefix,
      ))
    ));
  }
});
 
/**
* Setting up the models cache
*/
$di->setShared ('modelsCache', function () use ($di) {
  return $di->getCache ();
});
 
/**
* Setting up the models manager
*/
$di->setShared ('modelsManager', function () use ($di) {
  return new \PTMU\ModelsManager\ModelsManager ();
});
 
/**
 * Custom authentication component
 */
$di->setShared ('auth', function(){
  return new \PTMU\Auth\Auth ();
});
 
/**
* Setting up the authentication component
*/
$di->setShared ('lang', function () use ($di, $config) {
  $eventsManager = new EventManager ();   
  $language      = new \PTMU\Lang\Lang ($config->application->defaults->language);
 
  $eventsManager->attach ("language:afterSetLanguage", function ($event, $component, $code) {
    // Reload translations
    Translations::load (true);
  });
  
  $language->setEventsManager ($eventsManager);
  
  return $language;
});
 
/**
* Setting up the language component
*/
$di->setShared ('location', function () use ($config) {
  $eventsManager = new EventManager (); 
  $location      = new \PTMU\Location\Location ($config->application->defaults->country);
  
  $eventsManager->attach ("location:afterSetLocation", function ($event, $component, $code) {
    // Reload taxonomy
    Taxonomy::load (true);
    
    // Reload locations
    Locations::load (true);
  });
  
  $location->setEventsManager ($eventsManager);
  
  return $location;
});
 
/**
* Setting up forms manager
*/
$di->setShared ('formsManager', function () use ($di) {
  return new \PTMU\Forms\Manager ();
});
 
/**
* Setting up flash service
*/
$di->setShared ('flash', function () {
  return new \Phalcon\Flash\Direct ();
});
 
/**
* Setting up sendmail service
*/
$di->setShared ('mail', function () use ($config) {
  return new \Zend\Mail\Transport\Sendmail ();
});
 
/**
* Setting up cookies service
*/
$di->set('cookies', function() {
  $cookies = new Phalcon\Http\Response\Cookies ();
  $cookies->useEncryption (false);
  
  return $cookies;
});
#4{closure}(sql_slave)
#5Phalcon\DI\Service->resolve(Array([0] => sql_slave), Object(Phalcon\DI\FactoryDefault))
#6Phalcon\DI->get(dbEventManager, Array([0] => sql_slave))
/var/www/html/ptmu/common/config/services.php (309)
<?php
 
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Logger\Adapter\File as LoggerAdapterFile;
use Phalcon\Logger\Adapter\Dummy as LoggerAdapterDummy;
use Phalcon\Logger\Adapter\Stream as StreamAdapter;
use Phalcon\Events\Manager as EventManager;
use Phalcon\Logger\Formatter\Line as LineFormatter;
use PTMU\Models\Taxonomy;
use PTMU\Models\Translations;
use PTMU\Models\Locations;
use Phalcon\Db\Profiler as DBProfiler;
use Phalcon\Cache\Multiple;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Logger as Logger;
use Phalcon\DI;
use PTMU\MDebuger\MDebuger;
use PTMU\SphinxApi\SphinxClient;
use PTMU\Utils\Utils;
 
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault ();
$loggers = array ();
 
/**
 * Register the configuration itself as a service
 */
$di->setShared ('config', $config);
                      
/**
 * Router
 */
$di->setShared ('router', function () use ($di) {
  return include (__DIR__ . "/routes.php");
});
 
/**
* Dispatcher use a default namespace
*/
$di->setShared ('dispatcher', function () use ($di) {
  $dispatcher = new Dispatcher ();       
  
  $eventsManager = new EventManager ();  
  
  $eventsManager->attach ("dispatch", function ($event, $dispatcher, $exception) use ($di) {
    if ($event->getType () == 'beforeNotFoundAction') { 
      $dispatcher->forward (array (
        'controller' => 'index',
        'action'     => 'route404'
      ));
      
      return false;
    }
    
    if ($event->getType() == 'beforeException') { 
      switch ($exception->getCode ()) {
        case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
        case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
          $dispatcher->forward (array (
            'controller' => 'index',
            'action'     => 'route404'
          ));
          
          return false;
      }
    }
  });  
  
  $dispatcher->setEventsManager ($eventsManager);
  
  return $dispatcher;
});
 
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->setShared ('url', function() use ($config) {
  $url = new UrlResolver();
  
  $url->setBaseUri($config->application->baseUri);
  
  return $url;
});
          
/**
* Setting up volt
*/
 $di->setShared ('volt', function ($view, $di) use ($config) {
  $volt = new VoltEngine ($view, $di);                        
  
  $options = array (
    'compiledPath'      => $config->application->voltDir,
    'compiledSeparator' => '_',
    'prefix'            => $config->cache->prefix
  );
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $options ['compileAlways'] = true;
  }
  
  $volt->setOptions ($options);
 
  return $volt;
});
  
/**
* Setting up the view component
*/
$di->setShared ('view', function() use ($di, $config) {
  $view = new View ();
 
  $view->registerEngines(array(
    '.volt' => 'volt',
    '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
  ));
 
  $view->setLayout ('inner');
  
  $debugMode = $di->get ('cookies')->get ('ptmu-debug-mode');  
  
  if (filter_var ($debugMode->getValue (), FILTER_VALIDATE_BOOLEAN)) {
    $eventsManager = new EventManager;
    
    $request = $di->getService ('request');
    
    $eventsManager->attach ("view", function ($event, $view) {
      if ($event->getType() == 'beforeRender') {
        MDebuger::$BeforeRender = (microtime (true) - APP_START_TIME);
      }
      
      if ($event->getType() == 'afterRender') {
        MDebuger::$AfterRender = (microtime (true) - APP_START_TIME);
        
        $profiler = '<div class="debug" style="color: black;text-align: left;"><br clear="all"/><div style="background-color:#EFEFEF; margin: 4px; padding: 4px; border: solid 1px #345487; text-align: center">Script Execution time: <b>' . MDebuger::$AfterRender . '</b> (Clear code: <b>' . (MDebuger::$AfterRender - MDebuger::$SqlTime - (( MDebuger::$AfterRender - MDebuger::$BeforeRender ))) . '</b>, Sphinx: <b>' . $time["sphinx"] . '</b>, SQL: <b>' . MDebuger::$SqlTime . '</b>, Rendering: <b>' . ( MDebuger::$AfterRender - MDebuger::$BeforeRender ) . '</b>) &nbsp; [ <b>' . MDebuger::$SqlCount . '</b> queries used ]&nbsp; [ <b>' . Utils::toHumanBytes (memory_get_usage ()) . '</b> used ]</div>';
        $profiler .= MDebuger::RenderSmall ();
        $view->setContent (str_replace ('<!--debug-->', $profiler, $view->getContent ()));
      }
    });
    
    $view->setEventsManager ($eventsManager);  
  }
  
  return $view;
});
 
/**
* Setting up the logger component
*/
$di->set ('fileLogger', function () use ($config) {
  $arguments   = func_get_args ();  
  $logfileName = isset ($arguments [0]) ? $arguments [0] : 'application';
  $dirName     = $config->application->logDir . date ('Ymd');  
  
  if (!is_dir ($dirName)) {
    umask (0);
    mkdir ($dirName, 0774);    
    umask (002);      
  }
  
  $logger = new LoggerAdapterFile ($dirName . "/{$logfileName}.log");
  $logger->setFormatter (new LineFormatter ("[%date%][%type%] %message%", "Y-m-d H:i:s O"));      
  
  return $logger;
});
 
/**
* Setting up the logger component
*/
$di->setShared ('logger', function () use ($di, $config) {
  if ($config->logging->app) {
    return $di->get ('fileLogger', 'application');
  } else {
    return new LoggerAdapterDummy ();
  }
});
 
 
/**
 * Setting up the sphinxApi component
 */
$di->set ('sphinxApi', function () use ($di, $config) {
   $cl = new PTMU\SphinxApi\SphinxClient ();
   
   $cl->SetServer ($config->database->sphinx->host, $config->database->sphinx->portApi);
   $cl->SetConnectTimeout (1);
   $cl->SetArrayResult (true);
 
  return $cl;
});
 
/**
* Database event manager
*/
$di->set ('dbEventManager', function() use ($config, $di) {
  $arguments      = func_get_args ();
  $logFileName    = isset ($arguments [0]) ? $arguments [0] : 'sql';
  $logger         = null;
  $profiler       = null;
  $sqlLogger      = null;
  $profilerLogger = null;
 
  $eventsManager = new EventManager (); 
  
  if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $profiler       = new DBProfiler ();        
    $profilerLogger = $di->get ('fileLogger', array ("{$logFileName}_profiler"));
  }
  
  if ($config->logging->sql) {
    $sqlLogger = $di->get ('fileLogger', array ($logFileName));
  }
 
  //Listen all the database events
  $eventsManager->attach ("db", function ($event, $connection) use ($sqlLogger, $profilerLogger, $config, $profiler, $logFileName) {
    if ($event->getType () == 'beforeQuery') {
      if ($config->logging->sql) {
        $sqlVariables = $connection->getSqlVariables();          
        
        if (is_array ($sqlVariables)) {
          $sqlLogger->log ($connection->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']', Logger::DEBUG);
        } else {
          $sqlLogger->log ($connection->getSQLStatement (), Logger::DEBUG);            
        }
      }                                                   
      if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
        $profiler->startProfile ($connection->getSQLStatement ());
      }
    }
    
    if ($event->getType () == 'afterQuery') {      
      if ($config->logging->sqlProfiler) {
        $profiler->stopProfile();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables();                  
 
        if (is_array ($sqlVariables)) {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']' . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        } else {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        }
      }  
      
      if( $config->logging->sqlProfilerWeb ){
        $profiler->stopProfile ();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables (); 
        
        MDebuger::$SqlLog [] = array (
          "query"    => $connection->getSQLStatement (),
          "time"     => $profile->getTotalElapsedSeconds(),
          "serverdb" => (strpos ($connection->getSQLStatement (), 'spx_') !== false ? 'sphinx' : $logFileName),
          "heavy"    => intval($profile->getTotalElapsedSeconds() > 0.1),
          "total"    => 1
        );
        
        MDebuger::$SqlTime += $profile->getTotalElapsedSeconds ();
        MDebuger::$SqlCount++;
      }
    }
  });
  
  return $eventsManager;
});
 
/**
* Master database connection
*/
$di->set ('dbMaster', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->master->host,
    'port'       => $config->database->master->port,
    'username'   => $config->database->master->username,
    'password'   => $config->database->master->password,
    'dbname'     => $config->database->master->dbname,
    'charset'    => $config->database->master->charset,
    'persistent' => $config->database->master->persistent
  ));
  
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_master')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSlave', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->slave->host,
    'port'       => $config->database->slave->port,
    'username'   => $config->database->slave->username,
    'password'   => $config->database->slave->password,
    'dbname'     => $config->database->slave->dbname,
    'charset'    => $config->database->slave->charset,
    'persistent' => $config->database->slave->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_slave')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSphinx', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->sphinx->host,
    'port'       => $config->database->sphinx->port,
    'charset'    => $config->database->sphinx->charset,
    'persistent' => $config->database->sphinx->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sphinx')));
  }
  
  return $connection;
});
 
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set ('modelsMetadata', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Mvc\Model\Metadata\Memory ();
  } else {
    return new \Phalcon\Mvc\Model\MetaData\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->cache->lifetime,
    ));
  }
});
 
/**
* Start the session the first time some component request the session service
*/
$di->set ('session', function () use ($config) {
  session_set_cookie_params (0, $config->application->baseUri, '.' . $config->application->mainDomain);
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $session = new \Phalcon\Session\Adapter\Files ();
  } else {
    $session = new \Phalcon\Session\Adapter\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->session->lifetime,      
      'cookie'     => array ('domain' => '.' . $config->application->mainDomain)
    ));
  } 
  
  $session->start ();
  
  return $session;
});
 
/**
* Setting up the cache
*/
$di->setShared ('viewCache', function () use ($config) {
  $frontCache = new \Phalcon\Cache\Frontend\Output (array (
    'lifetime' => $config->cache->lifetime,
  ));
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Cache\Backend\File ($frontCache, array (
      'cacheDir' => $config->application->cacheDir . 'view/',    
      'prefix'   => $config->cache->prefix,    
    ));
  } else {  
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new $adapterClass ($frontCache, array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
    ));
  }
});
 
/**
* Setting up the cache
*/
$di->setShared ('cache', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $frontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->lifetime,
    ));
 
    return new \Phalcon\Cache\Backend\Memory ($frontCache);
  } else {  
    $apcFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->apc->lifetime,
    ));
    
    $memcacheFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->memcache->lifetime,
    ));
    
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new Multiple (array (
      new \Phalcon\Cache\Backend\Apc ($apcFrontCache, array (
        'prefix' => $config->cache->prefix,
      )),
      
      new $adapterClass ($memcacheFrontCache, array (
        'host'       => $config->cache->memcache->host,
        'port'       => $config->cache->memcache->port,
        'persistent' => $config->cache->memcache->persistent,            
        'prefix'     => $config->cache->prefix,
      ))
    ));
  }
});
 
/**
* Setting up the models cache
*/
$di->setShared ('modelsCache', function () use ($di) {
  return $di->getCache ();
});
 
/**
* Setting up the models manager
*/
$di->setShared ('modelsManager', function () use ($di) {
  return new \PTMU\ModelsManager\ModelsManager ();
});
 
/**
 * Custom authentication component
 */
$di->setShared ('auth', function(){
  return new \PTMU\Auth\Auth ();
});
 
/**
* Setting up the authentication component
*/
$di->setShared ('lang', function () use ($di, $config) {
  $eventsManager = new EventManager ();   
  $language      = new \PTMU\Lang\Lang ($config->application->defaults->language);
 
  $eventsManager->attach ("language:afterSetLanguage", function ($event, $component, $code) {
    // Reload translations
    Translations::load (true);
  });
  
  $language->setEventsManager ($eventsManager);
  
  return $language;
});
 
/**
* Setting up the language component
*/
$di->setShared ('location', function () use ($config) {
  $eventsManager = new EventManager (); 
  $location      = new \PTMU\Location\Location ($config->application->defaults->country);
  
  $eventsManager->attach ("location:afterSetLocation", function ($event, $component, $code) {
    // Reload taxonomy
    Taxonomy::load (true);
    
    // Reload locations
    Locations::load (true);
  });
  
  $location->setEventsManager ($eventsManager);
  
  return $location;
});
 
/**
* Setting up forms manager
*/
$di->setShared ('formsManager', function () use ($di) {
  return new \PTMU\Forms\Manager ();
});
 
/**
* Setting up flash service
*/
$di->setShared ('flash', function () {
  return new \Phalcon\Flash\Direct ();
});
 
/**
* Setting up sendmail service
*/
$di->setShared ('mail', function () use ($config) {
  return new \Zend\Mail\Transport\Sendmail ();
});
 
/**
* Setting up cookies service
*/
$di->set('cookies', function() {
  $cookies = new Phalcon\Http\Response\Cookies ();
  $cookies->useEncryption (false);
  
  return $cookies;
});
#7{closure}()
#8Phalcon\DI\Service->resolve(null, Object(Phalcon\DI\FactoryDefault))
#9Phalcon\DI->get(dbSlave)
/var/www/html/ptmu/common/library/ModelsManager/ModelsManager.php (54)
<?php
 
namespace PTMU\ModelsManager;
 
class ModelsManager extends \Phalcon\Mvc\Model\Manager {
 
  /**
   * Returns the connection service name used to write data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @param string
   */
  public function getWriteConnectionService ($model) { 
    return "dbMaster";
  }
 
  /**
   * Returns the connection service name used to read data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @param string
   */
  public function getReadConnectionService ($model) { 
    return "dbSlave";
  }
  
  /**
   * Returns the connection service name used to read data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @param string
   */
  public function getSphinxConnectionService ($model) { 
    return "dbSphinx";
  }
  
  /**
   * Returns the connection to write data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @return \Phalcon\Db\AdapterInterface
   */
  public function getWriteConnection ($model) {
    return $this->getDI ()->get ($this->getWriteConnectionService ($model));
  }
 
  /**
   * Returns the connection to read data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @return \Phalcon\Db\AdapterInterface
   */
  public function getReadConnection ($model) { 
    return $this->getDI ()->get ($this->getReadConnectionService ($model));
  }
  
  /**
   * Returns the connection to read data related to a model
   *
   * @param \Phalcon\Mvc\ModelInterface $model
   * @return \Phalcon\Db\AdapterInterface
   */
  public function getSphinxConnection ($model) { 
    return $this->getDI ()->get ($this->getSphinxConnectionService ($model));
  }
}
#10PTMU\ModelsManager\ModelsManager->getReadConnection(Object(PTMU\Models\Locations: ))
#11Phalcon\Mvc\Model->getReadConnection()
#12Phalcon\Mvc\Model\Query->_executeSelect(Array([models] => Array([0] => PTMU\Models\Locations), [tables] => Array([0] => locations), [columns] => Array([pTMU\Models\Locations] => Array([type] => object, [model] => PTMU\Models\Locations, [column] => locations, [balias] => pTMU\Models\Locations)), [where] => Array([type] => binary-op, [op] => =, [left] => Array([type] => qualified, [domain] => locations, [name] => Code, [balias] => code), [right] => Array([type] => placeholder, [value] => :0)), [limit] => Array([number] => 1)), Array([0] => united-kingdom), null)
#13Phalcon\Mvc\Model\Query->execute(Array([0] => united-kingdom), null)
#14Phalcon\Mvc\Model::findFirst(Array([conditions] => code = ?0, [bind] => Array([0] => united-kingdom)))
#15Phalcon\Mvc\Model::__callStatic(findFirstByCode, Array([0] => united-kingdom))
/var/www/html/ptmu/common/library/Location/Location.php (89)
<?php
 
namespace PTMU\Location;
 
use Phalcon\Mvc\User\Component;
use PTMU\Models\Locations;
 
class Location extends Component {
  
  /**
   *
   * @var string
   */
  protected $_defaultLocation;
 
  /**
   * Constructor
   * 
   * @param string $defaultLocation
   */
  public function __construct ($_defaultLocation) {
    $this->_defaultLocation = strtolower ($_defaultLocation);
    
    // Set default location
    if (!$this->session->has ('location-identity')) {
      $this->setLocationByCode ($_defaultLocation);
    }
  }
 
  /**
   * Set language from model
   * 
   * @param \PTMU\Models\Languages $language
   * @return boolean
   */
  public function setLocation ($location) {
    if ($location instanceof \PTMU\Models\Locations) {
      $code = $location->getCode ();
      
      if ($this->getCode () == $code) {
        if ($this->config->logging->app) {
          $this->logger->log ("Location: location already set to '{$code}'");
        }
        
        return false;
      }
      
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location set to '{$code}'");
      }
      
      $metaData = $location->getMetaData ();
      
      $this->session->set ('location-identity', array(
        'id'             => $location->getLocationID (),
        'code'           => $code,
        'sorting'        => $location->getSorting (),
        'uri'            => isset ($metaData ['uri']) ? $metaData ['uri'] : '',
        'currencySymbol' => isset ($metaData ['currencySymbol']) ? $metaData ['currencySymbol'] : ''
      ));
      
      // Fire event afterSetLocation
      $eventManager = $this->getEventsManager ();
      if (isset ($eventManager)) {
        $eventManager->fire ("location:afterSetLocation", $this, $code, false);
      }
 
      return true;
    }
    
    return false;
  }
 
  /**
   * Set location by code
   * 
   * @param string $code
   * @return boolean
   */
  public function setLocationByCode ($code) {
    if ($this->getCode () == $code) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location already set to '{$code}'");
      }
      
      return false;
    }
    
    $location = Locations::findFirstByCode ($code);
    
    if ($location == false) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: not found location for code '{$code}'");
      }
      
      $code = $this->_defaultLocation;
    }
    
    return $this->setLocation ($location);
  }
 
  /**
   * Get location id
   * 
   * @return int
   */
  public function getID () {
    return intval ($this->getSessionAttribute ('id'));
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getCode () {
    return $this->getSessionAttribute ('code');
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getSorting () {
    return $this->getSessionAttribute ('sorting');
  }
 
  /**
   * Get currency symbol
   * 
   * @return string
   */
  public function getCurrencySymbol () {
    return $this->getSessionAttribute ('currencySymbol');
  }
 
  /**
   * Get uri
   * 
   * @return string
   */
  public function getUri () {
    return $this->getSessionAttribute ('uri');
  }
  
  /**
   * Return language attribute from session
   * 
   * @return variant
   */
  public function getSessionAttribute ($attribute) {
    $identity = $this->session->get ('location-identity');
    
    return isset ($identity [$attribute]) ? $identity [$attribute] : null;
  }
}
#16PTMU\Models\Locations::findFirstByCode(united-kingdom)
/var/www/html/ptmu/common/library/Location/Location.php (89)
<?php
 
namespace PTMU\Location;
 
use Phalcon\Mvc\User\Component;
use PTMU\Models\Locations;
 
class Location extends Component {
  
  /**
   *
   * @var string
   */
  protected $_defaultLocation;
 
  /**
   * Constructor
   * 
   * @param string $defaultLocation
   */
  public function __construct ($_defaultLocation) {
    $this->_defaultLocation = strtolower ($_defaultLocation);
    
    // Set default location
    if (!$this->session->has ('location-identity')) {
      $this->setLocationByCode ($_defaultLocation);
    }
  }
 
  /**
   * Set language from model
   * 
   * @param \PTMU\Models\Languages $language
   * @return boolean
   */
  public function setLocation ($location) {
    if ($location instanceof \PTMU\Models\Locations) {
      $code = $location->getCode ();
      
      if ($this->getCode () == $code) {
        if ($this->config->logging->app) {
          $this->logger->log ("Location: location already set to '{$code}'");
        }
        
        return false;
      }
      
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location set to '{$code}'");
      }
      
      $metaData = $location->getMetaData ();
      
      $this->session->set ('location-identity', array(
        'id'             => $location->getLocationID (),
        'code'           => $code,
        'sorting'        => $location->getSorting (),
        'uri'            => isset ($metaData ['uri']) ? $metaData ['uri'] : '',
        'currencySymbol' => isset ($metaData ['currencySymbol']) ? $metaData ['currencySymbol'] : ''
      ));
      
      // Fire event afterSetLocation
      $eventManager = $this->getEventsManager ();
      if (isset ($eventManager)) {
        $eventManager->fire ("location:afterSetLocation", $this, $code, false);
      }
 
      return true;
    }
    
    return false;
  }
 
  /**
   * Set location by code
   * 
   * @param string $code
   * @return boolean
   */
  public function setLocationByCode ($code) {
    if ($this->getCode () == $code) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location already set to '{$code}'");
      }
      
      return false;
    }
    
    $location = Locations::findFirstByCode ($code);
    
    if ($location == false) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: not found location for code '{$code}'");
      }
      
      $code = $this->_defaultLocation;
    }
    
    return $this->setLocation ($location);
  }
 
  /**
   * Get location id
   * 
   * @return int
   */
  public function getID () {
    return intval ($this->getSessionAttribute ('id'));
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getCode () {
    return $this->getSessionAttribute ('code');
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getSorting () {
    return $this->getSessionAttribute ('sorting');
  }
 
  /**
   * Get currency symbol
   * 
   * @return string
   */
  public function getCurrencySymbol () {
    return $this->getSessionAttribute ('currencySymbol');
  }
 
  /**
   * Get uri
   * 
   * @return string
   */
  public function getUri () {
    return $this->getSessionAttribute ('uri');
  }
  
  /**
   * Return language attribute from session
   * 
   * @return variant
   */
  public function getSessionAttribute ($attribute) {
    $identity = $this->session->get ('location-identity');
    
    return isset ($identity [$attribute]) ? $identity [$attribute] : null;
  }
}
#17PTMU\Location\Location->setLocationByCode(united-kingdom)
/var/www/html/ptmu/common/library/Location/Location.php (26)
<?php
 
namespace PTMU\Location;
 
use Phalcon\Mvc\User\Component;
use PTMU\Models\Locations;
 
class Location extends Component {
  
  /**
   *
   * @var string
   */
  protected $_defaultLocation;
 
  /**
   * Constructor
   * 
   * @param string $defaultLocation
   */
  public function __construct ($_defaultLocation) {
    $this->_defaultLocation = strtolower ($_defaultLocation);
    
    // Set default location
    if (!$this->session->has ('location-identity')) {
      $this->setLocationByCode ($_defaultLocation);
    }
  }
 
  /**
   * Set language from model
   * 
   * @param \PTMU\Models\Languages $language
   * @return boolean
   */
  public function setLocation ($location) {
    if ($location instanceof \PTMU\Models\Locations) {
      $code = $location->getCode ();
      
      if ($this->getCode () == $code) {
        if ($this->config->logging->app) {
          $this->logger->log ("Location: location already set to '{$code}'");
        }
        
        return false;
      }
      
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location set to '{$code}'");
      }
      
      $metaData = $location->getMetaData ();
      
      $this->session->set ('location-identity', array(
        'id'             => $location->getLocationID (),
        'code'           => $code,
        'sorting'        => $location->getSorting (),
        'uri'            => isset ($metaData ['uri']) ? $metaData ['uri'] : '',
        'currencySymbol' => isset ($metaData ['currencySymbol']) ? $metaData ['currencySymbol'] : ''
      ));
      
      // Fire event afterSetLocation
      $eventManager = $this->getEventsManager ();
      if (isset ($eventManager)) {
        $eventManager->fire ("location:afterSetLocation", $this, $code, false);
      }
 
      return true;
    }
    
    return false;
  }
 
  /**
   * Set location by code
   * 
   * @param string $code
   * @return boolean
   */
  public function setLocationByCode ($code) {
    if ($this->getCode () == $code) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: location already set to '{$code}'");
      }
      
      return false;
    }
    
    $location = Locations::findFirstByCode ($code);
    
    if ($location == false) {
      if ($this->config->logging->app) {
        $this->logger->log ("Location: not found location for code '{$code}'");
      }
      
      $code = $this->_defaultLocation;
    }
    
    return $this->setLocation ($location);
  }
 
  /**
   * Get location id
   * 
   * @return int
   */
  public function getID () {
    return intval ($this->getSessionAttribute ('id'));
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getCode () {
    return $this->getSessionAttribute ('code');
  }
 
  /**
   * Get location code
   * 
   * @return string
   */
  public function getSorting () {
    return $this->getSessionAttribute ('sorting');
  }
 
  /**
   * Get currency symbol
   * 
   * @return string
   */
  public function getCurrencySymbol () {
    return $this->getSessionAttribute ('currencySymbol');
  }
 
  /**
   * Get uri
   * 
   * @return string
   */
  public function getUri () {
    return $this->getSessionAttribute ('uri');
  }
  
  /**
   * Return language attribute from session
   * 
   * @return variant
   */
  public function getSessionAttribute ($attribute) {
    $identity = $this->session->get ('location-identity');
    
    return isset ($identity [$attribute]) ? $identity [$attribute] : null;
  }
}
#18PTMU\Location\Location->__construct(united-kingdom)
/var/www/html/ptmu/common/config/services.php (478)
<?php
 
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Logger\Adapter\File as LoggerAdapterFile;
use Phalcon\Logger\Adapter\Dummy as LoggerAdapterDummy;
use Phalcon\Logger\Adapter\Stream as StreamAdapter;
use Phalcon\Events\Manager as EventManager;
use Phalcon\Logger\Formatter\Line as LineFormatter;
use PTMU\Models\Taxonomy;
use PTMU\Models\Translations;
use PTMU\Models\Locations;
use Phalcon\Db\Profiler as DBProfiler;
use Phalcon\Cache\Multiple;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Logger as Logger;
use Phalcon\DI;
use PTMU\MDebuger\MDebuger;
use PTMU\SphinxApi\SphinxClient;
use PTMU\Utils\Utils;
 
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault ();
$loggers = array ();
 
/**
 * Register the configuration itself as a service
 */
$di->setShared ('config', $config);
                      
/**
 * Router
 */
$di->setShared ('router', function () use ($di) {
  return include (__DIR__ . "/routes.php");
});
 
/**
* Dispatcher use a default namespace
*/
$di->setShared ('dispatcher', function () use ($di) {
  $dispatcher = new Dispatcher ();       
  
  $eventsManager = new EventManager ();  
  
  $eventsManager->attach ("dispatch", function ($event, $dispatcher, $exception) use ($di) {
    if ($event->getType () == 'beforeNotFoundAction') { 
      $dispatcher->forward (array (
        'controller' => 'index',
        'action'     => 'route404'
      ));
      
      return false;
    }
    
    if ($event->getType() == 'beforeException') { 
      switch ($exception->getCode ()) {
        case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
        case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
          $dispatcher->forward (array (
            'controller' => 'index',
            'action'     => 'route404'
          ));
          
          return false;
      }
    }
  });  
  
  $dispatcher->setEventsManager ($eventsManager);
  
  return $dispatcher;
});
 
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->setShared ('url', function() use ($config) {
  $url = new UrlResolver();
  
  $url->setBaseUri($config->application->baseUri);
  
  return $url;
});
          
/**
* Setting up volt
*/
 $di->setShared ('volt', function ($view, $di) use ($config) {
  $volt = new VoltEngine ($view, $di);                        
  
  $options = array (
    'compiledPath'      => $config->application->voltDir,
    'compiledSeparator' => '_',
    'prefix'            => $config->cache->prefix
  );
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $options ['compileAlways'] = true;
  }
  
  $volt->setOptions ($options);
 
  return $volt;
});
  
/**
* Setting up the view component
*/
$di->setShared ('view', function() use ($di, $config) {
  $view = new View ();
 
  $view->registerEngines(array(
    '.volt' => 'volt',
    '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
  ));
 
  $view->setLayout ('inner');
  
  $debugMode = $di->get ('cookies')->get ('ptmu-debug-mode');  
  
  if (filter_var ($debugMode->getValue (), FILTER_VALIDATE_BOOLEAN)) {
    $eventsManager = new EventManager;
    
    $request = $di->getService ('request');
    
    $eventsManager->attach ("view", function ($event, $view) {
      if ($event->getType() == 'beforeRender') {
        MDebuger::$BeforeRender = (microtime (true) - APP_START_TIME);
      }
      
      if ($event->getType() == 'afterRender') {
        MDebuger::$AfterRender = (microtime (true) - APP_START_TIME);
        
        $profiler = '<div class="debug" style="color: black;text-align: left;"><br clear="all"/><div style="background-color:#EFEFEF; margin: 4px; padding: 4px; border: solid 1px #345487; text-align: center">Script Execution time: <b>' . MDebuger::$AfterRender . '</b> (Clear code: <b>' . (MDebuger::$AfterRender - MDebuger::$SqlTime - (( MDebuger::$AfterRender - MDebuger::$BeforeRender ))) . '</b>, Sphinx: <b>' . $time["sphinx"] . '</b>, SQL: <b>' . MDebuger::$SqlTime . '</b>, Rendering: <b>' . ( MDebuger::$AfterRender - MDebuger::$BeforeRender ) . '</b>) &nbsp; [ <b>' . MDebuger::$SqlCount . '</b> queries used ]&nbsp; [ <b>' . Utils::toHumanBytes (memory_get_usage ()) . '</b> used ]</div>';
        $profiler .= MDebuger::RenderSmall ();
        $view->setContent (str_replace ('<!--debug-->', $profiler, $view->getContent ()));
      }
    });
    
    $view->setEventsManager ($eventsManager);  
  }
  
  return $view;
});
 
/**
* Setting up the logger component
*/
$di->set ('fileLogger', function () use ($config) {
  $arguments   = func_get_args ();  
  $logfileName = isset ($arguments [0]) ? $arguments [0] : 'application';
  $dirName     = $config->application->logDir . date ('Ymd');  
  
  if (!is_dir ($dirName)) {
    umask (0);
    mkdir ($dirName, 0774);    
    umask (002);      
  }
  
  $logger = new LoggerAdapterFile ($dirName . "/{$logfileName}.log");
  $logger->setFormatter (new LineFormatter ("[%date%][%type%] %message%", "Y-m-d H:i:s O"));      
  
  return $logger;
});
 
/**
* Setting up the logger component
*/
$di->setShared ('logger', function () use ($di, $config) {
  if ($config->logging->app) {
    return $di->get ('fileLogger', 'application');
  } else {
    return new LoggerAdapterDummy ();
  }
});
 
 
/**
 * Setting up the sphinxApi component
 */
$di->set ('sphinxApi', function () use ($di, $config) {
   $cl = new PTMU\SphinxApi\SphinxClient ();
   
   $cl->SetServer ($config->database->sphinx->host, $config->database->sphinx->portApi);
   $cl->SetConnectTimeout (1);
   $cl->SetArrayResult (true);
 
  return $cl;
});
 
/**
* Database event manager
*/
$di->set ('dbEventManager', function() use ($config, $di) {
  $arguments      = func_get_args ();
  $logFileName    = isset ($arguments [0]) ? $arguments [0] : 'sql';
  $logger         = null;
  $profiler       = null;
  $sqlLogger      = null;
  $profilerLogger = null;
 
  $eventsManager = new EventManager (); 
  
  if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $profiler       = new DBProfiler ();        
    $profilerLogger = $di->get ('fileLogger', array ("{$logFileName}_profiler"));
  }
  
  if ($config->logging->sql) {
    $sqlLogger = $di->get ('fileLogger', array ($logFileName));
  }
 
  //Listen all the database events
  $eventsManager->attach ("db", function ($event, $connection) use ($sqlLogger, $profilerLogger, $config, $profiler, $logFileName) {
    if ($event->getType () == 'beforeQuery') {
      if ($config->logging->sql) {
        $sqlVariables = $connection->getSqlVariables();          
        
        if (is_array ($sqlVariables)) {
          $sqlLogger->log ($connection->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']', Logger::DEBUG);
        } else {
          $sqlLogger->log ($connection->getSQLStatement (), Logger::DEBUG);            
        }
      }                                                   
      if ($config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
        $profiler->startProfile ($connection->getSQLStatement ());
      }
    }
    
    if ($event->getType () == 'afterQuery') {      
      if ($config->logging->sqlProfiler) {
        $profiler->stopProfile();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables();                  
 
        if (is_array ($sqlVariables)) {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Params: ' . join (', ', $sqlVariables) . ']' . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        } else {
          $profilerLogger->log ($profile->getSQLStatement () . ' [Elapsed time: ' . $profile->getTotalElapsedSeconds () . ']', Logger::DEBUG);          
        }
      }  
      
      if( $config->logging->sqlProfilerWeb ){
        $profiler->stopProfile ();
        
        $profile      = $profiler->getLastProfile ();
        $sqlVariables = $connection->getSqlVariables (); 
        
        MDebuger::$SqlLog [] = array (
          "query"    => $connection->getSQLStatement (),
          "time"     => $profile->getTotalElapsedSeconds(),
          "serverdb" => (strpos ($connection->getSQLStatement (), 'spx_') !== false ? 'sphinx' : $logFileName),
          "heavy"    => intval($profile->getTotalElapsedSeconds() > 0.1),
          "total"    => 1
        );
        
        MDebuger::$SqlTime += $profile->getTotalElapsedSeconds ();
        MDebuger::$SqlCount++;
      }
    }
  });
  
  return $eventsManager;
});
 
/**
* Master database connection
*/
$di->set ('dbMaster', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->master->host,
    'port'       => $config->database->master->port,
    'username'   => $config->database->master->username,
    'password'   => $config->database->master->password,
    'dbname'     => $config->database->master->dbname,
    'charset'    => $config->database->master->charset,
    'persistent' => $config->database->master->persistent
  ));
  
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_master')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSlave', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->slave->host,
    'port'       => $config->database->slave->port,
    'username'   => $config->database->slave->username,
    'password'   => $config->database->slave->password,
    'dbname'     => $config->database->slave->dbname,
    'charset'    => $config->database->slave->charset,
    'persistent' => $config->database->slave->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sql_slave')));
  }
  
  return $connection;
});
 
/**
* Slave database connection
*/
$di->set ('dbSphinx', function() use ($config, $di) {
  $connection = new DbAdapter (array (
    'host'       => $config->database->sphinx->host,
    'port'       => $config->database->sphinx->port,
    'charset'    => $config->database->sphinx->charset,
    'persistent' => $config->database->sphinx->persistent    
  ));
 
  if ($config->logging->sql || $config->logging->sqlProfiler || $config->logging->sqlProfilerWeb) {
    $connection->setEventsManager ($di->get ('dbEventManager', array ('sphinx')));
  }
  
  return $connection;
});
 
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set ('modelsMetadata', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Mvc\Model\Metadata\Memory ();
  } else {
    return new \Phalcon\Mvc\Model\MetaData\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->cache->lifetime,
    ));
  }
});
 
/**
* Start the session the first time some component request the session service
*/
$di->set ('session', function () use ($config) {
  session_set_cookie_params (0, $config->application->baseUri, '.' . $config->application->mainDomain);
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $session = new \Phalcon\Session\Adapter\Files ();
  } else {
    $session = new \Phalcon\Session\Adapter\Memcache (array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
      'lifetime'   => $config->session->lifetime,      
      'cookie'     => array ('domain' => '.' . $config->application->mainDomain)
    ));
  } 
  
  $session->start ();
  
  return $session;
});
 
/**
* Setting up the cache
*/
$di->setShared ('viewCache', function () use ($config) {
  $frontCache = new \Phalcon\Cache\Frontend\Output (array (
    'lifetime' => $config->cache->lifetime,
  ));
  
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    return new \Phalcon\Cache\Backend\File ($frontCache, array (
      'cacheDir' => $config->application->cacheDir . 'view/',    
      'prefix'   => $config->cache->prefix,    
    ));
  } else {  
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new $adapterClass ($frontCache, array (
      'host'       => $config->cache->memcache->host,
      'port'       => $config->cache->memcache->port,
      'persistent' => $config->cache->memcache->persistent,            
      'prefix'     => $config->cache->prefix,
    ));
  }
});
 
/**
* Setting up the cache
*/
$di->setShared ('cache', function () use ($config) {
  if (APPLICATION_ENV == DEVELOPMENT_ENV) {
    $frontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->lifetime,
    ));
 
    return new \Phalcon\Cache\Backend\Memory ($frontCache);
  } else {  
    $apcFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->apc->lifetime,
    ));
    
    $memcacheFrontCache = new \Phalcon\Cache\Frontend\Data (array (
      'lifetime' => $config->cache->memcache->lifetime,
    ));
    
    $adapterClass = '\Phalcon\Cache\Backend\\' . $config->cache->memcache->adapter; 
    
    return new Multiple (array (
      new \Phalcon\Cache\Backend\Apc ($apcFrontCache, array (
        'prefix' => $config->cache->prefix,
      )),
      
      new $adapterClass ($memcacheFrontCache, array (
        'host'       => $config->cache->memcache->host,
        'port'       => $config->cache->memcache->port,
        'persistent' => $config->cache->memcache->persistent,            
        'prefix'     => $config->cache->prefix,
      ))
    ));
  }
});
 
/**
* Setting up the models cache
*/
$di->setShared ('modelsCache', function () use ($di) {
  return $di->getCache ();
});
 
/**
* Setting up the models manager
*/
$di->setShared ('modelsManager', function () use ($di) {
  return new \PTMU\ModelsManager\ModelsManager ();
});
 
/**
 * Custom authentication component
 */
$di->setShared ('auth', function(){
  return new \PTMU\Auth\Auth ();
});
 
/**
* Setting up the authentication component
*/
$di->setShared ('lang', function () use ($di, $config) {
  $eventsManager = new EventManager ();   
  $language      = new \PTMU\Lang\Lang ($config->application->defaults->language);
 
  $eventsManager->attach ("language:afterSetLanguage", function ($event, $component, $code) {
    // Reload translations
    Translations::load (true);
  });
  
  $language->setEventsManager ($eventsManager);
  
  return $language;
});
 
/**
* Setting up the language component
*/
$di->setShared ('location', function () use ($config) {
  $eventsManager = new EventManager (); 
  $location      = new \PTMU\Location\Location ($config->application->defaults->country);
  
  $eventsManager->attach ("location:afterSetLocation", function ($event, $component, $code) {
    // Reload taxonomy
    Taxonomy::load (true);
    
    // Reload locations
    Locations::load (true);
  });
  
  $location->setEventsManager ($eventsManager);
  
  return $location;
});
 
/**
* Setting up forms manager
*/
$di->setShared ('formsManager', function () use ($di) {
  return new \PTMU\Forms\Manager ();
});
 
/**
* Setting up flash service
*/
$di->setShared ('flash', function () {
  return new \Phalcon\Flash\Direct ();
});
 
/**
* Setting up sendmail service
*/
$di->setShared ('mail', function () use ($config) {
  return new \Zend\Mail\Transport\Sendmail ();
});
 
/**
* Setting up cookies service
*/
$di->set('cookies', function() {
  $cookies = new Phalcon\Http\Response\Cookies ();
  $cookies->useEncryption (false);
  
  return $cookies;
});
#19{closure}()
#20Phalcon\DI\Service->resolve(null, Object(Phalcon\DI\FactoryDefault))
#21Phalcon\DI->get(location, null)
#22Phalcon\DI->getShared(location)
#23Phalcon\DI\Injectable->__get(location)
/var/www/html/ptmu/frontend/controllers/IndexController.php (217)
<?php
 
namespace PTMU\Frontend\Controllers;
 
use Phalcon\Mvc\View;
use PTMU\Models\SearchSeo;
use PTMU\Taxonomy;
use PTMU\Taxonomy\AdStatus as AdStatus;
use PTMU\Taxonomy\Gender as Gender;
use PTMU\Taxonomy\AdCategories as AdCategory;
use PTMU\Taxonomy\AdAvailability as AdAvailability;
use PTMU\Taxonomy\UserStatus;
use PTMU\Models\Taxonomy as TaxonomyModel;
use PTMU\Models\Locations as LocationsModel;
use PTMU\Models\Users as Users;
use PTMU\Models\UserDetails as UserDetails;
use PTMU\Models\LocationsSeo;
use PTMU\Taxonomy\LocationType;
use PTMU\Pages\SummaryHelper;
use PTMU\Utils\Utils;
 
class IndexController extends ControllerBase {
 
  /**
   * @var integer
   */
  protected $category;
  
  /**
   * @var integer
   */
  protected $gender;
  
  /**
   * @var integer
   */
  protected $availability;
 
  /**
   * @var string
   */
  protected $locationCode;
  
  /**
   * @var integer
   */
  public $currentLocation;
  
  /**
   * @var integer
   */
  public $rootLocationID;
 
  /**
   * @var bool
   */
  public $allCitiesPage;
  
  /**
   * @var integer
   */
  protected $page;
  
  /**
   * @var integer
   */
  protected $params;
 
  /**
   * @var integer
   */
  public $storedLocation;
 
  /**
   * @var sting
   */
  public $metaParts;
  
  /**
   * @var array
   */
  public $paging;
 
  /**
   * @var array
   */
  public $taxonomyTree;
 
  /**
   * @var \PTMU\Models\SeoSearch
   */
  public $popularSearch;
  
  /**
   * Controller initialization
   */
  public function initialize () {
    $this->taxonomyTree  = TaxonomyModel::getTaxonomyAsTree ();    
    $this->popularSearch = null;
  }
  
  /**
   * all-cities action
   */
  public function allCitiesAction () {
    $this->locationCode = 'all-cities';
 
    $this->initAction ();
    $this->indexRedirects ();
    
    $this->generateAdsSearchFilters ();
 
    $pageHelper = new SummaryHelper ($this->getReadConnection (), $this->params, $this->page);
 
    $this->view->pick (["index/allCities"]);
 
    $this->view->setVar ('urlWOCity', $pageHelper->getRewriteUri ($this->page, 'all-cities'));
    $this->view->setVar ('cities',    $pageHelper->getSortedCities ($this->config->pages->summary->topCitiesCount, $this->category, $this->gender));
    $this->view->setVar ('countKey',  Utils::getCounterKey ($this->category, $this->gender));
    $this->view->setVar ('metaParts', $this->metaParts);
 
    $this->view->setVar ('pageTitle',       sprintf ($this->translations ['all-cities-page-title'], $this->metaParts));
    $this->view->setVar ('metaDescription', sprintf ($this->translations ['all-cities-page-meta'],  $this->metaParts));
  }
 
  /**
   * index action
   */
  public function indexAction () {
    $this->locationCode = $this->getDispatcherParam ('location', 'string', null);
 
    $this->initAction ();
    $this->indexRedirects ();
 
    if ($this->searchSeoID){
      $this->popularSearchInit ();
    }
 
    // Generate page
    $pageHelper = new SummaryHelper ($this->getReadConnection (), $this->params, $this->page);
    
    $results = $pageHelper->extendedSearch (false, array (
      'page'=> $this->page
    ));
    
    $ads = $pageHelper->generateAdsByIDs ([], $results ['ids']);
 
    $this->paging = $pageHelper->generateAdsPagingCommon (array (
      'maximumPages'  => $this->config->pages->summary->maximumPages,
      'itemsPerPage'  => $this->config->pages->summary->itemsPerPage,
      'pagesToShow'   => $this->config->pages->summary->pagesToShow,
    ));
    
    if ($this->page > $this->paging ['totalPages']) {
      if (!$this->paging ['totalPages'] && !empty ($this->locationCode)) {
        return $this->response->redirect ($pageHelper->getRewriteUri ($this->page, $this->locationCode), true, 301);
      } else {
        $this->forwardToNotFound ();
      }
    }
    
    $this->generateAdsSearchFilters ();
    $this->setVariablesInView ();
    $this->setPagingInView ();
    $this->setAdvancedSearchLinkInView ();
    $this->setBreadcrumbsInView ($pageHelper);
    $this->setMetaInView ();
 
    $this->view->pick (["index/index"]);
 
    // JS assets
    $this->_jsAssets [] = 'summary';
    
    // Set variables in view
    $this->view->setVar ('ads',            $ads ['ads']);
    $this->view->setVar ('cities',         $pageHelper->getSortedCities ($this->config->pages->summary->topCitiesCount, $this->category, $this->gender));
    $this->view->setVar ('urlWOCity',      $pageHelper->getRewriteUri ($this->page, $this->locationCode, $this->popularSearch));
    $this->view->setVar ('urlFromRequest', $pageHelper->getRewriteUri ($this->page, null, $this->popularSearch));
    $this->view->setVar ('jsAssets',       $this->_jsAssets);
 
    if ($this->config->logging->app) {
      $this->getDI ()->getLogger ()->log ("afterQuery: " . (microtime (true) - APP_START_TIME));
    }
  }
 
  /**
   * Initialize class variables for popular search
   */
  public function popularSearchInit () {
    $this->popularSearch = SearchSeo::findFirstBySearchSeoID ($this->searchSeoID);
    
    if (is_null ($this->popularSearch->getLocationID ())) {
      $this->popularSearch->setLocationName ($this->storedLocation ['name']);
    }
    
    if (!$this->popularSearch){
      $redirectHelper = new SummaryHelper ($this->getReadConnection (), $this->params, $this->page);
      return $this->response->redirect ($redirectHelper->getRewriteUri ($this->page), true, 301);
    }
 
    $params = array ();
    
    parse_str (parse_url (trim ($this->popularSearch->getSearchUrl ()))['query'], $params);
    
    $this->params = array_merge ($params, $this->params);
  }
 
  /**
   * Initialize class variables 
   */
  protected function initAction () {
    $this->category        = $this->getDispatcherParam ('category',     'int', AdCategory::ESCORTS);
    $this->gender          = $this->getDispatcherParam ('gender',       'int', Gender::GENDER_FEMALE);
    $this->availability    = $this->getDispatcherParam ('availability', 'int', AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS);
    $this->searchSeoID     = $this->getDispatcherParam ('seo',          'int', 0);
    $this->page            = $this->getDispatcherParam ('page',         'int', 1);
    $this->currentLocation = $this->location->getID ();
    $this->rootLocationID  = $this->currentLocation;
    $this->allCitiesPage   = strcasecmp ($this->locationCode, 'all-cities') == 0;
 
    if (!empty ($this->locationCode) && !$this->allCitiesPage) {
      if ($this->location->getCode () == $this->locationCode) {
        $this->rootLocationID = null;
      }
 
      $this->currentLocation = LocationsModel::getLocationIDByCode ($this->rootLocationID, $this->locationCode);
    }
    
    // Get stored location
    $this->storedLocation = LocationsModel::getLocation ($this->currentLocation, false);          
 
    // Get age ranges from session
    if (!$this->_mobileApplication) {
      $ageRange = $this->session->get ('summary-page-age', array (
        'ageFrom' => null,
        'ageTo'   => null
      ));
    }
 
    $this->params = array (
      'el_category' => $this->category,
      'el_gender'   => $this->gender,
      'el_location' => $this->currentLocation,
    );
  }
 
  /**
   * Set advanced search link in view
   */
  protected function setAdvancedSearchLinkInView () {
    $params = array ();
    
    foreach ($this->params as $key => $value) {
      if (($key == 'el_location') && ($value <= 1)) {
        continue;
      }
      
      if (mb_strlen ($value)) {
        $params [$key] = $value;
      }
    }
    
    $this->view->setVar ('advanced_search_link', '/search?' . http_build_query ($params));    
  }
  
  /**
   * Set class dependency variables in view
   */
  protected function setVariablesInView () {
    $this->view->setVar ('urlLocationCode',    trim ($this->locationCode));
    $this->view->setVar ('storedLocation',     $this->storedLocation);
    $this->view->setVar ('storedLocationPath', LocationsModel::getLocationPath ($this->currentLocation));
    $this->view->setVar ('currentCountry',     LocationsModel::getLocationPath ($this->currentLocation, LocationType::COUNTRY)[0]);
    $this->view->setVar ('countries',          LocationsModel::getCountries (null, false));
    $this->view->setVar ('megalopolisTaxID',   LocationType::MEGALOPOLIS);
    $this->view->setVar ('countryTaxID',       LocationType::COUNTRY);
    $this->view->setVar ('stateTaxID',         LocationType::STATE);
    $this->view->setVar ('taxFemale',          Gender::GENDER_FEMALE);
    $this->view->setVar ('taxIncOutc',         AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS);
    $this->view->setVar ('countKey',           Utils::getCounterKey ($this->category, $this->gender));
    $this->view->setVar ('mobileVersion',      Utils::getVersionVar ());
    $this->view->setVar ('isPopularSearch',    ($this->searchSeoID > 0));    
    
    $this->view->setVar ("parentLocationsTaxIDs", array (
      LocationType::TOWN        => LocationType::TOWN,
      LocationType::CITY        => LocationType::CITY,
      LocationType::MEGALOPOLIS => LocationType::MEGALOPOLIS,
    ));
 
    $this->view->setVar ("locationsLvl1TaxIDs", array (
      LocationType::CITY        => LocationType::CITY,
      LocationType::MEGALOPOLIS => LocationType::MEGALOPOLIS,
    ));
  }
 
  /**
   * Set paging in view
   */
  protected function setPagingInView () {
    $this->view->setVar ('currentPage', $this->paging ['currentPage']);
    $this->view->setVar ('totalFound',  $this->paging ['totalFound']);
    $this->view->setVar ('totalPages',  $this->paging ['totalPages']);
    $this->view->setVar ('location',    $this->paging ['location']);
    $this->view->setVar ('pages',       $this->paging ['pages']);
    
    $this->setPagingMeta ();
  }
  
  /**
   * Set paging meta in view
   */
  protected function setPagingMeta () {
    if (!$this->paging ['totalFound']) return;
    
    $locationUri = $this->location->getUri ();
      
    if ($this->paging ['currentPage'] == 2) {
      $this->view->setVar ('prevLink', sprintf ('http://www.%s%s', $locationUri, $this->paging ['location']));
    }
 
    if ($this->paging ['currentPage'] > 2) {
      $this->view->setVar ('prevLink', sprintf ('http://www.%s%s/%s', $locationUri, $this->paging ['location'], $this->paging ['currentPage'] - 1));
    }
 
    if ($this->paging ['currentPage'] < $this->paging ['totalPages']) {
      $this->view->setVar ('nextLink', sprintf ('http://www.%s%s/%s', $locationUri, $this->paging ['location'], $this->paging ['currentPage'] + 1));
    }
  }
  
  /**
   * Initialize meta parts
   */
  protected function initMetaParts () {
    $this->metaParts = [];    
    
    if ($this->gender != Gender::GENDER_FEMALE) {
      $this->metaParts [] = $this->view->getVar ('requestData')['GENDER']['name'];
    }
    
    $this->metaParts [] = $this->view->getVar ('requestData')['AD_CATEGORIES']['name'];
    $this->metaParts = implode (' ', $this->metaParts);
  }
  
  /**
   * process redirects for index action
   */
  protected function indexRedirects () {
    $rewriteUri = $this->router->getRewriteUri ();
 
    // Prevent reaching all cities page without refferer
    if ($this->allCitiesPage && preg_match ('[incalls|outcalls]', $rewriteUri)) {
      $referrer   = $this->request->getHTTPReferer ();
      $rewriteUri = str_replace (array ('incalls-', 'outcalls-' ), '', $rewriteUri);
 
      if (!mb_strlen ($referrer)) {
        return $this->response->redirect (substr ($rewriteUri, strlen ($this->url->getBaseUri ()), -11) . '/all-cities', false, 301);
      }
    }
    
    // page 1 redirect
    if ($this->page == 1 and substr ($rewriteUri, -1, 1) == $this->page) {
      return $this->response->redirect (substr ($rewriteUri, 0, strlen ($rewriteUri) - 2), true, 301);
    }
 
    //@ToDo remove when google reindex pages
    if (strcasecmp ($this->locationCode, 'central') == 0) {
      $rewriteUri = str_replace ('central', 'central-london', $rewriteUri);
 
      return $this->response->redirect (substr ($rewriteUri, strlen ($this->url->getBaseUri ())));
    }
 
    // redirect if any incall/outcall provided
    if ($this->availability != AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS) {
      $categoryName = Utils::getCategoryNameByID ($this->category);
      $newUri       = '/' . $categoryName;
 
      if (!empty ($this->locationCode)) {
        $locationID    = LocationsModel::getLocationIDByCode ($this->rootLocationID, $this->locationCode);
        $locationArray = LocationsModel::getLocation ($locationID);
        
        if (in_array ($locationArray ['locationTypeID'], array (LocationType::CITY, LocationType::TOWN, LocationType::MEGALOPOLIS))) {
          $newUri .= '/' . $locationArray ['code'];
        } 
        
        if (in_array ($locationArray ['locationTypeID'], array (LocationType::CITY_PART, LocationType::NEIGHBOURHOOD))) {
          $locationPath = LocationsModel::getLocationPath ($locationID);
          $newUri .= '/' . $locationPath [0]['code'];
        }
      }
 
      return $this->response->redirect ($newUri, true, 301);
    }
    
    $maximumPages = $this->config->pages->summary->maximumPages;
    
    if ($this->_mobileApplication) {
      $maximumPages = $this->config->mobilePages->summary->maximumPages;
    }
    
    // Forward to not found page if information is not valid
    if (($this->page > $maximumPages) || empty ($this->category) || (empty ($this->currentLocation) && !$this->allCitiesPage)) {
      return $this->forwardToNotFound ();
    }
    
    // Redirect for preventing resubmit form on back action
    if ($this->request->isPost () || ($rewriteUri != $this->router->getRewriteUri ())) {
      return $this->response->redirect (substr ($rewriteUri, strlen ($this->url->getBaseUri ())));
    }
  }
 
  /**
   * Set breadcrumbs in view
   * 
   * @param array $breadcrumbs
   */
  protected function setBreadcrumbsInView ($pageHelper) {
    $tilte = ($this->searchSeoID && $this->popularSearch) ? $this->popularSearch->getAnchor () : null;
    
    $this->view->setVar ('breadcrumbs', $pageHelper->getBreadcrumb ($tilte));
  }
 
  /**
   * Set meta in view
   */
  protected function setMetaInView () {
    if ($this->searchSeoID && $this->popularSearch) {
      $this->setMetaDynamic ($this->popularSearch);
      $this->setSearchAnchors (true);      
    } else {
      $this->setSeoText ();
      $this->setSearchAnchors (false);
      $this->setMeta ();
    }
  }
  
  /**
   * Set meta tags
   */
  protected function setMeta () {
    $category = Utils::getCategoryTranslations ($this->category, $this->translations);
    $gender   = Utils::getGenderTranslations ($this->gender, $this->translations);
    $prefix   = '';
    
    if ($this->_mobileApplication) {
      $prefix = 'mobile-';
    }
    
    if (!empty ($this->locationCode)) {
      if ($this->page == 1) {
        $this->view->setVar ('pageTitle',       sprintf ($this->translations [$prefix . 'summary-page-title'], $this->storedLocation ['name'], $gender->nameSEO, $category->name, $gender->name, $category->nameSingular, $this->storedLocation ['name']));
        $this->view->setVar ('metaDescription', sprintf ($this->translations [$prefix . 'summary-page-meta-in'], $this->metaParts, $this->storedLocation ['name']));
      } else {
        $this->view->setVar ('pageTitle',       sprintf ($this->translations [$prefix . 'summary-page-title-page'], $this->storedLocation ['name'], $gender->nameSEO, $category->name, $gender->name, $category->nameSingular, $this->storedLocation ['name'], $this->page));
        $this->view->setVar ('metaDescription', sprintf ($this->translations [$prefix . 'summary-page-meta-in-page'], $this->metaParts, $this->storedLocation ['name'], $this->page));
      }
    } else {
      if ($this->page == 1) {
        $this->view->setVar ('pageTitle',       sprintf ($this->translations [$prefix . 'summary-page-title-no-city'], $gender->nameSEO, $category->name, $gender->name, $category->nameSingular));
        $this->view->setVar ('metaDescription', sprintf ($this->translations [$prefix . 'summary-page-meta'], $this->metaParts));
      } else {
        $this->view->setVar ('pageTitle',       sprintf ($this->translations [$prefix . 'summary-page-title-no-city-page'], $gender->nameSEO, $category->name, $gender->name, $category->nameSingular, $this->page));
        $this->view->setVar ('metaDescription', sprintf ($this->translations [$prefix . 'summary-page-meta-page'], $this->metaParts, $this->page));
      }
    }
 
    $this->view->setVar ('searchMeta', $this->metaParts);
  }
 
  /**
   * Set meta tags
   */
  protected function setMetaDynamic ($popularSerach) {
    $metaTitle       = trim ($popularSerach->getMetaTitle ());
    $metaDescription = trim ($popularSerach->getMetaDescription ());
    
    if ($this->page > 1) {
      if ($metaTitle [mb_strlen ($metaTitle) - 1] == '.') {
        $metaTitle = substr ($metaTitle, 0, -1);
      }
 
      if ($metaDescription [mb_strlen ($metaDescription) - 1] == '.') {
        $metaDescription = substr ($metaDescription, 0, -1);
      }
      
      $metaTitle       = sprintf ($this->translations ['summary-page-title-popular'], $metaTitle, $this->page);
      $metaDescription = sprintf ($this->translations ['summary-page-meta-popular'], $metaDescription, $this->page);
    }
    
    $this->view->setVar ('pageTitle',       $metaTitle);
    $this->view->setVar ('metaDescription', $metaDescription);
    $this->view->setVar ('h1',              $popularSerach->getH1 ());
    $this->view->setVar ('h2',              $popularSerach->getH2 ());
    $this->view->setVar ("seoText",         $popularSerach->getSeoText () );
  }
 
  /**
   * Set SEO text
   */
  protected function setSeoText () {
    if (!$this->currentLocation || !$this->gender || !$this->category) return;
 
    $res = LocationsSeo::findFirst (
      array (
        "conditions" => "locationID = :locationID: AND genderID = :genderID: AND categoryID = :categoryID:",
 
        "bind" => array (
          "locationID"  => $this->currentLocation,
          "genderID"    => $this->gender,
          "categoryID"  => $this->category
        )
      )
    );
    
    $this->view->setVar ("seoText", $res?$res->getSeoText():null);
  }
 
  /**
   * Set Popular Search Links
   * 
   * @param boolean $childLinks
   */
  protected function setSearchAnchors ($childLinks = false) {
    if (!$this->currentLocation || !$this->gender || !$this->category) return;
    
    $locationID    = $this->currentLocation;
    $searchAnchors = null;    
 
    if ($childLinks) {
      $location   = LocationsModel::getLocation ($this->currentLocation);
      $locationID = array ();
      
      if (isset ($location ['childs'])) {
        array_walk_recursive ($location, function ($value, $key) use (&$locationID) { 
          if (($key == 'locationID') && ($value != $this->currentLocation)) {
            $locationID [] = $value; 
          }
        });    
      }
    }
    
    $searchUrl = $childLinks ? $this->popularSearch->getSortedSearchQuery () : null;
    
    if ($locationID || (is_array ($locationID) && count ($locationID))) {
      $searchAnchors = SearchSeo::getSearchSeoByCriterias ($locationID, $this->category, $this->gender, $searchUrl);
    }
    
    $this->view->setVar ("searchAnchors", $searchAnchors);
  }
 
  /**
   * Generate search filters for ads
   */
  protected function generateAdsSearchFilters () {
    $controlsData = array ();
    $taxonomySet  = array ();
    
    foreach ($this->taxonomyTree as $treeItem) {
      if (isset ($treeItem ['taxonomyID']) && in_array ($treeItem ['taxonomyID'], [Taxonomy::AD_CATEGORIES, Taxonomy::GENDER, Taxonomy::AD_AVAILABILITY, Taxonomy::AGE])) {
        $controlsData [$treeItem ['code']] = array (
          'caption' => $treeItem ['name'],
          'items'   => array (),
          'type'    => 'select',          
        );
 
        if (!isset ($treeItem ['childs'])) {
          $range = $treeItem ['metaData']['range'];
 
          $controlsData [$treeItem ['code']] = array (
            'caption'     => $treeItem ['name'],
            'from'        => $range ['from'],
            'to'          => $range ['to'],
            'defaultFrom' => $range ['defaultFrom'],
            'defaultTo'   => $range ['defaultTo'],
            'type'        => 'range',            
          );
        } else {
          foreach ($treeItem ['childs'] as &$childItem) {
            // Replace translations
            $code = $childItem ['code'];
 
            if (isset ($this->translations ["summary-filter::{$code}"])) {
              $childItem ['name'] = $this->translations ["summary-filter::{$code}"];
            }
 
            if (in_array ($childItem ['taxonomyID'], AdCategory::getMembers ())) {
              $childItem ['attachExtraInfo'] = $childItem ['taxonomyID'] != AdCategory::MASSAGE;
            }
            
            if (in_array ($childItem ['taxonomyID'], Gender::getMembers ())) {
              $childItem ['enabled'] = $this->storedLocation [Utils::getCounterKey ($this->category, $childItem ['taxonomyID'])] > 0;
            }
 
            $taxonomySet [$childItem ['taxonomyID']] = $childItem;
            $controlsData [$treeItem ['code']]['items'][] = $childItem;
          }
        }
      }
    }
 
    // Get age ragnges from session
    if ($this->_mobileApplication) {
      $ageRange = $this->session->get ('summary-page-age', array (
        'ageFrom' => $this->config->pages->summary->defaultAgeRange->ageFrom, 
        'ageTo'   => $this->config->pages->summary->defaultAgeRange->ageTo
      ));
    } else {
      $ageRange = $this->session->get ('summary-page-age');
    } 
    
    // Set variables in view
    $this->view->setVar ("sessionAgeRange", $ageRange);
    $this->view->setVar ("controlsData",    $controlsData);
 
    // Set request data variables in view        
    $this->view->setVar ("requestData", array (
      'AD_CATEGORIES'   => $taxonomySet [$this->getDispatcherParam ('category',     'int', AdCategory::ESCORTS)],
      'GENDER'          => $taxonomySet [$this->getDispatcherParam ('gender',       'int', Gender::GENDER_FEMALE)],
      'AD_AVAILABILITY' => $taxonomySet [$this->getDispatcherParam ('availability', 'int', AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS)]
    ));
 
    $this->initMetaParts ();    
  }
}
#24PTMU\Frontend\Controllers\IndexController->initAction()
/var/www/html/ptmu/frontend/controllers/IndexController.php (132)
<?php
 
namespace PTMU\Frontend\Controllers;
 
use Phalcon\Mvc\View;
use PTMU\Models\SearchSeo;
use PTMU\Taxonomy;
use PTMU\Taxonomy\AdStatus as AdStatus;
use PTMU\Taxonomy\Gender as Gender;
use PTMU\Taxonomy\AdCategories as AdCategory;
use PTMU\Taxonomy\AdAvailability as AdAvailability;
use PTMU\Taxonomy\UserStatus;
use PTMU\Models\Taxonomy as TaxonomyModel;
use PTMU\Models\Locations as LocationsModel;
use PTMU\Models\Users as Users;
use PTMU\Models\UserDetails as UserDetails;
use PTMU\Models\LocationsSeo;
use PTMU\Taxonomy\LocationType;
use PTMU\Pages\SummaryHelper;
use PTMU\Utils\Utils;
 
class IndexController extends ControllerBase {
 
  /**
   * @var integer
   */
  protected $category;
  
  /**
   * @var integer
   */
  protected $gender;
  
  /**
   * @var integer
   */
  protected $availability;
 
  /**
   * @var string
   */
  protected $locationCode;
  
  /**
   * @var integer
   */
  public $currentLocation;
  
  /**
   * @var integer
   */
  public $rootLocationID;
 
  /**
   * @var bool
   */
  public $allCitiesPage;
  
  /**
   * @var integer
   */
  protected $page;
  
  /**
   * @var integer
   */
  protected $params;
 
  /**
   * @var integer
   */
  public $storedLocation;
 
  /**
   * @var sting
   */
  public $metaParts;
  
  /**
   * @var array
   */
  public $paging;
 
  /**
   * @var array
   */
  public $taxonomyTree;
 
  /**
   * @var \PTMU\Models\SeoSearch
   */
  public $popularSearch;
  
  /**
   * Controller initialization
   */
  public function initialize () {
    $this->taxonomyTree  = TaxonomyModel::getTaxonomyAsTree ();    
    $this->popularSearch = null;
  }
  
  /**
   * all-cities action
   */
  public function allCitiesAction () {
    $this->locationCode = 'all-cities';
 
    $this->initAction ();
    $this->indexRedirects ();
    
    $this->generateAdsSearchFilters ();
 
    $pageHelper = new SummaryHelper ($this->getReadConnection (), $this->params, $this->page);
 
    $this->view->pick (["index/allCities"]);
 
    $this->view->setVar ('urlWOCity', $pageHelper->getRewriteUri ($this->page, 'all-cities'));
    $this->view->setVar ('cities',    $pageHelper->getSortedCities ($this->config->pages->summary->topCitiesCount, $this->category, $this->gender));
    $this->view->setVar ('countKey',  Utils::getCounterKey ($this->category, $this->gender));
    $this->view->setVar ('metaParts', $this->metaParts);
 
    $this->view->setVar ('pageTitle',       sprintf ($this->translations ['all-cities-page-title'], $this->metaParts));
    $this->view->setVar ('metaDescription', sprintf ($this->translations ['all-cities-page-meta'],  $this->metaParts));
  }
 
  /**
   * index action
   */
  public function indexAction () {
    $this->locationCode = $this->getDispatcherParam ('location', 'string', null);
 
    $this->initAction ();
    $this->indexRedirects ();
 
    if ($this->searchSeoID){
      $this->popularSearchInit ();
    }
 
    // Generate page
    $pageHelper = new SummaryHelper ($this->getReadConnection (), $this->params, $this->page);
    
    $results = $pageHelper->extendedSearch (false, array (
      'page'=> $this->page
    ));
    
    $ads = $pageHelper->generateAdsByIDs ([], $results ['ids']);
 
    $this->paging = $pageHelper->generateAdsPagingCommon (array (
      'maximumPages'  => $this->config->pages->summary->maximumPages,
      'itemsPerPage'  => $this->config->pages->summary->itemsPerPage,
      'pagesToShow'   => $this->config->pages->summary->pagesToShow,
    ));
    
    if ($this->page > $this->paging ['totalPages']) {
      if (!$this->paging ['totalPages'] && !empty ($this->locationCode)) {
        return $this->response->redirect ($pageHelper->getRewriteUri ($this->page, $this->locationCode), true, 301);
      } else {
        $this->forwardToNotFound ();
      }
    }
    
    $this->generateAdsSearchFilters ();
    $this->setVariablesInView ();
    $this->setPagingInView ();
    $this->setAdvancedSearchLinkInView ();
    $this->setBreadcrumbsInView ($pageHelper);
    $this->setMetaInView ();
 
    $this->view->pick (["index/index"]);
 
    // JS assets
    $this->_jsAssets [] = 'summary';
    
    // Set variables in view
    $this->view->setVar ('ads',            $ads ['ads']);
    $this->view->setVar ('cities',         $pageHelper->getSortedCities ($this->config->pages->summary->topCitiesCount, $this->category, $this->gender));
    $this->view->setVar ('urlWOCity',      $pageHelper->getRewriteUri ($this->page, $this->locationCode, $this->popularSearch));
    $this->view->setVar ('urlFromRequest', $pageHelper->getRewriteUri ($this->page, null, $this->popularSearch));
    $this->view->setVar ('jsAssets',       $this->_jsAssets);
 
    if ($this->config->logging->app) {
      $this->getDI ()->getLogger ()->log ("afterQuery: " . (microtime (true) - APP_START_TIME));
    }
  }
 
  /**
   * Initialize class variables for popular search
   */
  public function popularSearchInit () {
    $this->popularSearch = SearchSeo::findFirstBySearchSeoID ($this->searchSeoID);
    
    if (is_null ($this->popularSearch->getLocationID ())) {
      $this->popularSearch->setLocationName ($this->storedLocation ['name']);
    }
    
    if (!$this->popularSearch){
      $redirectHelper = new SummaryHelper ($this->getReadConnection (), $this->params, $this->page);
      return $this->response->redirect ($redirectHelper->getRewriteUri ($this->page), true, 301);
    }
 
    $params = array ();
    
    parse_str (parse_url (trim ($this->popularSearch->getSearchUrl ()))['query'], $params);
    
    $this->params = array_merge ($params, $this->params);
  }
 
  /**
   * Initialize class variables 
   */
  protected function initAction () {
    $this->category        = $this->getDispatcherParam ('category',     'int', AdCategory::ESCORTS);
    $this->gender          = $this->getDispatcherParam ('gender',       'int', Gender::GENDER_FEMALE);
    $this->availability    = $this->getDispatcherParam ('availability', 'int', AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS);
    $this->searchSeoID     = $this->getDispatcherParam ('seo',          'int', 0);
    $this->page            = $this->getDispatcherParam ('page',         'int', 1);
    $this->currentLocation = $this->location->getID ();
    $this->rootLocationID  = $this->currentLocation;
    $this->allCitiesPage   = strcasecmp ($this->locationCode, 'all-cities') == 0;
 
    if (!empty ($this->locationCode) && !$this->allCitiesPage) {
      if ($this->location->getCode () == $this->locationCode) {
        $this->rootLocationID = null;
      }
 
      $this->currentLocation = LocationsModel::getLocationIDByCode ($this->rootLocationID, $this->locationCode);
    }
    
    // Get stored location
    $this->storedLocation = LocationsModel::getLocation ($this->currentLocation, false);          
 
    // Get age ranges from session
    if (!$this->_mobileApplication) {
      $ageRange = $this->session->get ('summary-page-age', array (
        'ageFrom' => null,
        'ageTo'   => null
      ));
    }
 
    $this->params = array (
      'el_category' => $this->category,
      'el_gender'   => $this->gender,
      'el_location' => $this->currentLocation,
    );
  }
 
  /**
   * Set advanced search link in view
   */
  protected function setAdvancedSearchLinkInView () {
    $params = array ();
    
    foreach ($this->params as $key => $value) {
      if (($key == 'el_location') && ($value <= 1)) {
        continue;
      }
      
      if (mb_strlen ($value)) {
        $params [$key] = $value;
      }
    }
    
    $this->view->setVar ('advanced_search_link', '/search?' . http_build_query ($params));    
  }
  
  /**
   * Set class dependency variables in view
   */
  protected function setVariablesInView () {
    $this->view->setVar ('urlLocationCode',    trim ($this->locationCode));
    $this->view->setVar ('storedLocation',     $this->storedLocation);
    $this->view->setVar ('storedLocationPath', LocationsModel::getLocationPath ($this->currentLocation));
    $this->view->setVar ('currentCountry',     LocationsModel::getLocationPath ($this->currentLocation, LocationType::COUNTRY)[0]);
    $this->view->setVar ('countries',          LocationsModel::getCountries (null, false));
    $this->view->setVar ('megalopolisTaxID',   LocationType::MEGALOPOLIS);
    $this->view->setVar ('countryTaxID',       LocationType::COUNTRY);
    $this->view->setVar ('stateTaxID',         LocationType::STATE);
    $this->view->setVar ('taxFemale',          Gender::GENDER_FEMALE);
    $this->view->setVar ('taxIncOutc',         AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS);
    $this->view->setVar ('countKey',           Utils::getCounterKey ($this->category, $this->gender));
    $this->view->setVar ('mobileVersion',      Utils::getVersionVar ());
    $this->view->setVar ('isPopularSearch',    ($this->searchSeoID > 0));    
    
    $this->view->setVar ("parentLocationsTaxIDs", array (
      LocationType::TOWN        => LocationType::TOWN,
      LocationType::CITY        => LocationType::CITY,
      LocationType::MEGALOPOLIS => LocationType::MEGALOPOLIS,
    ));
 
    $this->view->setVar ("locationsLvl1TaxIDs", array (
      LocationType::CITY        => LocationType::CITY,
      LocationType::MEGALOPOLIS => LocationType::MEGALOPOLIS,
    ));
  }
 
  /**
   * Set paging in view
   */
  protected function setPagingInView () {
    $this->view->setVar ('currentPage', $this->paging ['currentPage']);
    $this->view->setVar ('totalFound',  $this->paging ['totalFound']);
    $this->view->setVar ('totalPages',  $this->paging ['totalPages']);
    $this->view->setVar ('location',    $this->paging ['location']);
    $this->view->setVar ('pages',       $this->paging ['pages']);
    
    $this->setPagingMeta ();
  }
  
  /**
   * Set paging meta in view
   */
  protected function setPagingMeta () {
    if (!$this->paging ['totalFound']) return;
    
    $locationUri = $this->location->getUri ();
      
    if ($this->paging ['currentPage'] == 2) {
      $this->view->setVar ('prevLink', sprintf ('http://www.%s%s', $locationUri, $this->paging ['location']));
    }
 
    if ($this->paging ['currentPage'] > 2) {
      $this->view->setVar ('prevLink', sprintf ('http://www.%s%s/%s', $locationUri, $this->paging ['location'], $this->paging ['currentPage'] - 1));
    }
 
    if ($this->paging ['currentPage'] < $this->paging ['totalPages']) {
      $this->view->setVar ('nextLink', sprintf ('http://www.%s%s/%s', $locationUri, $this->paging ['location'], $this->paging ['currentPage'] + 1));
    }
  }
  
  /**
   * Initialize meta parts
   */
  protected function initMetaParts () {
    $this->metaParts = [];    
    
    if ($this->gender != Gender::GENDER_FEMALE) {
      $this->metaParts [] = $this->view->getVar ('requestData')['GENDER']['name'];
    }
    
    $this->metaParts [] = $this->view->getVar ('requestData')['AD_CATEGORIES']['name'];
    $this->metaParts = implode (' ', $this->metaParts);
  }
  
  /**
   * process redirects for index action
   */
  protected function indexRedirects () {
    $rewriteUri = $this->router->getRewriteUri ();
 
    // Prevent reaching all cities page without refferer
    if ($this->allCitiesPage && preg_match ('[incalls|outcalls]', $rewriteUri)) {
      $referrer   = $this->request->getHTTPReferer ();
      $rewriteUri = str_replace (array ('incalls-', 'outcalls-' ), '', $rewriteUri);
 
      if (!mb_strlen ($referrer)) {
        return $this->response->redirect (substr ($rewriteUri, strlen ($this->url->getBaseUri ()), -11) . '/all-cities', false, 301);
      }
    }
    
    // page 1 redirect
    if ($this->page == 1 and substr ($rewriteUri, -1, 1) == $this->page) {
      return $this->response->redirect (substr ($rewriteUri, 0, strlen ($rewriteUri) - 2), true, 301);
    }
 
    //@ToDo remove when google reindex pages
    if (strcasecmp ($this->locationCode, 'central') == 0) {
      $rewriteUri = str_replace ('central', 'central-london', $rewriteUri);
 
      return $this->response->redirect (substr ($rewriteUri, strlen ($this->url->getBaseUri ())));
    }
 
    // redirect if any incall/outcall provided
    if ($this->availability != AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS) {
      $categoryName = Utils::getCategoryNameByID ($this->category);
      $newUri       = '/' . $categoryName;
 
      if (!empty ($this->locationCode)) {
        $locationID    = LocationsModel::getLocationIDByCode ($this->rootLocationID, $this->locationCode);
        $locationArray = LocationsModel::getLocation ($locationID);
        
        if (in_array ($locationArray ['locationTypeID'], array (LocationType::CITY, LocationType::TOWN, LocationType::MEGALOPOLIS))) {
          $newUri .= '/' . $locationArray ['code'];
        } 
        
        if (in_array ($locationArray ['locationTypeID'], array (LocationType::CITY_PART, LocationType::NEIGHBOURHOOD))) {
          $locationPath = LocationsModel::getLocationPath ($locationID);
          $newUri .= '/' . $locationPath [0]['code'];
        }
      }
 
      return $this->response->redirect ($newUri, true, 301);
    }
    
    $maximumPages = $this->config->pages->summary->maximumPages;
    
    if ($this->_mobileApplication) {
      $maximumPages = $this->config->mobilePages->summary->maximumPages;
    }
    
    // Forward to not found page if information is not valid
    if (($this->page > $maximumPages) || empty ($this->category) || (empty ($this->currentLocation) && !$this->allCitiesPage)) {
      return $this->forwardToNotFound ();
    }
    
    // Redirect for preventing resubmit form on back action
    if ($this->request->isPost () || ($rewriteUri != $this->router->getRewriteUri ())) {
      return $this->response->redirect (substr ($rewriteUri, strlen ($this->url->getBaseUri ())));
    }
  }
 
  /**
   * Set breadcrumbs in view
   * 
   * @param array $breadcrumbs
   */
  protected function setBreadcrumbsInView ($pageHelper) {
    $tilte = ($this->searchSeoID && $this->popularSearch) ? $this->popularSearch->getAnchor () : null;
    
    $this->view->setVar ('breadcrumbs', $pageHelper->getBreadcrumb ($tilte));
  }
 
  /**
   * Set meta in view
   */
  protected function setMetaInView () {
    if ($this->searchSeoID && $this->popularSearch) {
      $this->setMetaDynamic ($this->popularSearch);
      $this->setSearchAnchors (true);      
    } else {
      $this->setSeoText ();
      $this->setSearchAnchors (false);
      $this->setMeta ();
    }
  }
  
  /**
   * Set meta tags
   */
  protected function setMeta () {
    $category = Utils::getCategoryTranslations ($this->category, $this->translations);
    $gender   = Utils::getGenderTranslations ($this->gender, $this->translations);
    $prefix   = '';
    
    if ($this->_mobileApplication) {
      $prefix = 'mobile-';
    }
    
    if (!empty ($this->locationCode)) {
      if ($this->page == 1) {
        $this->view->setVar ('pageTitle',       sprintf ($this->translations [$prefix . 'summary-page-title'], $this->storedLocation ['name'], $gender->nameSEO, $category->name, $gender->name, $category->nameSingular, $this->storedLocation ['name']));
        $this->view->setVar ('metaDescription', sprintf ($this->translations [$prefix . 'summary-page-meta-in'], $this->metaParts, $this->storedLocation ['name']));
      } else {
        $this->view->setVar ('pageTitle',       sprintf ($this->translations [$prefix . 'summary-page-title-page'], $this->storedLocation ['name'], $gender->nameSEO, $category->name, $gender->name, $category->nameSingular, $this->storedLocation ['name'], $this->page));
        $this->view->setVar ('metaDescription', sprintf ($this->translations [$prefix . 'summary-page-meta-in-page'], $this->metaParts, $this->storedLocation ['name'], $this->page));
      }
    } else {
      if ($this->page == 1) {
        $this->view->setVar ('pageTitle',       sprintf ($this->translations [$prefix . 'summary-page-title-no-city'], $gender->nameSEO, $category->name, $gender->name, $category->nameSingular));
        $this->view->setVar ('metaDescription', sprintf ($this->translations [$prefix . 'summary-page-meta'], $this->metaParts));
      } else {
        $this->view->setVar ('pageTitle',       sprintf ($this->translations [$prefix . 'summary-page-title-no-city-page'], $gender->nameSEO, $category->name, $gender->name, $category->nameSingular, $this->page));
        $this->view->setVar ('metaDescription', sprintf ($this->translations [$prefix . 'summary-page-meta-page'], $this->metaParts, $this->page));
      }
    }
 
    $this->view->setVar ('searchMeta', $this->metaParts);
  }
 
  /**
   * Set meta tags
   */
  protected function setMetaDynamic ($popularSerach) {
    $metaTitle       = trim ($popularSerach->getMetaTitle ());
    $metaDescription = trim ($popularSerach->getMetaDescription ());
    
    if ($this->page > 1) {
      if ($metaTitle [mb_strlen ($metaTitle) - 1] == '.') {
        $metaTitle = substr ($metaTitle, 0, -1);
      }
 
      if ($metaDescription [mb_strlen ($metaDescription) - 1] == '.') {
        $metaDescription = substr ($metaDescription, 0, -1);
      }
      
      $metaTitle       = sprintf ($this->translations ['summary-page-title-popular'], $metaTitle, $this->page);
      $metaDescription = sprintf ($this->translations ['summary-page-meta-popular'], $metaDescription, $this->page);
    }
    
    $this->view->setVar ('pageTitle',       $metaTitle);
    $this->view->setVar ('metaDescription', $metaDescription);
    $this->view->setVar ('h1',              $popularSerach->getH1 ());
    $this->view->setVar ('h2',              $popularSerach->getH2 ());
    $this->view->setVar ("seoText",         $popularSerach->getSeoText () );
  }
 
  /**
   * Set SEO text
   */
  protected function setSeoText () {
    if (!$this->currentLocation || !$this->gender || !$this->category) return;
 
    $res = LocationsSeo::findFirst (
      array (
        "conditions" => "locationID = :locationID: AND genderID = :genderID: AND categoryID = :categoryID:",
 
        "bind" => array (
          "locationID"  => $this->currentLocation,
          "genderID"    => $this->gender,
          "categoryID"  => $this->category
        )
      )
    );
    
    $this->view->setVar ("seoText", $res?$res->getSeoText():null);
  }
 
  /**
   * Set Popular Search Links
   * 
   * @param boolean $childLinks
   */
  protected function setSearchAnchors ($childLinks = false) {
    if (!$this->currentLocation || !$this->gender || !$this->category) return;
    
    $locationID    = $this->currentLocation;
    $searchAnchors = null;    
 
    if ($childLinks) {
      $location   = LocationsModel::getLocation ($this->currentLocation);
      $locationID = array ();
      
      if (isset ($location ['childs'])) {
        array_walk_recursive ($location, function ($value, $key) use (&$locationID) { 
          if (($key == 'locationID') && ($value != $this->currentLocation)) {
            $locationID [] = $value; 
          }
        });    
      }
    }
    
    $searchUrl = $childLinks ? $this->popularSearch->getSortedSearchQuery () : null;
    
    if ($locationID || (is_array ($locationID) && count ($locationID))) {
      $searchAnchors = SearchSeo::getSearchSeoByCriterias ($locationID, $this->category, $this->gender, $searchUrl);
    }
    
    $this->view->setVar ("searchAnchors", $searchAnchors);
  }
 
  /**
   * Generate search filters for ads
   */
  protected function generateAdsSearchFilters () {
    $controlsData = array ();
    $taxonomySet  = array ();
    
    foreach ($this->taxonomyTree as $treeItem) {
      if (isset ($treeItem ['taxonomyID']) && in_array ($treeItem ['taxonomyID'], [Taxonomy::AD_CATEGORIES, Taxonomy::GENDER, Taxonomy::AD_AVAILABILITY, Taxonomy::AGE])) {
        $controlsData [$treeItem ['code']] = array (
          'caption' => $treeItem ['name'],
          'items'   => array (),
          'type'    => 'select',          
        );
 
        if (!isset ($treeItem ['childs'])) {
          $range = $treeItem ['metaData']['range'];
 
          $controlsData [$treeItem ['code']] = array (
            'caption'     => $treeItem ['name'],
            'from'        => $range ['from'],
            'to'          => $range ['to'],
            'defaultFrom' => $range ['defaultFrom'],
            'defaultTo'   => $range ['defaultTo'],
            'type'        => 'range',            
          );
        } else {
          foreach ($treeItem ['childs'] as &$childItem) {
            // Replace translations
            $code = $childItem ['code'];
 
            if (isset ($this->translations ["summary-filter::{$code}"])) {
              $childItem ['name'] = $this->translations ["summary-filter::{$code}"];
            }
 
            if (in_array ($childItem ['taxonomyID'], AdCategory::getMembers ())) {
              $childItem ['attachExtraInfo'] = $childItem ['taxonomyID'] != AdCategory::MASSAGE;
            }
            
            if (in_array ($childItem ['taxonomyID'], Gender::getMembers ())) {
              $childItem ['enabled'] = $this->storedLocation [Utils::getCounterKey ($this->category, $childItem ['taxonomyID'])] > 0;
            }
 
            $taxonomySet [$childItem ['taxonomyID']] = $childItem;
            $controlsData [$treeItem ['code']]['items'][] = $childItem;
          }
        }
      }
    }
 
    // Get age ragnges from session
    if ($this->_mobileApplication) {
      $ageRange = $this->session->get ('summary-page-age', array (
        'ageFrom' => $this->config->pages->summary->defaultAgeRange->ageFrom, 
        'ageTo'   => $this->config->pages->summary->defaultAgeRange->ageTo
      ));
    } else {
      $ageRange = $this->session->get ('summary-page-age');
    } 
    
    // Set variables in view
    $this->view->setVar ("sessionAgeRange", $ageRange);
    $this->view->setVar ("controlsData",    $controlsData);
 
    // Set request data variables in view        
    $this->view->setVar ("requestData", array (
      'AD_CATEGORIES'   => $taxonomySet [$this->getDispatcherParam ('category',     'int', AdCategory::ESCORTS)],
      'GENDER'          => $taxonomySet [$this->getDispatcherParam ('gender',       'int', Gender::GENDER_FEMALE)],
      'AD_AVAILABILITY' => $taxonomySet [$this->getDispatcherParam ('availability', 'int', AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS)]
    ));
 
    $this->initMetaParts ();    
  }
}
#25PTMU\Frontend\Controllers\IndexController->indexAction(100703, 200001, newcastle, )
#26Phalcon\Dispatcher->dispatch()
#27Phalcon\Mvc\Application->handle()
/var/www/html/public/index.php (36)
<?php
  define('PINBA',(extension_loaded('pinba')?true:false));  
  error_reporting (E_ERROR | E_WARNING);
 
  // Global start time
  define ('APP_START_TIME', microtime (true));
    
  // Read the configuration
  $config = include (__DIR__ . "/../ptmu/common/config/config.php");
  
  // Define global application environment constant  
  define ('APPLICATION_ENV', (getenv ('APPLICATION_ENV') ? getenv ('APPLICATION_ENV') : $config->application->environment));
  
  // Read auto-loader
  include (__DIR__ . "/../ptmu/common/config/loader.php");
 
  // Read services
  include (__DIR__ . "/../ptmu/common/config/services.php");
 
  // Setup debugger
 
  $debug = new Phalcon\Debug ();
  $debug->listen ();
 
  // Handle the request
  $application = new \Phalcon\Mvc\Application ($di);
 
  // Registering modules  
  $application->registerModules (require (__DIR__ . '/../ptmu/common/config/modules.php'));
 
  if ($config->logging->app) {
    $di->getLogger ()->log ("Initialization time: " . (microtime (true) - APP_START_TIME));    
  } 
  
  // Output application result
  echo ($application->handle ()->getContent ());
  
 
  if ($config->logging->app) {
    $di->getLogger ()->log ("Execution time: " . (microtime (true) - APP_START_TIME));    
  }        
 //pinba.flush();
 
                                                                      
  
KeyValue
_url/transexual-escorts/newcastle
KeyValue
USERapache
HOME/var/www
FCGI_ROLERESPONDER
SCRIPT_FILENAME/var/www/html/public/index.php
QUERY_STRING_url=/transexual-escorts/newcastle
REQUEST_METHODGET
CONTENT_TYPE
CONTENT_LENGTH
SCRIPT_NAME/index.php
REQUEST_URI/transexual-escorts/newcastle
DOCUMENT_URI/index.php
DOCUMENT_ROOT/var/www/html/public
SERVER_PROTOCOLHTTP/1.0
GATEWAY_INTERFACECGI/1.1
SERVER_SOFTWAREnginx/1.6.2
REMOTE_ADDR54.146.176.30
REMOTE_PORT37965
SERVER_ADDR172.31.17.249
SERVER_PORT80
SERVER_NAMEptmuadmin.ptmu.co.uk
REDIRECT_STATUS200
HTTP_HOSTwww.ptmu.co.uk
HTTP_ACCEPT_ENCODINGx-gzip, gzip, deflate
HTTP_USER_AGENTCCBot/2.0 (http://commoncrawl.org/faq/)
HTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
PHP_SELF/index.php
REQUEST_TIME_FLOAT1487645459.7864
REQUEST_TIME1487645459
#Path
0/var/www/html/public/index.php
1/var/www/html/ptmu/common/config/config.php
2/var/www/html/ptmu/common/config/loader.php
3/var/www/html/ptmu/common/config/services.php
4/var/www/html/ptmu/common/config/modules.php
5/var/www/html/ptmu/common/config/routes.php
6/var/www/html/ptmu/common/library/Utils/Utils.php
7/var/www/html/ptmu/common/library/Taxonomy/Taxonomy0.php
8/var/www/html/ptmu/common/library/Taxonomy/Taxonomy1.php
9/var/www/html/ptmu/common/models/SearchSeo.php
10/var/www/html/ptmu/frontend/Module.php
11/var/www/html/ptmu/common/library/Phalcon/Session/Adapter/Memcache.php
12/var/www/html/ptmu/frontend/controllers/IndexController.php
13/var/www/html/ptmu/frontend/controllers/ControllerBase.php
14/var/www/html/ptmu/common/models/Translations.php
15/var/www/html/ptmu/common/models/CacheableModel.php
16/var/www/html/ptmu/common/library/Phalcon/Logger/Adapter/Dummy.php
17/var/www/html/ptmu/common/library/Auth/Auth.php
18/var/www/html/ptmu/common/models/Taxonomy.php
19/var/www/html/ptmu/common/library/Location/Location.php
20/var/www/html/ptmu/common/models/Locations.php
21/var/www/html/ptmu/common/library/ModelsManager/ModelsManager.php
22/var/www/html/ptmu/common/library/Phalcon/Mvc/Model/MetaData/Memcache.php
23/var/www/html/ptmu/common/library/Phalcon/Mvc/Model/MetaData/Base.php
Memory
Usage4194304