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\Ads: ))
#11Phalcon\Mvc\Model->getReadConnection()
#12Phalcon\Mvc\Model\Query->_executeSelect(Array([models] => Array([0] => PTMU\Models\Ads), [tables] => Array([0] => ads), [columns] => Array([pTMU\Models\Ads] => Array([type] => object, [model] => PTMU\Models\Ads, [column] => ads, [balias] => pTMU\Models\Ads)), [where] => Array([type] => binary-op, [op] => =, [left] => Array([type] => qualified, [domain] => ads, [name] => AdID, [balias] => adID), [right] => Array([type] => placeholder, [value] => :0)), [limit] => Array([number] => 1)), Array([0] => 56), null)
#13Phalcon\Mvc\Model\Query->execute(Array([0] => 56), null)
#14Phalcon\Mvc\Model::findFirst(Array([conditions] => adID = ?0, [bind] => Array([0] => 56)))
#15Phalcon\Mvc\Model::__callStatic(findFirstByAdID, Array([0] => 56))
/var/www/html/ptmu/frontend/controllers/PostController.php (57)
<?php
 
namespace PTMU\Frontend\Controllers;
 
use Phalcon\DI;
use Phalcon\Mvc\View;
use PTMU\Models\Ads;
use PTMU\Models\Users;
use PTMU\Models\AdReviews;
use PTMU\Models\AgencyReviews;
use PTMU\Models\SearchSeo;
use PTMU\Forms\AdsForm;
use PTMU\Forms\UsersForm;
use PTMU\Taxonomy as Taxonomy;
use PTMU\Taxonomy\AdStatus;
use PTMU\Taxonomy\AdCategories;
use PTMU\Taxonomy\AdAvailability;
use PTMU\Taxonomy\AdPricingLevel;
use PTMU\Taxonomy\AdAvailabilityDay;
use PTMU\Taxonomy\AdEthnicity;
use PTMU\Taxonomy\Gender;
use PTMU\Taxonomy\UserType;
use PTMU\Taxonomy\UserStatus;
use PTMU\Taxonomy\ReviewStatus;
use PTMU\Models\Locations;
use PTMU\Models\Taxonomy as TaxonomyModel;
use PTMU\Models\Locations as LocationsModel;
use PTMU\Taxonomy\LocationType;
use PTMU\Breadcrumb\Breadcrumb;
use PTMU\Taxonomy\AdUpdateType as AdUpdateType;
use PTMU\Utils\Utils;
use PTMU\Pages\SummaryHelper;
 
class PostController extends ControllerBase {
 
  protected $seoLinks;
 
 
  /**
   * index action
   */
  public function indexAction () {
    $this->response->setContent ("Post controller");
 
    return $this->response;
  }
 
  /**
   * view action
   */
  public function viewAction () {
    $id       = $this->dispatcher->getParam ("id");  
    $tilte    = $this->dispatcher->getParam ("title");      
    $category = $this->dispatcher->getParam ("category");
    $hash     = $this->dispatcher->getParam ("hash");
    
    if (($ad = Ads::findFirstByAdID ($id)) === false) {
      return $this->forwardToNotFound ();
    }
 
    // Redirect to summary if ad is not reachable anymore    
    if ($this->isInactiveAd ($ad)) {
      $location = LocationsModel::getLocationPath ($ad->getLocationID ());
      return $this->response->redirect ("{$ad->getCategoryUri ()}/{$location [0]['code']}", false, 301);
    }
    
    $queryURL = $this->request->getQuery ()['_url'];
    $reviewID = 0;
    
    // Check review hash
    if ((strpos ($hash, 'review-') === 0) && ($reviewID = intval (substr ($hash, 7)))) {
      $queryURL = substr ($queryURL, 0, -(strlen ($hash) + 1));
    }
 
    // Check ad details and forward to new url if ad details was changed
    if ($queryURL != $ad->getDetailsURL ()) {
      return $this->response->redirect ($ad->getDetailsURL (false), false, 302);
    }
 
    $updates    = $ad->getStatusUpdates (null);
    $relatedAds = $this->getRelatedAds ($ad);
 
    $this->view->pick (["post/detail"]);
        
    // JS assets
    $this->_jsAssets [] = 'jquery.sticky-kit';
    $this->_jsAssets [] = 'jquery.preload';
    $this->_jsAssets [] = 'detail';
 
    $this->view->setVar ("ad",                  $ad);
    $this->view->setVar ("updates",             $updates);
    $this->view->setVar ('relatedAdsPreloaded', $relatedAds ['relatedAdsPreloaded']);    
    $this->view->setVar ('breadcrumbs',         $this->getBreadcrumb ($ad));
    $this->view->setVar ("backUrl",             $this->getBackUrl ($ad));    
    $this->view->setVar ('jsAssets',            $this->_jsAssets);
 
 
    if($ad->getCategoryID() == AdCategories::ESCORTS) {
      $this->getPopularDetailLinks($ad);
    }
 
    $this->view->setVar ('seoLinks',            $this->seoLinks);
 
    $this->view->setVar ("detailsPageData", array(
      "biographyLinesLimit"   => $this->config->pages->details->biographyLinesLimit,
      "commentsInitialItems"  => $this->config->pages->comments->initialItems,
      "commentsAjaxLoadItems" => $this->config->pages->comments->ajaxLoadItems,
      "newSinceDate"          => $updates ["nextUpdateDate"],
      "relatedAdsIDs"         => $relatedAds ['relatedAdsIDs'],
      "adID"                  => $ad->getAdID (),
      "isAdInUse"             => $ad->getAdID () == $this->getAdInUseID (),
      "identity"              => !is_null ($this->auth->getIdentity ()),
      "isVerified"            => $this->auth->isVerified (),
      "isWatchlisted"         => $this->auth->isWatchlisted (),
      "reviewID"              => $reviewID,
    ));
 
    $this->setReviewsVariablesInView ($ad, $reviewID);  
    $this->setVariablesInView ();
    
    // Getting meta parts
    $metaParts = Utils::getDetailPageMetaParts ($ad, $this->translations);
        
    // Page title and meta description
    $this->view->setVar ('pageTitle',       sprintf ($this->translations ['details-page-title'], $metaParts->title, $metaParts->variant, $metaParts->city));
    $this->view->setVar ('metaDescription', sprintf ($this->translations ['details-page-meta'], $metaParts->userName, $metaParts->age, $metaParts->variant, $metaParts->city, $metaParts->biography));
  }
 
  public function getPopularDetailLinks ( $ad ){
   $ethnicitySeo = [];
   $bodySeo      = [];
   $ageSeo       = [];
   $config       = DI::getDefault ()->getConfig ();
 
    $this->seoLinks[0] = ['link' =>$ad->getCategoryUri (true)."/".$ad->getLocationPath()[0]['code'], 'name'=> $ad->getCategory().' in '.$ad->getLocationPath()[0]['name'] ];
 
    foreach (searchSeo::find () as $searchSeo) {
      $params = $searchSeo->getSearchParams();
 
      if(in_array($ad->getCategoryID(),$params) && in_array($ad->getEthnicityID(),$params)){
 
        $ethnicitySeo[]= $searchSeo->getSearchSeoID();
        $pageHelper = new SummaryHelper (DI::getDefault()->getModelsManager ()->getReadConnection (), $params, 0);
        $results    = $pageHelper->extendedSearchFilter (['locationids']);
 
        $anchor = str_ireplace("%city%","in ". $ad->getLocationPath()[0]['name'], $searchSeo->getAnchor(false));
 
        if($results ['filteredIds']['LOCATIONIDS'][$ad->getLocationPath()[0]['locationID']]>$config->popularSearch->minAdsCount and $searchSeo->getLocationID() == null){
         $searchSeo->setLocationID ($ad->getLocationPath()[0]['locationID']);
         $this->seoLinks[1] = ['link'=>$ad->getCategoryUri ().'/'.$ad->getLocationPath()[0]['code'].'/'.$searchSeo->getDestinationUrl(), 'name'=>$anchor];
        } elseif ($searchSeo->getLocationID() != null){
         $this->seoLinks[1] = ['link'=>$ad->getCategoryUri ().'/'.$searchSeo->getDestinationUrl(), 'name'=>$searchSeo->getAnchor(true)];
        }
      }
 
      if(in_array($ad->getCategoryID(),$params) && in_array($ad->getBodyTypeID(),$params)){
        $bodySeo[]= $searchSeo->getSearchSeoID();
 
        $pageHelper = new SummaryHelper (DI::getDefault()->getModelsManager ()->getReadConnection (), $params, 0);
        $results    = $pageHelper->extendedSearchFilter (['locationids']);
 
        $anchor = str_ireplace("%city%","in ". $ad->getLocationPath()[0]['name'], $searchSeo->getAnchor(false));
 
        if($results ['filteredIds']['LOCATIONIDS'][$ad->getLocationPath()[0]['locationID']]>$config->popularSearch->minAdsCount and $searchSeo->getLocationID() == null){
          $searchSeo->setLocationID ($ad->getLocationPath()[0]['locationID']);
          $this->seoLinks[2] = ['link'=>$ad->getCategoryUri ().'/'.$ad->getLocationPath()[0]['code'].'/'.$searchSeo->getDestinationUrl(), 'name'=>$anchor];
        }
        elseif($searchSeo->getLocationID() != null){
          $this->seoLinks[2] = ['link'=>$ad->getCategoryUri ().'/'.$searchSeo->getDestinationUrl(), 'name'=>$searchSeo->getAnchor(true)];
        }
      }
 
      if(in_array($ad->getCategoryID(),$params) && intval($ad->getAge()) >= 18 and intval($ad->getAge()) <= 19 && in_array($searchSeo->getSearchSeoID(),[16,31])){
        $ageSeo[]= $searchSeo;
 
 
        $pageHelper = new SummaryHelper (DI::getDefault()->getModelsManager ()->getReadConnection (), $params, 0);
        $results    = $pageHelper->extendedSearchFilter (['locationids']);
        $anchor = str_ireplace("%city%","in ". $ad->getLocationPath()[0]['name'], $searchSeo->getAnchor(false));
 
        if($results ['filteredIds']['LOCATIONIDS'][$ad->getLocationPath()[0]['locationID']]>$config->popularSearch->minAdsCount and $searchSeo->getLocationID() == null){
          $searchSeo->setLocationID ($ad->getLocationPath()[0]['locationID']);
          $this->seoLinks[3] = ['link'=>$ad->getCategoryUri ().'/'.$ad->getLocationPath()[0]['code'].'/'.$searchSeo->getDestinationUrl(), 'name'=>$anchor];
        }
        elseif($searchSeo->getLocationID() != null){
          $this->seoLinks[3] = ['link'=>$ad->getCategoryUri ().'/'.$searchSeo->getDestinationUrl(), 'name'=>$searchSeo->getAnchor(true)];
        }
      }
 
      if(in_array($ad->getCategoryID(),$params) && intval($ad->getAge()) >= 36 and intval($ad->getAge()) <= 60 && in_array($searchSeo->getSearchSeoID(), [1,7]) ){
        $ageSeo[]= $searchSeo;
 
 
        $pageHelper = new SummaryHelper (DI::getDefault()->getModelsManager ()->getReadConnection (), $params, 0);
        $results    = $pageHelper->extendedSearchFilter (['locationids']);
 
 
        $anchor = str_ireplace("%city%","in ". $ad->getLocationPath()[0]['name'], $searchSeo->getAnchor(false));
 
        if($results ['filteredIds']['LOCATIONIDS'][$ad->getLocationPath()[0]['locationID']]>$config->popularSearch->minAdsCount and $searchSeo->getLocationID() == null){
          $searchSeo->setLocationID ($ad->getLocationPath()[0]['locationID']);
          $this->seoLinks[3] = ['link'=>$ad->getCategoryUri ().'/'.$ad->getLocationPath()[0]['code'].'/'.$searchSeo->getDestinationUrl(), 'name'=>$anchor];
        }
        elseif($searchSeo->getLocationID() != null){
          $this->seoLinks[3] = ['link'=>$ad->getCategoryUri ().'/'.$searchSeo->getDestinationUrl(), 'name'=>$searchSeo->getAnchor(true)];
        }
      }
    }
  }
 
  /**
   * Show form for post new ad
   */
  public function addAction () {
    $user          = $this->getUserForNewAd ();        
    $ad            = new Ads ();
    $adsForm       = new AdsForm ($ad);
    $usersForm     = new UsersForm ($user);    
    $taxonomy      = TaxonomyModel::getTaxonomy ();
 
    if ($this->_mobileApplication) {
      $this->view->setViewsDir($this->di->getConfig()->mobileModule->viewsDir);
    }
    $this->view->pick (["post/adsForm"]);
        
    // JS assets
    $this->_jsAssets [] = 'postingForm';
 
    $this->view->setVar ("ad",                  $ad);
    $this->view->setVar ("adsForm",             $adsForm);
    $this->view->setVar ("usersForm",           $usersForm);
    $this->view->setVar ("taxonomyTree",        TaxonomyModel::getTaxonomyAsTree ());
    $this->view->setVar ("currencySymbol",      $this->location->getCurrencySymbol ());
    $this->view->setVar ("locationsLvl1",       LocationsModel::getLocations ($this->location->getID ()));
    $this->view->setVar ("locations",           LocationsModel::getLocations (null, true));
    $this->view->setVar ("availableCategories", $this->getAvailableCategories ($user->getUserID (), $taxonomy));
    $this->view->setVar ("accountTaxonomies",   $this->getAccountTaxonomies ($ad, $user, $taxonomy));
    $this->view->setVar ("isAgency",            ($user->getTypeID () == UserType::AGENCY_USER));
    $this->view->setVar ('jsAssets',            $this->_jsAssets);    
    
    // Set proper application version for alternate/canonical link
    $this->view->setVar (Utils::getVersionVar (), true);
    
    // Page title and meta description
    $this->view->setVar ("pageTitle",       $this->translations ['posting-page-title']);
    $this->view->setVar ("metaDescription", $this->translations ['posting-page-meta']);
  }
 
  /**
   * Show form for ad update
   */
  public function updateAction ($adID) {
    if (!($ad = Ads::findFirstByAdID ($adID)) || !$this->auth->isLoggedUser ($ad->getUserID ())) {
      return $this->forwardToNotFound ();
    }
 
    $adsForm   = new AdsForm ($ad);
    $usersForm = new UsersForm ($ad->user);
 
    $taxonomyTree = TaxonomyModel::getTaxonomyAsTree ();
    $taxonomy     = TaxonomyModel::getTaxonomy ();
    $attributes   = $this->getAttributes ($ad, $taxonomy);
 
    //if ($this->_mobileApplication) {
    //  $this->view->setViewsDir($this->di->getConfig()->mobileModule->viewsDir);
    //}
 
    $this->view->pick (["post/adsForm"]);
        
    // JS assets
    $this->_jsAssets [] = 'postingForm';
 
    $this->view->setVar ("ad",                $ad);
    $this->view->setVar ("adsForm",           $adsForm);
    $this->view->setVar ("usersForm",         $usersForm);
    $this->view->setVar ("taxonomyTree",      $taxonomyTree);
    $this->view->setVar ("currencySymbol",    $this->location->getCurrencySymbol ());
    $this->view->setVar ("locationsLvl1",     LocationsModel::getLocations ($this->location->getID ()));
    $this->view->setVar ("locations",         LocationsModel::getLocations ());
    $this->view->setVar ("locationPath",      LocationsModel::getLocationPath ($ad->getLocationID (), array (LocationType::STATE)));
    $this->view->setVar ("adCategory",        $taxonomy [$ad->getCategoryID ()]);
    $this->view->setVar ("adUserType",        $taxonomy [$ad->user->getTypeID ()]);
    $this->view->setVar ("accountTaxonomies", $this->getAccountTaxonomies ($ad, $ad->user, $taxonomy));
    $this->view->setVar ("isAgency",          ($ad->user->getTypeID () == UserType::AGENCY_USER));
    $this->view->setVar ('jsAssets',          $this->_jsAssets);
 
    $this->view->setVar ("availabilityPricingData", array (
      "availabilityOptions"       => TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::AD_AVAILABILITY_DAY),
      "availabilityForOptions"    => AdAvailability::getMembers (),
      "pricingOptions"            => TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::AD_PRICING_LEVEL),
      "hoursRange"                => $attributes->hoursRange,
      "adPricings"                => $attributes->adPricings,
      "adAvailabilitiDays"        => $attributes->adAvailabilitiDays,
      "adID"                      => $ad->getAdID (),
      "hourPricingTax"            => $taxonomy [AdPricingLevel::AD_PRICING_1_HOUR],
      "availabilityEverydayTax"   => $taxonomy [AdAvailabilityDay::AD_AVAILABILITY_EVERYDAY],
      "availabilityIncallsTax"    => $taxonomy [AdAvailability::AD_AVAILABILITY_INCALLS],
      "availabilityOutcallsTax"   => $taxonomy [AdAvailability::AD_AVAILABILITY_OUTCALLS],
      "anyTimeTax"                => $attributes->anyTimeTax,
      "firstHoursItem"            => $attributes->firstHoursItem,
      "lastHoursItem"             => $attributes->lastHoursItem,
      "timeAfterAnyTimeUncheck"   => '23:00:00',
    ));
 
    // Page title and meta description
    $this->view->setVar ("pageTitle",       $this->translations ['posting-page-title']);
    $this->view->setVar ("metaDescription", $this->translations ['posting-page-meta']);
  }
  
  /**
   * Show form for upload pictures
   */
  public function postPicturesAction ($adID) {
    if (!($ad = Ads::findFirstByAdID ($adID)) || !$this->auth->isLoggedUser ($ad->getUserID ())) {
      return $this->forwardToNotFound ();
    }
    if ($this->_mobileApplication) {
      $this->view->setViewsDir($this->di->getConfig()->mobileModule->viewsDir);
    }
 
    $this->view->pick (["post/postPictures"]);
        
    // JS assets
    $this->_jsAssets [] = 'postPictures';
 
    $this->view->setVar ("ad",       $ad);
    $this->view->setVar ('jsAssets', $this->_jsAssets);
    
    $this->view->setVar ("requiredPicturesCounts", array (
      "requiredPicturesCount"       => $this->config->pages->posting->requiredPicturesCount,
      "requiredPublicPicturesCount" => $this->config->pages->posting->requiredPublicPicturesCount,
    ));
    
    // Page title and meta description
    if ($this->_mobileApplication) {
      $this->view->setVar ("pageTitle",       $this->translations ['mobile-upload-photos-page-title']);
      $this->view->setVar ("metaDescription", $this->translations ['mobile-upload-photos-page-meta']);
    } else {
      $this->view->setVar ("pageTitle",       $this->translations ['upload-photos-page-title']);
      $this->view->setVar ("metaDescription", $this->translations ['upload-photos-page-meta']);
    }
  }
 
  /**
   * Get ads that related to provided
   */
  protected function getRelatedAds ($ad) {
    $locations           = Locations::getLocationPath ($ad->getLocationID ());
    $gender              = $ad->getGenderID ();
    $location            = $locations[0]['locationID'];
    $category            = $ad->getCategoryID ();
    $status              = implode (',', [AdStatus::AD_ACTIVE, AdStatus::AD_EDITED]);
    $userStatus          = UserStatus::VERIFIED;
    $excludeAdID         = $ad->getAdID ();
    $relatedAdsIDs       = array ();
    $relatedAdsPreloaded = array ();
 
    $relatedAds = $this->modelsManager->getReadConnection (null)->query ("
      select spx_ads.AdID
      from spx_ads
      where query='!filter=indexID,{$excludeAdID};filter=StatusID,{$status};filter=UserStatusID,{$userStatus};filter=CategoryID,{$category};filter=GenderID,{$gender};filter=LocationID,{$location};sort=extended:@random;limit=2000;maxmatches=2000'
    ")->fetchAll ();
 
    foreach ($relatedAds as $ad) {
      $relatedAdsIDs [] = $ad ['AdID'];
    }
 
    if (!empty ($relatedAdsIDs)) {
      $pageHelper   = new SummaryHelper ($this->getReadConnection ());
      $generatedAds = $pageHelper->generateAdsByIDs (array (), array_slice ($relatedAdsIDs, 0, $this->config->pages->details->relatedAdsLimit));
 
      foreach ($generatedAds ['ads'] as $ad) {
        $relatedAdsPreloaded [] = array (
          'userName' => $ad->getUserName (),
          'picURL'   => "/{$ad->getPicturesUri ()}/{$ad->getMainPictureThumbnailFileName ()}",
          'adURL'    => $ad->getDetailsURL (),
          'city'     => $locations [0]['name'],
        );
      }
    }
 
    return array (
      'relatedAdsIDs'       => $relatedAdsIDs,
      'relatedAdsPreloaded' => $relatedAdsPreloaded
    );
  }
  
  /**
   * Returns true if ad is inactive
   * 
   * @param \PTMU\Models\Ads $ad
   * @returns boolean
   */
  protected function isInactiveAd ($ad) {
    $adIsActive   = in_array ($ad->getStatusID (), array (AdStatus::AD_ACTIVE, AdStatus::AD_EDITED));
    $userIsActive = ($ad->user->getStatusID () == UserStatus::VERIFIED);
    $logedAdOwner = ($this->auth->getID () == $ad->user->getUserID ());
 
    return ((((!$adIsActive || !$userIsActive) && !$logedAdOwner)) || ($ad->getStatusID () == AdStatus::AD_DELETED));
  }
  
  /**
   * Set class dependency variables in view
   */
  protected function setVariablesInView () {
    $taxonomyTree = TaxonomyModel::getTaxonomyAsTree ();    
    
    $this->view->setVar ("user",                Users::findFirst($this->auth->getID ()));
    $this->view->setVar ("statusUpdateTaxID",   AdUpdateType::STATUS_UPDATE);
    $this->view->setVar ("profileUpdateTaxID",  AdUpdateType::PROFILE_UPDATE);
    $this->view->setVar ("cities",              LocationsModel::getCities ($this->location->getID ()));
    $this->view->setVar ("availabilityOptions", TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::AD_AVAILABILITY_DAY));
    $this->view->setVar ("pricingOptions",      TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::AD_PRICING_LEVEL));
    $this->view->setVar ("anyTimeTax",          $taxonomyTree [Taxonomy::HOUR_ANYTIME]);
    $this->view->setVar ("canReply",            false);
    $this->view->setVar ('mobileVersion',       true);        
  }
  
  /**
   * Set reviews variables in view
   * 
   * @param \PTMU\Models\Ads $ad
   * @param integer $reviewID
   */
  protected function setReviewsVariablesInView ($ad, $reviewID) {
    $listreviews         = array();
    $canReviewRegular    = array ();    
    $userCanReviewAgency = false;
    $userCanReview       = false;
    $agencyTotalReviews  = null;    
    $limit               = null;    
 
    $totalreviews = AdReviews::avgReviews ($ad->getAdID (), $this->auth->getUser());
        
    if ($totalreviews ['count']) {
      $limit    = $this->config->pages->details->reviewsLimit;
      $position = AdReviews::getReviewsPosition ($ad->getAdID (), $reviewID, $this->auth->getUser ());
      
      if ($position > $limit) {
        $limit = $position;
      }
      
      $listreviews      = AdReviews::findReviewsByAdID ($ad->getAdID (), $this->auth->getUser (), $limit);
      $canReviewRegular = AdReviews::getUserProfileReviewCount ($ad->getAdID ());
    }
 
    if ((($reviewer = $this->auth->getUser ()) !== false) && $reviewer->isRegular () && $reviewer->isVerified ()) {
      $userCanReview = !AdReviews::getUserHaveAdReviews ($reviewer->getUserID (), $ad->getAdID ());
    }
    
    if ($ad->isAgency ()) {
      $agencyTotalReviews = AgencyReviews::avgReviews ($ad->getUserID ());
      
      if ($reviewer && $reviewer->isRegular () && $reviewer->isVerified ()) {
        $rejected = ReviewStatus::REVIEW_REJECTED;
        $userCanReviewAgency = !AgencyReviews::count ("userID = {$reviewer->getUserID()} AND agencyID = {$ad->getUserID()} AND statusID != {$rejected}");
      }
    }
    
    $this->view->setVar ("totalreviews",        $totalreviews);
    $this->view->setVar ("adreviews",           $listreviews);
    $this->view->setVar ("canReviewRegular",    $canReviewRegular);
    $this->view->setVar ("userCanReview",       $userCanReview);
    $this->view->setVar ("userCanReviewAgency", $userCanReviewAgency);
    $this->view->setVar ("agencyTotalreviews",  $agencyTotalReviews);
    $this->view->setVar ("limit",               $limit);            
    $this->view->setVar ("reviewID",            $reviewID);
    $this->view->setVar ("openReviews",         ($reviewID > 0));
  }
 
  /**
   * Get account taxonomies
   * 
   * @param \PTMU\Models\Ads $ad
   * @param \PTMU\Models\Users $user
   * @param array $taxonomy
   * 
   * @returns array
   */
  protected function getAccountTaxonomies ($ad, $user, $taxonomy) {
    $userTypeTax   = $taxonomy [UserType::INDIVIDUAL_USER];
    $adCategoryTax = $taxonomy [AdCategories::ESCORTS];    
        
    if (($user->getTypeID () != UserType::AGENCY_USER) && !is_null ($ad->getCategoryID ())) {
      $adCategoryTax = $taxonomy [$ad->getCategoryID ()];      
    }
    
    if (!is_null ($user->getTypeID ())) {
      $userTypeTax = $taxonomy [$user->getTypeID ()];
    }
    
    $accountTaxonomies = array (
      "escortsTax"        => $taxonomy [AdCategories::ESCORTS],
      "massageTax"        => $taxonomy [AdCategories::MASSAGE],
      "individualUserTax" => $taxonomy [UserType::INDIVIDUAL_USER],
      "agencyUserTax"     => $taxonomy [UserType::AGENCY_USER],
      "userTypeTax"       => $userTypeTax,
      "genderMaleTax"     => $taxonomy [Gender::GENDER_MALE],
      "incallOutcallTax"  => $taxonomy [AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS],
      "oneHourPricingTax" => $taxonomy [AdPricingLevel::AD_PRICING_1_HOUR],
      "adCategoryTax"     => $adCategoryTax,      
    );
    
    return $accountTaxonomies;
  }
  
  /**
   * Get attributes
   * 
   * @param \PTMU\Models\Ads $ad
   * @param array $taxonomy
   * 
   * @returns object
   */
  protected function getAttributes ($ad, $taxonomy) {
    $pricings           = $ad->getPrices ();    
    $anyTimeTax         = $taxonomy [Taxonomy::HOUR_ANYTIME];
    $hoursRangeTax      = $taxonomy [Taxonomy::HOURS_RANGE]["metaData"]["list"];    
    $adAvailabilitiDays = array ();    
    $adPricings         = array ();
 
    $hoursRange = array (array (
      "value" => $anyTimeTax ["code"],
      "name"  => $anyTimeTax ["name"],
    ));
 
    $firstHoursItem = array(
      "value" => date ('H:i:s', strtotime ($hoursRangeTax [0])),
      "text"  => date ('g a',   strtotime ($hoursRangeTax [0])),
    );
 
    $lastHoursItem = array(
      "value" => date ('H:i:s', strtotime (end ($hoursRangeTax))),
      "text"  => date ('g a',   strtotime (end ($hoursRangeTax))),
    );
 
    foreach ($hoursRangeTax as $item) {
      $hoursRange [] = array(
        "value" => date ('H:i:s', strtotime ($item)),
        "name" =>  date ('g a',   strtotime ($item))
      );
    }
 
    foreach ($ad->getAvailabilities () as $item) {
      $adAvailabilitiDays [$item->getAvailabilityDayID ()] = array(
        "from"      => $item->getFromTime ("H:i:s"),
        "to"        => $item->getToTime ("H:i:s"),
        "isAnyTime" => ($item->getIsAnyTime () == 1)
      );
    }
 
    foreach ($pricings as $item) {
      $adPricings [$item->getPricingPeriodID ()] = array(
        "incall"  => $item->getIncallPrice (),
        "outcall" => $item->getOutcallPrice (),
      );
    }
    
    return (object) array (
      'anyTimeTax'         => $anyTimeTax,
      'hoursRange'         => $hoursRange,
      'firstHoursItem'     => $firstHoursItem,
      'lastHoursItem'      => $lastHoursItem,
      'hoursRange'         => $hoursRange,
      'adAvailabilitiDays' => $adAvailabilitiDays,
      'adPricings'         => $adPricings
    );
  }
  
  /**
   * Get user for new add
   *
   * @return \PTMU\Models\Users
   */
  protected function getUserForNewAd () {
    if ($identity = $this->auth->getIdentity ()) {
      return Users::findFirstByUserID ($identity ["id"]);
    } else {
      return new Users ();
    }
  }
  
  /**
   * Get available categories
   *
   * @param integer $userID
   * @param array $taxonomy
   * 
   * @return array
   */
  protected function getAvailableCategories ($userID, $taxonomy) {
    $result  = array ();
    $userAds = Ads::findUserAds ($userID);    
 
    $allowedAdStatuses = array (
      AdStatus::AD_ACTIVE,
      AdStatus::AD_EDITED,
      AdStatus::AD_PENDING,
      AdStatus::AD_INCOMPLETE
    );
 
    foreach ([$taxonomy [AdCategories::ESCORTS], $taxonomy [AdCategories::MASSAGE]] as $category) {
      foreach ($userAds as $userAd) {
        if (($userAd->getCategoryID () == $category ["taxonomyID"]) && in_array ($userAd->getStatusID (), $allowedAdStatuses)) {
          continue 2;
        }
      }
 
      $result [] = $category ["code"];
    }
    
    return $result;
  }
 
  /**
   * Get backUrl
   *
   * @param \PTMU\Models\Ads $ad
   * @return string
   */
  protected function getBackUrl ($ad) {
    $taxonomy = TaxonomyModel::getTaxonomy ();
    $referrer = $this->request->getHTTPReferer ();
    $urlPath  = parse_url ($referrer, PHP_URL_PATH);
    $router   = $this->di->get ('router');
    $genderID = $ad->getGenderID ();    
    $backUrl  = '/';    
 
    $router->handle ($urlPath);
 
    if ($router->getControllerName () != 'home') {
      if ($router->getControllerName () == 'index') {
        $backUrl = "{$referrer}#item-{$ad->getAdID ()}";
      } elseif($router->getControllerName () == 'search' ){
        $backUrl = $referrer;
      }
      else {
        $taxCodesConvert = [
          'GENDER_MALE'       => 'male',
          'GENDER_TRANSEXUAL' => 'transexual',
        ];
 
        if ($genderID != Gender::GENDER_FEMALE) {
          $backUrl .= $taxCodesConvert [$taxonomy [$genderID]["code"]] . '-';
        }
 
        $backUrl .= mb_strtolower ($taxonomy [$ad->getCategoryID ()]["code"]) . '/';
        $backUrl .= $ad->getParentLocaion ()["code"];
      }
    }
    
    return $backUrl;
  }
  
  /**
   * Return breadcrum for current page
   *
   * @param PTMU\Models\Ads $ad
   * @return array
   */
  protected function getBreadcrumb ($ad) {
    $breadcrumb = new Breadcrumb ();
 
    $breadcrumb->setCategory ($ad->getCategoryID ());
    $breadcrumb->setGender ($ad->getGenderID ());
    $breadcrumb->setAvailability ($ad->getAvailabilityID ());
    $breadcrumb->setLocation ($ad->getLocationID ());
    $breadcrumb->setTitle ("{$ad->getUserName ()} (Ad #{$ad->getAdID ()})");
 
    return $breadcrumb->getBreadcrumb ();
  }
}
#16PTMU\Models\Ads::findFirstByAdID(56)
/var/www/html/ptmu/frontend/controllers/PostController.php (57)
<?php
 
namespace PTMU\Frontend\Controllers;
 
use Phalcon\DI;
use Phalcon\Mvc\View;
use PTMU\Models\Ads;
use PTMU\Models\Users;
use PTMU\Models\AdReviews;
use PTMU\Models\AgencyReviews;
use PTMU\Models\SearchSeo;
use PTMU\Forms\AdsForm;
use PTMU\Forms\UsersForm;
use PTMU\Taxonomy as Taxonomy;
use PTMU\Taxonomy\AdStatus;
use PTMU\Taxonomy\AdCategories;
use PTMU\Taxonomy\AdAvailability;
use PTMU\Taxonomy\AdPricingLevel;
use PTMU\Taxonomy\AdAvailabilityDay;
use PTMU\Taxonomy\AdEthnicity;
use PTMU\Taxonomy\Gender;
use PTMU\Taxonomy\UserType;
use PTMU\Taxonomy\UserStatus;
use PTMU\Taxonomy\ReviewStatus;
use PTMU\Models\Locations;
use PTMU\Models\Taxonomy as TaxonomyModel;
use PTMU\Models\Locations as LocationsModel;
use PTMU\Taxonomy\LocationType;
use PTMU\Breadcrumb\Breadcrumb;
use PTMU\Taxonomy\AdUpdateType as AdUpdateType;
use PTMU\Utils\Utils;
use PTMU\Pages\SummaryHelper;
 
class PostController extends ControllerBase {
 
  protected $seoLinks;
 
 
  /**
   * index action
   */
  public function indexAction () {
    $this->response->setContent ("Post controller");
 
    return $this->response;
  }
 
  /**
   * view action
   */
  public function viewAction () {
    $id       = $this->dispatcher->getParam ("id");  
    $tilte    = $this->dispatcher->getParam ("title");      
    $category = $this->dispatcher->getParam ("category");
    $hash     = $this->dispatcher->getParam ("hash");
    
    if (($ad = Ads::findFirstByAdID ($id)) === false) {
      return $this->forwardToNotFound ();
    }
 
    // Redirect to summary if ad is not reachable anymore    
    if ($this->isInactiveAd ($ad)) {
      $location = LocationsModel::getLocationPath ($ad->getLocationID ());
      return $this->response->redirect ("{$ad->getCategoryUri ()}/{$location [0]['code']}", false, 301);
    }
    
    $queryURL = $this->request->getQuery ()['_url'];
    $reviewID = 0;
    
    // Check review hash
    if ((strpos ($hash, 'review-') === 0) && ($reviewID = intval (substr ($hash, 7)))) {
      $queryURL = substr ($queryURL, 0, -(strlen ($hash) + 1));
    }
 
    // Check ad details and forward to new url if ad details was changed
    if ($queryURL != $ad->getDetailsURL ()) {
      return $this->response->redirect ($ad->getDetailsURL (false), false, 302);
    }
 
    $updates    = $ad->getStatusUpdates (null);
    $relatedAds = $this->getRelatedAds ($ad);
 
    $this->view->pick (["post/detail"]);
        
    // JS assets
    $this->_jsAssets [] = 'jquery.sticky-kit';
    $this->_jsAssets [] = 'jquery.preload';
    $this->_jsAssets [] = 'detail';
 
    $this->view->setVar ("ad",                  $ad);
    $this->view->setVar ("updates",             $updates);
    $this->view->setVar ('relatedAdsPreloaded', $relatedAds ['relatedAdsPreloaded']);    
    $this->view->setVar ('breadcrumbs',         $this->getBreadcrumb ($ad));
    $this->view->setVar ("backUrl",             $this->getBackUrl ($ad));    
    $this->view->setVar ('jsAssets',            $this->_jsAssets);
 
 
    if($ad->getCategoryID() == AdCategories::ESCORTS) {
      $this->getPopularDetailLinks($ad);
    }
 
    $this->view->setVar ('seoLinks',            $this->seoLinks);
 
    $this->view->setVar ("detailsPageData", array(
      "biographyLinesLimit"   => $this->config->pages->details->biographyLinesLimit,
      "commentsInitialItems"  => $this->config->pages->comments->initialItems,
      "commentsAjaxLoadItems" => $this->config->pages->comments->ajaxLoadItems,
      "newSinceDate"          => $updates ["nextUpdateDate"],
      "relatedAdsIDs"         => $relatedAds ['relatedAdsIDs'],
      "adID"                  => $ad->getAdID (),
      "isAdInUse"             => $ad->getAdID () == $this->getAdInUseID (),
      "identity"              => !is_null ($this->auth->getIdentity ()),
      "isVerified"            => $this->auth->isVerified (),
      "isWatchlisted"         => $this->auth->isWatchlisted (),
      "reviewID"              => $reviewID,
    ));
 
    $this->setReviewsVariablesInView ($ad, $reviewID);  
    $this->setVariablesInView ();
    
    // Getting meta parts
    $metaParts = Utils::getDetailPageMetaParts ($ad, $this->translations);
        
    // Page title and meta description
    $this->view->setVar ('pageTitle',       sprintf ($this->translations ['details-page-title'], $metaParts->title, $metaParts->variant, $metaParts->city));
    $this->view->setVar ('metaDescription', sprintf ($this->translations ['details-page-meta'], $metaParts->userName, $metaParts->age, $metaParts->variant, $metaParts->city, $metaParts->biography));
  }
 
  public function getPopularDetailLinks ( $ad ){
   $ethnicitySeo = [];
   $bodySeo      = [];
   $ageSeo       = [];
   $config       = DI::getDefault ()->getConfig ();
 
    $this->seoLinks[0] = ['link' =>$ad->getCategoryUri (true)."/".$ad->getLocationPath()[0]['code'], 'name'=> $ad->getCategory().' in '.$ad->getLocationPath()[0]['name'] ];
 
    foreach (searchSeo::find () as $searchSeo) {
      $params = $searchSeo->getSearchParams();
 
      if(in_array($ad->getCategoryID(),$params) && in_array($ad->getEthnicityID(),$params)){
 
        $ethnicitySeo[]= $searchSeo->getSearchSeoID();
        $pageHelper = new SummaryHelper (DI::getDefault()->getModelsManager ()->getReadConnection (), $params, 0);
        $results    = $pageHelper->extendedSearchFilter (['locationids']);
 
        $anchor = str_ireplace("%city%","in ". $ad->getLocationPath()[0]['name'], $searchSeo->getAnchor(false));
 
        if($results ['filteredIds']['LOCATIONIDS'][$ad->getLocationPath()[0]['locationID']]>$config->popularSearch->minAdsCount and $searchSeo->getLocationID() == null){
         $searchSeo->setLocationID ($ad->getLocationPath()[0]['locationID']);
         $this->seoLinks[1] = ['link'=>$ad->getCategoryUri ().'/'.$ad->getLocationPath()[0]['code'].'/'.$searchSeo->getDestinationUrl(), 'name'=>$anchor];
        } elseif ($searchSeo->getLocationID() != null){
         $this->seoLinks[1] = ['link'=>$ad->getCategoryUri ().'/'.$searchSeo->getDestinationUrl(), 'name'=>$searchSeo->getAnchor(true)];
        }
      }
 
      if(in_array($ad->getCategoryID(),$params) && in_array($ad->getBodyTypeID(),$params)){
        $bodySeo[]= $searchSeo->getSearchSeoID();
 
        $pageHelper = new SummaryHelper (DI::getDefault()->getModelsManager ()->getReadConnection (), $params, 0);
        $results    = $pageHelper->extendedSearchFilter (['locationids']);
 
        $anchor = str_ireplace("%city%","in ". $ad->getLocationPath()[0]['name'], $searchSeo->getAnchor(false));
 
        if($results ['filteredIds']['LOCATIONIDS'][$ad->getLocationPath()[0]['locationID']]>$config->popularSearch->minAdsCount and $searchSeo->getLocationID() == null){
          $searchSeo->setLocationID ($ad->getLocationPath()[0]['locationID']);
          $this->seoLinks[2] = ['link'=>$ad->getCategoryUri ().'/'.$ad->getLocationPath()[0]['code'].'/'.$searchSeo->getDestinationUrl(), 'name'=>$anchor];
        }
        elseif($searchSeo->getLocationID() != null){
          $this->seoLinks[2] = ['link'=>$ad->getCategoryUri ().'/'.$searchSeo->getDestinationUrl(), 'name'=>$searchSeo->getAnchor(true)];
        }
      }
 
      if(in_array($ad->getCategoryID(),$params) && intval($ad->getAge()) >= 18 and intval($ad->getAge()) <= 19 && in_array($searchSeo->getSearchSeoID(),[16,31])){
        $ageSeo[]= $searchSeo;
 
 
        $pageHelper = new SummaryHelper (DI::getDefault()->getModelsManager ()->getReadConnection (), $params, 0);
        $results    = $pageHelper->extendedSearchFilter (['locationids']);
        $anchor = str_ireplace("%city%","in ". $ad->getLocationPath()[0]['name'], $searchSeo->getAnchor(false));
 
        if($results ['filteredIds']['LOCATIONIDS'][$ad->getLocationPath()[0]['locationID']]>$config->popularSearch->minAdsCount and $searchSeo->getLocationID() == null){
          $searchSeo->setLocationID ($ad->getLocationPath()[0]['locationID']);
          $this->seoLinks[3] = ['link'=>$ad->getCategoryUri ().'/'.$ad->getLocationPath()[0]['code'].'/'.$searchSeo->getDestinationUrl(), 'name'=>$anchor];
        }
        elseif($searchSeo->getLocationID() != null){
          $this->seoLinks[3] = ['link'=>$ad->getCategoryUri ().'/'.$searchSeo->getDestinationUrl(), 'name'=>$searchSeo->getAnchor(true)];
        }
      }
 
      if(in_array($ad->getCategoryID(),$params) && intval($ad->getAge()) >= 36 and intval($ad->getAge()) <= 60 && in_array($searchSeo->getSearchSeoID(), [1,7]) ){
        $ageSeo[]= $searchSeo;
 
 
        $pageHelper = new SummaryHelper (DI::getDefault()->getModelsManager ()->getReadConnection (), $params, 0);
        $results    = $pageHelper->extendedSearchFilter (['locationids']);
 
 
        $anchor = str_ireplace("%city%","in ". $ad->getLocationPath()[0]['name'], $searchSeo->getAnchor(false));
 
        if($results ['filteredIds']['LOCATIONIDS'][$ad->getLocationPath()[0]['locationID']]>$config->popularSearch->minAdsCount and $searchSeo->getLocationID() == null){
          $searchSeo->setLocationID ($ad->getLocationPath()[0]['locationID']);
          $this->seoLinks[3] = ['link'=>$ad->getCategoryUri ().'/'.$ad->getLocationPath()[0]['code'].'/'.$searchSeo->getDestinationUrl(), 'name'=>$anchor];
        }
        elseif($searchSeo->getLocationID() != null){
          $this->seoLinks[3] = ['link'=>$ad->getCategoryUri ().'/'.$searchSeo->getDestinationUrl(), 'name'=>$searchSeo->getAnchor(true)];
        }
      }
    }
  }
 
  /**
   * Show form for post new ad
   */
  public function addAction () {
    $user          = $this->getUserForNewAd ();        
    $ad            = new Ads ();
    $adsForm       = new AdsForm ($ad);
    $usersForm     = new UsersForm ($user);    
    $taxonomy      = TaxonomyModel::getTaxonomy ();
 
    if ($this->_mobileApplication) {
      $this->view->setViewsDir($this->di->getConfig()->mobileModule->viewsDir);
    }
    $this->view->pick (["post/adsForm"]);
        
    // JS assets
    $this->_jsAssets [] = 'postingForm';
 
    $this->view->setVar ("ad",                  $ad);
    $this->view->setVar ("adsForm",             $adsForm);
    $this->view->setVar ("usersForm",           $usersForm);
    $this->view->setVar ("taxonomyTree",        TaxonomyModel::getTaxonomyAsTree ());
    $this->view->setVar ("currencySymbol",      $this->location->getCurrencySymbol ());
    $this->view->setVar ("locationsLvl1",       LocationsModel::getLocations ($this->location->getID ()));
    $this->view->setVar ("locations",           LocationsModel::getLocations (null, true));
    $this->view->setVar ("availableCategories", $this->getAvailableCategories ($user->getUserID (), $taxonomy));
    $this->view->setVar ("accountTaxonomies",   $this->getAccountTaxonomies ($ad, $user, $taxonomy));
    $this->view->setVar ("isAgency",            ($user->getTypeID () == UserType::AGENCY_USER));
    $this->view->setVar ('jsAssets',            $this->_jsAssets);    
    
    // Set proper application version for alternate/canonical link
    $this->view->setVar (Utils::getVersionVar (), true);
    
    // Page title and meta description
    $this->view->setVar ("pageTitle",       $this->translations ['posting-page-title']);
    $this->view->setVar ("metaDescription", $this->translations ['posting-page-meta']);
  }
 
  /**
   * Show form for ad update
   */
  public function updateAction ($adID) {
    if (!($ad = Ads::findFirstByAdID ($adID)) || !$this->auth->isLoggedUser ($ad->getUserID ())) {
      return $this->forwardToNotFound ();
    }
 
    $adsForm   = new AdsForm ($ad);
    $usersForm = new UsersForm ($ad->user);
 
    $taxonomyTree = TaxonomyModel::getTaxonomyAsTree ();
    $taxonomy     = TaxonomyModel::getTaxonomy ();
    $attributes   = $this->getAttributes ($ad, $taxonomy);
 
    //if ($this->_mobileApplication) {
    //  $this->view->setViewsDir($this->di->getConfig()->mobileModule->viewsDir);
    //}
 
    $this->view->pick (["post/adsForm"]);
        
    // JS assets
    $this->_jsAssets [] = 'postingForm';
 
    $this->view->setVar ("ad",                $ad);
    $this->view->setVar ("adsForm",           $adsForm);
    $this->view->setVar ("usersForm",         $usersForm);
    $this->view->setVar ("taxonomyTree",      $taxonomyTree);
    $this->view->setVar ("currencySymbol",    $this->location->getCurrencySymbol ());
    $this->view->setVar ("locationsLvl1",     LocationsModel::getLocations ($this->location->getID ()));
    $this->view->setVar ("locations",         LocationsModel::getLocations ());
    $this->view->setVar ("locationPath",      LocationsModel::getLocationPath ($ad->getLocationID (), array (LocationType::STATE)));
    $this->view->setVar ("adCategory",        $taxonomy [$ad->getCategoryID ()]);
    $this->view->setVar ("adUserType",        $taxonomy [$ad->user->getTypeID ()]);
    $this->view->setVar ("accountTaxonomies", $this->getAccountTaxonomies ($ad, $ad->user, $taxonomy));
    $this->view->setVar ("isAgency",          ($ad->user->getTypeID () == UserType::AGENCY_USER));
    $this->view->setVar ('jsAssets',          $this->_jsAssets);
 
    $this->view->setVar ("availabilityPricingData", array (
      "availabilityOptions"       => TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::AD_AVAILABILITY_DAY),
      "availabilityForOptions"    => AdAvailability::getMembers (),
      "pricingOptions"            => TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::AD_PRICING_LEVEL),
      "hoursRange"                => $attributes->hoursRange,
      "adPricings"                => $attributes->adPricings,
      "adAvailabilitiDays"        => $attributes->adAvailabilitiDays,
      "adID"                      => $ad->getAdID (),
      "hourPricingTax"            => $taxonomy [AdPricingLevel::AD_PRICING_1_HOUR],
      "availabilityEverydayTax"   => $taxonomy [AdAvailabilityDay::AD_AVAILABILITY_EVERYDAY],
      "availabilityIncallsTax"    => $taxonomy [AdAvailability::AD_AVAILABILITY_INCALLS],
      "availabilityOutcallsTax"   => $taxonomy [AdAvailability::AD_AVAILABILITY_OUTCALLS],
      "anyTimeTax"                => $attributes->anyTimeTax,
      "firstHoursItem"            => $attributes->firstHoursItem,
      "lastHoursItem"             => $attributes->lastHoursItem,
      "timeAfterAnyTimeUncheck"   => '23:00:00',
    ));
 
    // Page title and meta description
    $this->view->setVar ("pageTitle",       $this->translations ['posting-page-title']);
    $this->view->setVar ("metaDescription", $this->translations ['posting-page-meta']);
  }
  
  /**
   * Show form for upload pictures
   */
  public function postPicturesAction ($adID) {
    if (!($ad = Ads::findFirstByAdID ($adID)) || !$this->auth->isLoggedUser ($ad->getUserID ())) {
      return $this->forwardToNotFound ();
    }
    if ($this->_mobileApplication) {
      $this->view->setViewsDir($this->di->getConfig()->mobileModule->viewsDir);
    }
 
    $this->view->pick (["post/postPictures"]);
        
    // JS assets
    $this->_jsAssets [] = 'postPictures';
 
    $this->view->setVar ("ad",       $ad);
    $this->view->setVar ('jsAssets', $this->_jsAssets);
    
    $this->view->setVar ("requiredPicturesCounts", array (
      "requiredPicturesCount"       => $this->config->pages->posting->requiredPicturesCount,
      "requiredPublicPicturesCount" => $this->config->pages->posting->requiredPublicPicturesCount,
    ));
    
    // Page title and meta description
    if ($this->_mobileApplication) {
      $this->view->setVar ("pageTitle",       $this->translations ['mobile-upload-photos-page-title']);
      $this->view->setVar ("metaDescription", $this->translations ['mobile-upload-photos-page-meta']);
    } else {
      $this->view->setVar ("pageTitle",       $this->translations ['upload-photos-page-title']);
      $this->view->setVar ("metaDescription", $this->translations ['upload-photos-page-meta']);
    }
  }
 
  /**
   * Get ads that related to provided
   */
  protected function getRelatedAds ($ad) {
    $locations           = Locations::getLocationPath ($ad->getLocationID ());
    $gender              = $ad->getGenderID ();
    $location            = $locations[0]['locationID'];
    $category            = $ad->getCategoryID ();
    $status              = implode (',', [AdStatus::AD_ACTIVE, AdStatus::AD_EDITED]);
    $userStatus          = UserStatus::VERIFIED;
    $excludeAdID         = $ad->getAdID ();
    $relatedAdsIDs       = array ();
    $relatedAdsPreloaded = array ();
 
    $relatedAds = $this->modelsManager->getReadConnection (null)->query ("
      select spx_ads.AdID
      from spx_ads
      where query='!filter=indexID,{$excludeAdID};filter=StatusID,{$status};filter=UserStatusID,{$userStatus};filter=CategoryID,{$category};filter=GenderID,{$gender};filter=LocationID,{$location};sort=extended:@random;limit=2000;maxmatches=2000'
    ")->fetchAll ();
 
    foreach ($relatedAds as $ad) {
      $relatedAdsIDs [] = $ad ['AdID'];
    }
 
    if (!empty ($relatedAdsIDs)) {
      $pageHelper   = new SummaryHelper ($this->getReadConnection ());
      $generatedAds = $pageHelper->generateAdsByIDs (array (), array_slice ($relatedAdsIDs, 0, $this->config->pages->details->relatedAdsLimit));
 
      foreach ($generatedAds ['ads'] as $ad) {
        $relatedAdsPreloaded [] = array (
          'userName' => $ad->getUserName (),
          'picURL'   => "/{$ad->getPicturesUri ()}/{$ad->getMainPictureThumbnailFileName ()}",
          'adURL'    => $ad->getDetailsURL (),
          'city'     => $locations [0]['name'],
        );
      }
    }
 
    return array (
      'relatedAdsIDs'       => $relatedAdsIDs,
      'relatedAdsPreloaded' => $relatedAdsPreloaded
    );
  }
  
  /**
   * Returns true if ad is inactive
   * 
   * @param \PTMU\Models\Ads $ad
   * @returns boolean
   */
  protected function isInactiveAd ($ad) {
    $adIsActive   = in_array ($ad->getStatusID (), array (AdStatus::AD_ACTIVE, AdStatus::AD_EDITED));
    $userIsActive = ($ad->user->getStatusID () == UserStatus::VERIFIED);
    $logedAdOwner = ($this->auth->getID () == $ad->user->getUserID ());
 
    return ((((!$adIsActive || !$userIsActive) && !$logedAdOwner)) || ($ad->getStatusID () == AdStatus::AD_DELETED));
  }
  
  /**
   * Set class dependency variables in view
   */
  protected function setVariablesInView () {
    $taxonomyTree = TaxonomyModel::getTaxonomyAsTree ();    
    
    $this->view->setVar ("user",                Users::findFirst($this->auth->getID ()));
    $this->view->setVar ("statusUpdateTaxID",   AdUpdateType::STATUS_UPDATE);
    $this->view->setVar ("profileUpdateTaxID",  AdUpdateType::PROFILE_UPDATE);
    $this->view->setVar ("cities",              LocationsModel::getCities ($this->location->getID ()));
    $this->view->setVar ("availabilityOptions", TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::AD_AVAILABILITY_DAY));
    $this->view->setVar ("pricingOptions",      TaxonomyModel::getTaxonomyOptions ($taxonomyTree, Taxonomy::AD_PRICING_LEVEL));
    $this->view->setVar ("anyTimeTax",          $taxonomyTree [Taxonomy::HOUR_ANYTIME]);
    $this->view->setVar ("canReply",            false);
    $this->view->setVar ('mobileVersion',       true);        
  }
  
  /**
   * Set reviews variables in view
   * 
   * @param \PTMU\Models\Ads $ad
   * @param integer $reviewID
   */
  protected function setReviewsVariablesInView ($ad, $reviewID) {
    $listreviews         = array();
    $canReviewRegular    = array ();    
    $userCanReviewAgency = false;
    $userCanReview       = false;
    $agencyTotalReviews  = null;    
    $limit               = null;    
 
    $totalreviews = AdReviews::avgReviews ($ad->getAdID (), $this->auth->getUser());
        
    if ($totalreviews ['count']) {
      $limit    = $this->config->pages->details->reviewsLimit;
      $position = AdReviews::getReviewsPosition ($ad->getAdID (), $reviewID, $this->auth->getUser ());
      
      if ($position > $limit) {
        $limit = $position;
      }
      
      $listreviews      = AdReviews::findReviewsByAdID ($ad->getAdID (), $this->auth->getUser (), $limit);
      $canReviewRegular = AdReviews::getUserProfileReviewCount ($ad->getAdID ());
    }
 
    if ((($reviewer = $this->auth->getUser ()) !== false) && $reviewer->isRegular () && $reviewer->isVerified ()) {
      $userCanReview = !AdReviews::getUserHaveAdReviews ($reviewer->getUserID (), $ad->getAdID ());
    }
    
    if ($ad->isAgency ()) {
      $agencyTotalReviews = AgencyReviews::avgReviews ($ad->getUserID ());
      
      if ($reviewer && $reviewer->isRegular () && $reviewer->isVerified ()) {
        $rejected = ReviewStatus::REVIEW_REJECTED;
        $userCanReviewAgency = !AgencyReviews::count ("userID = {$reviewer->getUserID()} AND agencyID = {$ad->getUserID()} AND statusID != {$rejected}");
      }
    }
    
    $this->view->setVar ("totalreviews",        $totalreviews);
    $this->view->setVar ("adreviews",           $listreviews);
    $this->view->setVar ("canReviewRegular",    $canReviewRegular);
    $this->view->setVar ("userCanReview",       $userCanReview);
    $this->view->setVar ("userCanReviewAgency", $userCanReviewAgency);
    $this->view->setVar ("agencyTotalreviews",  $agencyTotalReviews);
    $this->view->setVar ("limit",               $limit);            
    $this->view->setVar ("reviewID",            $reviewID);
    $this->view->setVar ("openReviews",         ($reviewID > 0));
  }
 
  /**
   * Get account taxonomies
   * 
   * @param \PTMU\Models\Ads $ad
   * @param \PTMU\Models\Users $user
   * @param array $taxonomy
   * 
   * @returns array
   */
  protected function getAccountTaxonomies ($ad, $user, $taxonomy) {
    $userTypeTax   = $taxonomy [UserType::INDIVIDUAL_USER];
    $adCategoryTax = $taxonomy [AdCategories::ESCORTS];    
        
    if (($user->getTypeID () != UserType::AGENCY_USER) && !is_null ($ad->getCategoryID ())) {
      $adCategoryTax = $taxonomy [$ad->getCategoryID ()];      
    }
    
    if (!is_null ($user->getTypeID ())) {
      $userTypeTax = $taxonomy [$user->getTypeID ()];
    }
    
    $accountTaxonomies = array (
      "escortsTax"        => $taxonomy [AdCategories::ESCORTS],
      "massageTax"        => $taxonomy [AdCategories::MASSAGE],
      "individualUserTax" => $taxonomy [UserType::INDIVIDUAL_USER],
      "agencyUserTax"     => $taxonomy [UserType::AGENCY_USER],
      "userTypeTax"       => $userTypeTax,
      "genderMaleTax"     => $taxonomy [Gender::GENDER_MALE],
      "incallOutcallTax"  => $taxonomy [AdAvailability::AD_AVAILABILITY_INCALLS_OUTCALLS],
      "oneHourPricingTax" => $taxonomy [AdPricingLevel::AD_PRICING_1_HOUR],
      "adCategoryTax"     => $adCategoryTax,      
    );
    
    return $accountTaxonomies;
  }
  
  /**
   * Get attributes
   * 
   * @param \PTMU\Models\Ads $ad
   * @param array $taxonomy
   * 
   * @returns object
   */
  protected function getAttributes ($ad, $taxonomy) {
    $pricings           = $ad->getPrices ();    
    $anyTimeTax         = $taxonomy [Taxonomy::HOUR_ANYTIME];
    $hoursRangeTax      = $taxonomy [Taxonomy::HOURS_RANGE]["metaData"]["list"];    
    $adAvailabilitiDays = array ();    
    $adPricings         = array ();
 
    $hoursRange = array (array (
      "value" => $anyTimeTax ["code"],
      "name"  => $anyTimeTax ["name"],
    ));
 
    $firstHoursItem = array(
      "value" => date ('H:i:s', strtotime ($hoursRangeTax [0])),
      "text"  => date ('g a',   strtotime ($hoursRangeTax [0])),
    );
 
    $lastHoursItem = array(
      "value" => date ('H:i:s', strtotime (end ($hoursRangeTax))),
      "text"  => date ('g a',   strtotime (end ($hoursRangeTax))),
    );
 
    foreach ($hoursRangeTax as $item) {
      $hoursRange [] = array(
        "value" => date ('H:i:s', strtotime ($item)),
        "name" =>  date ('g a',   strtotime ($item))
      );
    }
 
    foreach ($ad->getAvailabilities () as $item) {
      $adAvailabilitiDays [$item->getAvailabilityDayID ()] = array(
        "from"      => $item->getFromTime ("H:i:s"),
        "to"        => $item->getToTime ("H:i:s"),
        "isAnyTime" => ($item->getIsAnyTime () == 1)
      );
    }
 
    foreach ($pricings as $item) {
      $adPricings [$item->getPricingPeriodID ()] = array(
        "incall"  => $item->getIncallPrice (),
        "outcall" => $item->getOutcallPrice (),
      );
    }
    
    return (object) array (
      'anyTimeTax'         => $anyTimeTax,
      'hoursRange'         => $hoursRange,
      'firstHoursItem'     => $firstHoursItem,
      'lastHoursItem'      => $lastHoursItem,
      'hoursRange'         => $hoursRange,
      'adAvailabilitiDays' => $adAvailabilitiDays,
      'adPricings'         => $adPricings
    );
  }
  
  /**
   * Get user for new add
   *
   * @return \PTMU\Models\Users
   */
  protected function getUserForNewAd () {
    if ($identity = $this->auth->getIdentity ()) {
      return Users::findFirstByUserID ($identity ["id"]);
    } else {
      return new Users ();
    }
  }
  
  /**
   * Get available categories
   *
   * @param integer $userID
   * @param array $taxonomy
   * 
   * @return array
   */
  protected function getAvailableCategories ($userID, $taxonomy) {
    $result  = array ();
    $userAds = Ads::findUserAds ($userID);    
 
    $allowedAdStatuses = array (
      AdStatus::AD_ACTIVE,
      AdStatus::AD_EDITED,
      AdStatus::AD_PENDING,
      AdStatus::AD_INCOMPLETE
    );
 
    foreach ([$taxonomy [AdCategories::ESCORTS], $taxonomy [AdCategories::MASSAGE]] as $category) {
      foreach ($userAds as $userAd) {
        if (($userAd->getCategoryID () == $category ["taxonomyID"]) && in_array ($userAd->getStatusID (), $allowedAdStatuses)) {
          continue 2;
        }
      }
 
      $result [] = $category ["code"];
    }
    
    return $result;
  }
 
  /**
   * Get backUrl
   *
   * @param \PTMU\Models\Ads $ad
   * @return string
   */
  protected function getBackUrl ($ad) {
    $taxonomy = TaxonomyModel::getTaxonomy ();
    $referrer = $this->request->getHTTPReferer ();
    $urlPath  = parse_url ($referrer, PHP_URL_PATH);
    $router   = $this->di->get ('router');
    $genderID = $ad->getGenderID ();    
    $backUrl  = '/';    
 
    $router->handle ($urlPath);
 
    if ($router->getControllerName () != 'home') {
      if ($router->getControllerName () == 'index') {
        $backUrl = "{$referrer}#item-{$ad->getAdID ()}";
      } elseif($router->getControllerName () == 'search' ){
        $backUrl = $referrer;
      }
      else {
        $taxCodesConvert = [
          'GENDER_MALE'       => 'male',
          'GENDER_TRANSEXUAL' => 'transexual',
        ];
 
        if ($genderID != Gender::GENDER_FEMALE) {
          $backUrl .= $taxCodesConvert [$taxonomy [$genderID]["code"]] . '-';
        }
 
        $backUrl .= mb_strtolower ($taxonomy [$ad->getCategoryID ()]["code"]) . '/';
        $backUrl .= $ad->getParentLocaion ()["code"];
      }
    }
    
    return $backUrl;
  }
  
  /**
   * Return breadcrum for current page
   *
   * @param PTMU\Models\Ads $ad
   * @return array
   */
  protected function getBreadcrumb ($ad) {
    $breadcrumb = new Breadcrumb ();
 
    $breadcrumb->setCategory ($ad->getCategoryID ());
    $breadcrumb->setGender ($ad->getGenderID ());
    $breadcrumb->setAvailability ($ad->getAvailabilityID ());
    $breadcrumb->setLocation ($ad->getLocationID ());
    $breadcrumb->setTitle ("{$ad->getUserName ()} (Ad #{$ad->getAdID ()})");
 
    return $breadcrumb->getBreadcrumb ();
  }
}
#17PTMU\Frontend\Controllers\PostController->viewAction(escorts, 56, hot-friendly-sexy-sensual-lad-avaliable-24-7-massage, 4)
#18Phalcon\Dispatcher->dispatch()
#19Phalcon\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/escorts/56/hot-friendly-sexy-sensual-lad-avaliable-24-7-massage
KeyValue
USERapache
HOME/var/www
FCGI_ROLERESPONDER
SCRIPT_FILENAME/var/www/html/public/index.php
QUERY_STRING_url=/escorts/56/hot-friendly-sexy-sensual-lad-avaliable-24-7-massage
REQUEST_METHODGET
CONTENT_TYPE
CONTENT_LENGTH
SCRIPT_NAME/index.php
REQUEST_URI/escorts/56/hot-friendly-sexy-sensual-lad-avaliable-24-7-massage
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_PORT51260
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_FLOAT1487645486.9952
REQUEST_TIME1487645486
#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/frontend/Module.php
10/var/www/html/ptmu/common/library/Phalcon/Session/Adapter/Memcache.php
11/var/www/html/ptmu/frontend/controllers/PostController.php
12/var/www/html/ptmu/frontend/controllers/ControllerBase.php
13/var/www/html/ptmu/common/models/Translations.php
14/var/www/html/ptmu/common/models/CacheableModel.php
15/var/www/html/ptmu/common/library/Phalcon/Logger/Adapter/Dummy.php
16/var/www/html/ptmu/common/library/Auth/Auth.php
17/var/www/html/ptmu/common/models/Ads.php
18/var/www/html/ptmu/common/library/ModelsManager/ModelsManager.php
19/var/www/html/ptmu/common/library/Phalcon/Mvc/Model/MetaData/Memcache.php
20/var/www/html/ptmu/common/library/Phalcon/Mvc/Model/MetaData/Base.php
Memory
Usage2359296