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\Users: ))
#11Phalcon\Mvc\Model->getReadConnection()
#12Phalcon\Mvc\Model\Query->_executeSelect(Array([models] => Array([0] => PTMU\Models\Users), [tables] => Array([0] => users), [columns] => Array([pTMU\Models\Users] => Array([type] => object, [model] => PTMU\Models\Users, [column] => users, [balias] => pTMU\Models\Users)), [where] => Array([type] => binary-op, [op] => AND, [left] => Array([type] => binary-op, [op] => AND, [left] => Array(), [right] => Array()), [right] => Array([type] => parentheses, [left] => Array())), [limit] => Array([number] => 1)), Array([userID] => 11502, [statusBlocked] => 100204, [statusDeleted] => 100203), null)
#13Phalcon\Mvc\Model\Query->execute(Array([userID] => 11502, [statusBlocked] => 100204, [statusDeleted] => 100203), null)
#14Phalcon\Mvc\Model::findFirst(Array([conditions] => (userID = :userID:) and (statusID <> :statusBlocked:) and (statusID <> :statusDeleted:), [bind] => Array([userID] => 11502, [statusBlocked] => 100204, [statusDeleted] => 100203)))
/var/www/html/ptmu/common/models/Users.php (909)
<?php
 
namespace PTMU\Models;
 
use PTMU\Taxonomy\PhonePreference;
use PTMU\Taxonomy\UserStatus;
use PTMU\Taxonomy\UserType;
use PTMU\Taxonomy\LocationType;
use PTMU\Taxonomy\AdCategories;
use PTMU\Taxonomy\Entities;
use PTMU\Taxonomy\UserAttributes;
use PTMU\Taxonomy\VerificationStatus;
use PTMU\Mail\Mail as PTMUMail;
use PTMU\Utils\Utils;
use Phalcon\Utils\Slug;
use PTMU\Taxonomy\UserTokenTypes;
use Phalcon\Db\RawValue as DBRawValue;
use Phalcon\DI;
 
class Users extends \Phalcon\Mvc\Model {
 
  /**
   *
   * @var integer
   */
  protected $userID;
   
  /**
   *
   * @var integer
   */
  protected $typeID;
   
  /**
   *
   * @var string
   */
  protected $email;
   
  /**
   *
   * @var string
   */
  protected $password;
   
  /**
   *
   * @var string
   */
  protected $name;
   
  /**
   *
   * @var integer
   */
  protected $locationID;
   
  /**
   *
   * @var integer
   */
  protected $statusID;
 
  /**
   *
   * @var string
   */
  protected $createDate;
 
  /**
   *
   * @var string
   */
  protected $verificationDate;
   
  /**
   *
   * @var string
   */
  protected $updateDate;
  
  /**
   *
   * @var string
   */
  protected $moderationDate;
  
  /**
   *
   * @var integer
   */
  protected $applicationType;
  
  /**
   *
   * @var string
   */
  protected $postingIP;
  
  /**
   *
   * @var boolean
   */
  protected $_skipUpdateDate;
 
  /**
   *
   * @var array
   */
  protected $_taxonomy;
 
  /**
   *
   * @var array
   */
  protected $_taxonomyAttributes;
 
 
  /**
   *
   * @var integer
   */
  protected $notificationVisitDate;
 
  /**
   * Method to set the value of field UserID
   *
   * @param integer $userID
   * @return $this
   */
  public function setUserID ($userID) {
    $this->userID = $userID;
    
    return $this;
  }
 
  /**
   * Method to set the value of field TypeID
   *
   * @param integer $typeID
   * @return $this
   */
  public function setTypeID ($typeID) {
    $this->typeID = $typeID;
    
    return $this;
  }
 
  /**
   * Method to set the value of field Email
   *
   * @param string $email
   * @return $this
   */
  public function setEmail ($email) {
    $this->email = $email;
    
    return $this;
  }
 
  /**
   * Method to set the value of field Password
   *
   * @param string $password
   * @return $this
   */
  public function setPassword ($password) {
    $this->password = $password;
    
    return $this;
  }
 
  /**
   * Method to set the value of field Name
   *
   * @param string $name
   * @return $this
   */
  public function setName ($name) {
    $this->name = $name;
    
    return $this;
  }
 
  /**
   * Method to set the value of field LocationID
   *
   * @param integer $locationID
   * @return $this
   */
  public function setLocationID ($locationID) {
    $this->locationID = $locationID;
    
    return $this;
  }
 
  /**
   * Method to set the value of field StatusID
   *
   * @param integer $statusID
   * @return $this
   */
  public function setStatusID ($statusID) {
    $this->statusID = $statusID;
    
    return $this;
  }
 
  /**
   * Method to set the value of field CreateDate
   *
   * @param string $createDate
   * @return $this
   */
  public function setCreateDate ($createDate) {
    $this->createDate = $createDate;
    
    return $this;
  }
 
  /**
   * Method to set the value of field VerificationDate
   *
   * @param string $createDate
   * @return $this
   */
  public function setVerificationDate ($verificationDate) {
    $this->verificationDate = $verificationDate;
    
    return $this;
  }
  
  /**
   * Method to set the value of field UpdateDate
   *
   * @param string $updateDate
   * @return $this
   */
  public function setUpdateDate ($updateDate) {
    $this->updateDate = $updateDate;
    
    return $this;
  }
 
  /**
   * Method to set the value of field ModerationDate
   *
   * @param string $moderationDate
   * @return $this
   */
  public function setModerationDate ($moderationDate) {
    $this->moderationDate = $moderationDate;
    
    return $this;
  }
  
  /**
   * Method to set the value of field ApplicationType
   *
   * @param integer $applicationType
   * @return $this
   */
  public function setApplicationType ($applicationType) {
    $this->applicationType = $applicationType;
    
    return $this;
  }
 
  /**
   * Method to set the value of field PostingIP
   *
   * @param integer $postingIP
   * @return $this
   */
  public function setPostingIP ($postingIP) {
    $this->postingIP = $postingIP;
    
    return $this;
  }
  
    /**
   * Method to set the flag for ad update date modification
   *
   * @param bool $skipUpdateDate
   * @return $this
   */
  public function setSkipUpdateDate ($skipUpdateDate) {
    $this->_skipUpdateDate = $skipUpdateDate;
  }
 
 
  /**
   * Method to set the value of field NotificationVisitDate
   *
   * @param string $notificationVisitDate
   * @return $this
   */
  public function setNotificationVisitDate ($notificationVisitDate) {
    $this->notificationVisitDate = $notificationVisitDate;
 
    return $this;
  }
  
  /**
   * Returns the value of field UserID
   *
   * @return integer
   */
  public function getUserID () {
    return $this->userID;
  }
 
  /**
   * Returns the value of field TypeID
   *
   * @return integer
   */
  public function getTypeID () {
    return $this->typeID;
  }
 
  /**
   * Returns the value of field Email
   *
   * @return string
   */
  public function getEmail () {
    return $this->email;
  }
 
  /**
   * Returns the value of field Password
   *
   * @return string
   */
  public function getPassword () {
    return $this->password;
  }
 
  /**
   * Returns the value of field Name
   *
   * @return string
   */
  public function getName () {
    return $this->name;
  }
  
  /**
   * Return user name 
   * 
   * @param integer $limit
   * @return array
   */
  public function getUserName ($limit = 0) {
    $userName = $this->getName ();    
    
    if ($limit && (mb_strlen ($userName) > $limit)) {
      $userName = trim (substr ($userName, 0, $limit))."..";       
    }
    
    return $userName;
  }
 
  /**
   * Returns the value of field LocationID
   *
   * @return integer
   */
  public function getLocationID () {
    return $this->locationID;
  }
 
  /**
   * Returns the value of field StatusID
   *
   * @return integer
   */
  public function getStatusID () {
    return $this->statusID;
  }
 
  /**
   * Returns the value of field CreateDate
   *
   * param string $dateFormat
   * @return string
   */
  public function getCreateDate ($dateFormat = null) {
    return is_null ($dateFormat) ? $this->createDate : date ($dateFormat, strtotime ($this->createDate));
  }
 
  /**
   * Returns the value of field VerificationDate
   *
   * @return string
   */
  public function getVerificationDate () {
    return $this->verificationDate;
  }
  
  /**
   * Returns the value of field UpdateDate
   *
   * param string $dateFormat
   * @return string
   */
  public function getUpdateDate ($dateFormat = null) {
    $updateDate = ($this->updateDate == '0000-00-00 00:00:00') ? $this->createDate : $this->updateDate;
 
    return is_null ($dateFormat) ? $updateDate : date ($dateFormat, strtotime ($updateDate));    
  }
  
  /**
   * Returns the value of field ModerationDate
   *
   * @return integer
   */
  public function getModerationDate () {
    return $this->moderationDate;
  }
 
  /**
   * Returns the value of field ApplicationType
   *
   * @return integer
   */
  public function getApplicationType () {
    return $this->applicationType;
  }
  
  /**
   * Returns the value of field PostingIP
   *
   * @return string
   */
  public function getPostingIP () {
    return $this->postingIP;
  }
  
  /**
   * Returns location of user
   *
   * @return PTMU\Models\Locations
   * @codeCoverageIgnore
   */
  public function getLocation () {
    return Locations::getLocation ($this->locationID);
  }
 
  /**
   * Returns user age from profile
   *
   * @return integer
   */
  public function getAge () {
    return ($this->profile !== false) ? $this->profile->getAge () : null;
  }
 
  /**
   * Returns user age from profile
   *
   * @return integer
   */
  public function getDescription () {
    return ($this->profile !== false) ? $this->profile->getDescription () : null;
  }
 
  /**
   * Returns the value of field ModerationDate
   *
   * @return integer
   */
  public function getNotificationVisitDate () {
    return $this->notificationVisitDate;
  }
  
  /**
   * Returns true if user is independent
   *
   * @return boolean
   */
  public function isIndependent () {
    return $this->getTypeID () == UserType::INDIVIDUAL_USER;
  }
 
  /**
   * Returns true if user is agency
   *
   * @return boolean
   */
  public function isAgency () {
    return $this->getTypeID () == UserType::AGENCY_USER;
  }
 
  /**
   * Returns true if user is regular
   *
   * @return boolean
   */
  public function isRegular () {
    return $this->getTypeID () == UserType::REGULAR_USER;
  }
 
  /**
   * Checks if user's status is verified
   *
   * @return integer
   */
  public function isVerified () {
    return $this->getStatusID() == UserStatus::VERIFIED;
  }
 
  /**
   * Checks if user's status is deleted
   *
   * @return integer
   */
  public function isDeleted () {
    return $this->getStatusID() == UserStatus::DELETED;
  }
 
  /**
   * Checks if user's status is blocked
   *
   * @return integer
   */
  public function isBlocked () {
    return $this->getStatusID() == UserStatus::BLOCKED;
  }
 
  /**
   * Checks if user's status is UnVerified
   *
   * @return integer
   */
  public function isUnVerified () {
    return $this->getStatusID() == UserStatus::UNVERIFIED;
  }
 
  /**
   * Returns true if Bump Explanation email was sent to user, 0 if not
   *
   * @return integer
   */
  public function isBumpExplanationEmailSent () {
    return intval ($this->getTaxonomyAttribute (UserAttributes::BUMP_EXPLANATION_EMAIL_SENT));
  }
 
  /**
   * Returns true if activation email was resubmitted to user, 0 if not
   *
   * @return integer
   */
  public function isActivationEmailResubmitted () {
    return intval ($this->getTaxonomyAttribute (UserAttributes::ACTIVATION_EMAIL_RESUBMITTED));
  }
 
  /**
   * Returns true if user was watchlisted for email spamming, 0 if not
   *
   * @return integer
   */
  public function isWatchlisted () {
    return intval ($this->getTaxonomyAttribute (UserAttributes::USER_WATCHLISTED));
  }
 
  /**
   * Returns true if user verification photo is allowed
   *
   * @return integer
   */
  public function isVerificationPhotoAllowed () {
    return intval ($this->getTaxonomyAttribute (UserAttributes::VERIFICATION_PHOTO_ALLOWED));
  }
 
  /**  
   * Returns true if user did unsubsribe
   *
   * @return integer
   */
  public function isUnSubscribed () {
    return intval ($this->getTaxonomyAttribute (UserAttributes::SEND_NEWADS_SUBSCRIPTION));
  }
  
  /**
   * Returns true if verification alert needed
   *
   * @return true
   */
  public function isVerificationAlertVisible () {
    return ($this->isIndependent() && $this->isVerified () && !$this->isUserVerified (true) && !intval ($this->getTaxonomyAttribute (UserAttributes::VERIFICATION_ALERT_HIDDEN)));
  }
  
  /**
   * Returns true if user is verified
   *
   * @param boolean $checkPresence
   * @return boolean
   */
  public function isUserVerified ($checkPresence = false) {
    $verification = $this->getRelated ('verification');
    
    if ($checkPresence) {
      return $verification;
    } else {
      return ($verification && ($verification->getStatusID () == VerificationStatus::VERIFICATION_APPROVED));      
    }
  }
  
  /**
   * Return user details
   */
  public function getDetails () {
    $details = $this->getRelated ('details');
    
    if ($details === false) {
      $details = new UserDetails ();
      $details->setPhonePreferenceID (PhonePreference::CALLS_AND_SMS);
    }
 
    return $details;
  }
 
  /**
   * Return profile picture file name
   * 
   * @boolean $allFiles
   * @return string
   */
  public function getProfilePictureFileName ($allFiles = false) {
    $profilePictureFileName = null;
    
    $profile = $this->getRelated ('profile');
 
    if ($profile !== false) {
      $profilePictureFileName = ($allFiles) ? $profile->getPictureFiles () : $profile->getPictureFileName ();
    }
    
    return $profilePictureFileName;
  }
 
  /**
   * Return verification picture file name
   * 
   * @boolean $allFiles
   * @return string
   */
  public function getVerificationPictureFileName ($allFiles = false) {
    $verificationPictureFileName = null;
    
    $verification = $this->getRelated ('verification');
 
    if ($verification !== false) {
      $verificationPictureFileName = ($allFiles) ? $verification->getPictureFiles () : $verification->getPictureFileName ();
    }
    
    return $verificationPictureFileName;
  }
  
  /**
   * Return pictures path
   * 
   * @return string
   */
  public function getProfilePicturePath () {
    $id = sprintf ('%09s', $this->userID);
 
    return substr ($id, 0, 3) . '/' . substr ($id, 3, 6) . '/' . $id;
  }
  
  /**
   * Return pictures directory
   * 
   * @return string
   */
  public function getProfilePictureDir () {
    return $this->getDI ()->getConfig ()->application->profilesDir . $this->getProfilePicturePath ();
  }
  
  /**
   * Return pictures Uri
   * 
   * @return string
   */
  public function getProfilePictureUri () {
    return basename ($this->getDI ()->getConfig ()->application->profilesDir) . '/' . $this->getProfilePicturePath ();
  }
  
  /**
   * Returns country name detected from posting IP
   * @codeCoverageIgnore
   */ 
  public function getPostingCountryName () {
    return CountryIP::findCountryNameByIP ($this->getPostingIP ());
  }
 
  /**
   * Returns LocationPath
   * @codeCoverageIgnore
   */
  public function getLocationsPath($finalLocationType = null, $reversePath = true){
    return Locations::getLocationPath($this->locationID, $finalLocationType, $reversePath);
  }
 
  /**
   * Return location path
   * 
   * @param boolean $includeCountry
   * @return array
   *
   */
  public function getLocationPath ($includeCountry = false) {
    if ($includeCountry) {
      return $this->getLocationsPath (array (LocationType::COUNTRY));
    } else {
      return $this->getLocationsPath ();
    }
  }
  
  /**
   * Return city from location path
   * 
   * @param boolean $includeParentLocation
   * @return array
   */
  public function getCity ($includeParentLocation = true) {
    $locationPath   = $this->getLocationsPath (array (LocationType::TOWN, LocationType::CITY, LocationType::MEGALOPOLIS), false);
    $cityLocation   = $locationPath [0]['name'];
    $locationsCount = count ($locationPath);
    
    if ($locationsCount > 1) {
      if ($includeParentLocation) {
        $cityLocation = "{$locationPath [$locationsCount - 1]['name']}, {$cityLocation}"; 
      } else {
        $cityLocation = $locationPath [$locationsCount - 1]['name'];
      }
    }
    
    return $cityLocation;
  }
  
  /**
   * Return parent location
   * 
   * @return array
   */
  public function getParentLocation () {
    $locationPath   = $this->getLocationsPath (array (LocationType::TOWN, LocationType::CITY, LocationType::MEGALOPOLIS), false);
    $parentLocation = $locationPath [0];
    $locationsCount = count ($locationPath);
    
    if ($locationsCount > 1) {
      $parentLocation = $locationPath [$locationsCount - 1];
    }
    
    return $parentLocation;
  }
  
  /**
   * Return profile url
   * 
   * @param boolean $leadingSlash
   * @return string
   */
  public function getProfileURL ($leadingSlash = true) {
    $name    = Slug::generate ($this->getName ());
    $urlPart = 'profile';
    
    if ($this->typeID == UserType::AGENCY_USER) {
      $urlPart = 'agency';
    }
    
    return ($leadingSlash ? '/' : '') . "{$urlPart}/{$this->userID}/{$name}";
  } 
 
  /**
   * Return review form url
   *
   * @param boolean $leadingSlash
   * @return string
   */
  public function getReviewFormURL ($leadingSlash = true) {
    $userType = $this->typeID == UserType::AGENCY_USER ? 'agency' : 'user';
    return ($leadingSlash ? '/' : '') . "post/{$userType}Review/{$this->userID}";
  }
 
  /**
   * Returns source table name.
   */
  public function getSource () {
    return 'users';
  }
  
  /**
   * Independent Column Mapping.
   */
  public function columnMap() {
    return array(
      'UserID'           => 'userID', 
      'TypeID'           => 'typeID', 
      'Email'            => 'email', 
      'Password'         => 'password', 
      'Name'             => 'name', 
      'LocationID'       => 'locationID', 
      'StatusID'         => 'statusID', 
      'CreateDate'       => 'createDate',      
      'VerificationDate' => 'verificationDate',            
      'UpdateDate'       => 'updateDate',
      'ModerationDate'   => 'moderationDate',
      'ApplicationType'  => 'applicationType',                
      'PostingIP'        => 'postingIP',
      'NotificationVisitDate'       => 'notificationVisitDate',
    );
  }
 
  /**
   * Model initialization method
   */
  public function initialize () {
    $this->_skipUpdateDate = false;
        
    $this->hasOne ('userID', 'PTMU\Models\UserDetails', 'userID', array (
      'alias' => 'details',
    ));
 
    $this->hasOne ('userID', 'PTMU\Models\UserProfile', 'userID', array (
      'alias' => 'profile',
    ));
 
    $this->hasOne ('userID', 'PTMU\Models\UserVerification', 'userID', array (
      'alias' => 'verification',
    ));
    
    $this->hasMany ('userID', 'PTMU\Models\Ads', 'userID', array (
      'alias' => 'ads',
    ));
    
     $this->hasMany ('userID', 'PTMU\Models\AdReviews', 'userID', array (
      'alias' => 'userreviews',
    ));
 
     $this->hasMany ('userID', 'PTMU\Models\UserLogs', 'userID', array (
      'alias' => 'userlogs',
    ));
 
    $this->hasMany ('userID', 'PTMU\Models\UserAttributes', 'userID', [
      'alias' => 'attributes',
    ]);
 
  }
  
  /**
   * Validate model before create
   */
  public function beforeValidationOnCreate () {
    $this->createDate       = date ("Y-m-d H:i:s");
    $this->verificationDate = new DBRawValue ('default');    
    $this->updateDate       = new DBRawValue ('default');
    $this->name             = Utils::normalizeStirng ($this->name);
  }
 
  /**
   * Validate model before update
   */
  public function beforeValidationOnUpdate () {
    if (!$this->_skipUpdateDate) {    
      $this->updateDate = date ("Y-m-d H:i:s");
    }
    
    $this->name = Utils::normalizeStirng ($this->name);    
  }
 
  /**
   * Find user by email
   * 
   * @param string $email
   * @return boolean
   * @codeCoverageIgnore
   */
  public static function findUserByEmail ($email) {
    return self::findFirst (array (
      'conditions' => '(email = :email:) and (statusID <> :statusBlocked:) and (statusID <> :statusDeleted:)',
      
      'bind' => array (
        'email'         => $email,
        'statusBlocked' => UserStatus::BLOCKED,
        'statusDeleted' => UserStatus::DELETED
      )
    ));
  }
  
  /**
   * Find user by email
   * 
   * @param string $email
   * @return boolean
   * @codeCoverageIgnore
   */
  public static function findActiveUserByID ($userID) {
    return self::findFirst (array (
      'conditions' => '(userID = :userID:) and (statusID <> :statusBlocked:) and (statusID <> :statusDeleted:)',
      
      'bind' => array (
        'userID'         => $userID,
        'statusBlocked' => UserStatus::BLOCKED,
        'statusDeleted' => UserStatus::DELETED
      )
    ));
  }
 
  /**
   * Return users with specific profile status id
   * 
   * @param integer $typeID
   * @param integer $statusID
   * @param integer $userStatusID
   * @param integer $profilesLimit
   * 
   * @return \Phalcon\Mvc\Model\ResultsetInterface
   */
  public static function findUsersByProfileStatusID ($typeID, $statusID, $userStatusID = null, $profilesLimit = null) {
    $dependencyInjector = DI::getDefault();    
 
    if (empty ($profilesLimit)) {
      $pageConfig = $dependencyInjector->getConfig ()->pages->admin;
      $profilesLimit   = $pageConfig->lookProfilesLimit;
    }
    
    $queryBuilder = $dependencyInjector->getModelsManager ()->createBuilder ();
 
    $queryBuilder->columns ('u.*, up.*');             
    $queryBuilder->from (array (
      'u' => 'PTMU\Models\Users'
    ));
    
    $queryBuilder->join ('PTMU\Models\UserProfile', 'up.userID = u.userID', 'up');
    
    $queryBuilder->where ('u.typeID = :typeID:', array (
      'typeID' => $typeID
    ));
    
    if (!is_array ($statusID)) {
      $statusID = [$statusID];
    }
    
    $queryBuilder->inWhere ('up.statusID', $statusID);
                             
    if (empty ($userStatusID)) {
      $userStatusID = array (UserStatus::UNVERIFIED, UserStatus::VERIFIED);
    } else if (!is_array ($userStatusID)) {
      $userStatusID = [$userStatusID];
    }
    
    $queryBuilder->inWhere ('u.statusID', $userStatusID);
    
    $queryBuilder->orderBy ('u.updateDate desc'); 
    $queryBuilder->limit (intval ($profilesLimit));
    
    return $queryBuilder->getQuery ()->execute ();
  }
  
  /**
   * Validate if email is already registered
   * 
   * @param string $email
   * @return boolean
   * @codeCoverageIgnore
   */
  public static function isEmailRegistered ($email) {
    return (self::findUserByEmail ($email) !== false);
  }
  
  /**
   * Send a confirmation e-mail to the user after create the account
   */
  public function sendConfirmationEmail ($referrerID, $page = null) {
    $userToken = new UserTokens ();
    
    $userToken->setUserID ($this->userID);
    $userToken->setTokenTypeID (UserTokenTypes::EMAIL_VERIFICATION);
    $userToken->setIsActual (false);
    $userToken->setReferrerAdID ($referrerID);
    
    $userToken->setReferrerMetaData (array (
      'refID' => $referrerID, 
      'page'  => $page
    ));
    
    if ($userToken->create ()) {
      $userToken->activateToken ();
      
      $emailTemplate = ($this->typeID == UserType::REGULAR_USER) ? 'accountActivationRegular' : 'accountActivation';
      
      $mail = new PTMUMail (true);
      
      $mail->setTo ($this->email);    
      $mail->setTemplate ($emailTemplate, array (
        'userName' => $this->getName (),
        'token'    => $userToken->getToken ()
      ));
      
      $mail->send ();
    }
  }
 
  /**
   * Get user attribute
   * 
   * @param string $attributeName
   * return mixed
   */
  public function getTaxonomyAttribute ($attributeName) {
    if (is_null ($this->_taxonomyAttributes)) {
      $this->_taxonomyAttributes = [];
 
      $this->_taxonomy = Taxonomy::getTaxonomy();
 
      $attributes = $this->getAttributes();
 
      foreach ($attributes as $attribute) {
        $this->addTaxonomyAttribute($this->_taxonomy, $attribute->getTaxonomyID(), $attribute->getValue());
      }
    }
    
    return @$this->_taxonomyAttributes [$attributeName];
  }
 
  /**
   * Return attributes
   *
   * @return \Phalcon\Mvc\Model\ResultsetInterface
   */
  public function getAttributes () {
    return $this->getRelated ('attributes');
  }
 
  /**
   * Add taxonomy attribute in the internal array
   *
   * @param array $taxonomy
   * @param integer $taxonomyID
   * @param variant $value optional
   */
  public function addTaxonomyAttribute ($taxonomy, $taxonomyID, $value = null) {
    if (is_null ($value) && isset ($taxonomy [$taxonomyID])) {
      $this->_taxonomyAttributes [$taxonomyID] = $taxonomy [$taxonomyID]['name'];
    } else {
      $this->_taxonomyAttributes [$taxonomyID] = $value;
    }
  }
 
  /**
   * Returns notifications count since last visit in the notifications list
   *
   * @return integer
   */
  public function getNotifcationsCounter () {
    if ($this->isRegular ()) return 0;
 
    $dateTo  = $this->getNotificationVisitDate ();
    $session = DI::getDefault ()->get ('session');
 
    $notifications = $this->getReadConnection ()->query ("
      SELECT count(*) as counter, max(CreatedDate) as maxdate
      FROM (
        (SELECT l.AdID AS adID, l.EntityID, l.EntityTypeID, l.CreatedDate , 'like' as notificationType, UserID, NULL as Comment FROM likes as l
            WHERE l.ToUserID = {$this->getUserID ()} AND l.ToUserID <> l.UserID AND l.CreatedDate > '{$dateTo}')
        UNION
        (SELECT c.AdID AS adID, c.EntityID, c.EntityTypeID, c.CreatedDate , 'comment' as notificationType, UserID, Comment as Comment FROM comments as c
            WHERE c.ToUserID = {$this->getUserID ()} AND c.ToUserID <> c.UserID AND c.CreatedDate > '{$dateTo}')
        UNION
        (SELECT n.AdID AS adID, n.EntityID, n.EntityTypeID, n.CreatedDate , 'notification' as notificationType, UserID, Notification as Comment FROM notifications as n
            WHERE n.ToUserID = {$this->getUserID ()} AND n.ToUserID <> n.UserID AND n.CreatedDate > '{$dateTo}')
      ) as notifications
     ")->fetch ();                 
       
    $sessionMaxDate = $session->get('maxdate');
       
    if (!$sessionMaxDate || ($sessionMaxDate < $notifications['maxdate'])) {
      $session->set ('maxdate', $notifications ['maxdate']);
      $session->remove ("notifierMenuList");
    }
 
    return $notifications['counter'];
  }
 
  /**
   * Returns notifications
   *
   * @param integer $limit
   * @return array 
   */
  public function getNotifcations ($limit = 5){
    $session           = DI::getDefault ()->get ('session');
    $notificationsList = array ();
 
    if (!$notificationsList = $session->get ("notifierMenuList")) {
      $notifications = $this->getReadConnection()->query ("
        SELECT notifications.AdID, notifications.ID as NotificationID, notifications.EntityID, notifications.EntityTypeID ,notifications.CreatedDate ,
               notifications.notificationType, notifications.UserID, notifications.Comment, notifications.ToUserID, notifications.FromAdID
        FROM (
          (
            SELECT l.LikeID as ID, l.AdID AS adID, l.EntityID, l.EntityTypeID, l.CreatedDate , 'like' as notificationType, UserID, ToUserID, FromAdID, NULL as Comment FROM likes as l
            WHERE l.ToUserID = {$this->getUserID()} AND l.ToUserID <> l.UserID  
          ) UNION (
            SELECT c.CommentID as ID, c.AdID AS adID, c.EntityID, c.EntityTypeID, c.CreatedDate , 'comment' as notificationType, UserID, ToUserID, FromAdID, Comment as Comment FROM comments as c
            WHERE c.ToUserID = {$this->getUserID()} AND c.ToUserID <> c.UserID 
          ) UNION (
            SELECT n.NotificationID as ID, n.AdID AS adID, n.EntityID, n.EntityTypeID, n.CreatedDate , 'notification' as notificationType, n.UserID, n.ToUserID, n.FromAdID, n.Notification as Comment FROM notifications as n
            WHERE n.ToUserID = {$this->getUserID()} AND n.ToUserID <> n.UserID
          )
        ) as notifications 
        order by notifications.CreatedDate DESC
        limit 0, {$limit}
      ")->fetchAll ();
 
      foreach ($notifications as $notification) {
        $entity  = $notification;
        $picture = false;
 
        $entity ['fromAd']             = null;        
        $entity ['orginalCreatedDate'] = $entity ["CreatedDate"];
        $entity ['CreatedDate']        = Utils::_formatDateAsSince ($entity ['CreatedDate'], false);
        
        switch ($notification ['EntityTypeID']) {
          case Entities::AD_STATUS_UPDATE:
            $update  = AdUpdates::findFirst (intval ($notification ['EntityID']));
            $picture = $update->updatePictures->getFirst ()->picture;
            break;
          case Entities::AD_PICTURE:
            $picture = AdPictures::findFirst (intval ($notification ['EntityID']));
        }
        
        if ($picture) {
          $entity ['entity'] = array (
            'pictureFileName' => $picture->getPictureFiles (),
            'picturesUri'     => $picture->getPicturesUri (),
            'isPrivate'     => $picture->getIsPrivate (),
          );
        }
        
        if ($user = Users::findFirst ($notification ['UserID'])) {
          $entity ['user'] = array (
            'profileURL'             => $user->getProfileURL (),
            'profilePictureFileName' => $user->getProfilePictureFileName (true),
            'profilePicturePath'     => $user->getProfilePicturePath (),
            'name'                   => $user->getName (true)
          );
        }
        
        if ($notification ['FromAdID'] && ($fromAd = Ads::findFirst ($notification ['FromAdID']))) {
          $entity ['fromAd'] = array (
            'picturesPath'        => $fromAd->getPicturesPath (),
            'mainPictureFileName' => $fromAd->getMainPictureThumbnailFileName (),
            'detailsURL'          => $fromAd->getDetailsURL (),
            'title'               => $fromAd->getTitle (),
            'name'                => $fromAd->getName (),
            'isActive'            => $fromAd->getIsActive (),
          );
        }
        
        $notificationsList [] = $entity;
      }
      
      $session->set ("notifierMenuList", $notificationsList);
    }
 
    return $notificationsList;
  }
}
#15PTMU\Models\Users::findActiveUserByID(11502)
/var/www/html/ptmu/frontend/controllers/AgencyProfileController.php (73)
<?php
 
namespace PTMU\Frontend\Controllers;
 
use PTMU\Auth\Exception as AuthException;
use PTMU\Models\Ads;
use PTMU\Models\Users;
use PTMU\Models\Locations;
use PTMU\Models\Taxonomy as TaxonomyModel;
use PTMU\Models\UserDetails;
use PTMU\Models\UserProfile;
use PTMU\Models\AgencyReviews;
use PTMU\Taxonomy;
use PTMU\Taxonomy\UserStatus;                
use PTMU\Taxonomy\UserType;                
use PTMU\Taxonomy\AdStatus;
use PTMU\Taxonomy\ProfileStatus;
use PTMU\Taxonomy\ReviewStatus;
use PTMU\Utils\Utils;
use Phalcon\Db\RawValue as DBRawValue;
use Phalcon\Mvc\View;
 
class AgencyProfileController extends ControllerBase {
  
  /**
   * index action
   */
  public function indexAction () {
  }
  
  /**
   * edit action
   */
  public function editAction () {
    $user = $this->auth->getUser ();                
    
    if (is_null ($this->auth->getIdentity ()) || $this->auth->isRegular () || ($user->getTypeID () != UserType::AGENCY_USER)) {
      return $this->forwardToNotFound ();
    }
    
    if ($this->request->isPost ()) {
      if ($this->security->getSessionToken () != $this->request->getPost ('csrf', 'string')) {
        return $this->forwardToNotFound ();
      }
      
      $this->updateProfile ($user);
      $this->auth->setUser ($user);
      $this->auth->addAttribute ('profileSaved', true);
      
      return $this->response->redirect (array (
        'for' => 'accountRoute',
      ));
    }
    
    $this->view->pick (['agencyProfile/edit']);    
    
    // JS assets
    $this->_jsAssets [] = 'agencyProfileEditForm';
    
    $this->view->setVar ("cities",   Locations::getCities ($this->location->getID ()));
    $this->view->setVar ("user",     $user);           
    $this->view->setVar ('jsAssets', $this->_jsAssets);     
        
    // Page title and meta description        
    $this->view->setVar ("pageTitle",       $this->translations ['agency-profile-edit-page-title']);
    $this->view->setVar ("metaDescription", $this->translations ['agency-profile-edit-page-meta']);
  }
  
  /**
   * view action
   */
  public function viewAction ($agencyID) {
    if (!($agency = Users::findActiveUserByID ($agencyID))) {
      return $this->response->redirect('escorts',false,301);
    }
 
    // Check user profile and forward to new url if user profile was changed
    if ($this->request->getQuery ()['_url'] != $agency->getProfileURL ()) {
      return $this->response->redirect ($agency->getProfileURL (false), false, 302);
    }
 
    $visitor = $this->auth->getUser ();
    
    if ($this->_mobileApplication) {
      $this->view->setViewsDir ($this->di->getConfig ()->mobileModule->viewsDir);
    }
    
    $this->view->pick (['agencyProfile/view']);    
       
    $this->_jsAssets [] = 'profileView';
    $this->_jsAssets [] = 'jquery.sticky-kit';
    $this->_jsAssets [] = 'jquery.preload';
   
    $this->view->setVar ("canReview",      $this->getCanReview ($visitor, $agency));
    $this->view->setVar ("canReviewReply", ($visitor && ($visitor->getUserID () == $agency->getUserID ())));
    $this->view->setVar ("cities",         Locations::getCities ($this->location->getID ()));
    $this->view->setVar ("agency",         $agency);    
    $this->view->setVar ("ads",            Ads::findUserActiveAds ($agencyID));    
    $this->view->setVar ("visitor",        $visitor);
    $this->view->setVar ('jsAssets',       $this->_jsAssets);
    
    // Set reviews variables in view
    $this->setReviewsVariablesInView ($agency->getUserID ());
    
    // Set proper application version for alternate/canonical link
    $this->view->setVar (Utils::getVersionVar (), true);
    
    // Page title and meta description        
    $this->view->setVar ("pageTitle",       sprintf ($this->translations ['agency-profile-page-title'], $agency->getName ()));
    $this->view->setVar ("metaDescription", sprintf ($this->translations ['agency-profile-page-meta'],  $agency->getName ()));
  }
 
  /**
   * Set reviews variables in view
   * 
   * @param integer $userID
   */
  protected function setReviewsVariablesInview ($userID) {
    $reviewsAbout = AgencyReviews::findReviewsByAgencyID ($userID);
    $user_ids     = array ();  
    
    foreach ($reviewsAbout as $review) {
      $user_ids [$review->arev->getUserID ()] = $review->arev->getUserID ();      
    }
    
    $this->view->setVar ("reviewsAbout",      $reviewsAbout);    
    $this->view->setVar ("reviewsTotalAbout", count ($reviewsAbout));   
    $this->view->setVar ("reviewsAVGReviews", AgencyReviews::avgReviews ($userID));   
    $this->view->setVar ("reviewers",         AgencyReviews::getAgencyReviewsCountByUserIds ($user_ids)); 
  }
  
  /**
   * Update profile
   * 
   * @param \PTMU\Models\Users $user
   */
  protected function updateProfile ($user) {
    $oldName        = trim ($user->getName ());
    $oldDescription = trim ($user->getDescription ());
    $oldWebSite     = trim ($user->details->getWebSite ());
    $newName        = trim ($this->request->getPost ('profileName', 'string'));            
    $newDescription = trim ($this->request->getPost ('profileDesc', 'string'));
    $newWebSite     = trim ($this->request->getPost ('profileWebSite', 'string'));
    $profileAge     = intval ($this->request->getPost ('profileAge', 'int'));
    
    $isNameChanged    = strcasecmp (htmlspecialchars_decode ($newName, ENT_QUOTES), $oldName) != 0;      
    $isDescChanged    = strcasecmp (htmlspecialchars_decode ($newDescription, ENT_QUOTES), $oldDescription) != 0;
    $isWebSiteChanged = strcasecmp (htmlspecialchars_decode ($newWebSite, ENT_QUOTES), $oldWebSite) != 0;      
    
    if ($profileAge <= 0) {
      $profileAge = new DBRawValue ('default');
    }
    
    if (!mb_strlen ($newDescription)) {
      $newDescription = new DBRawValue ('default');        
    }
    
    $profile = $user->profile;
    
    if ($profile === false) {
      $profile = new UserProfile ();
      $profile->setUserID ($user->getUserID ());
      $profile->create ();
      
      $profile = $user->profile;              
    } 
 
    $profile->setAge ($profileAge);                
    $profile->setDescription ($newDescription);        
    
    if ($isDescChanged && ($profile->getStatusID () != ProfileStatus::PROFILE_PENDING)) {
      $profile->setStatusID (ProfileStatus::PROFILE_EDITED);
      $profile->setAppliedChange (UserProfile::CHG_DESCRIPTION);          
    }
    
    if ($isNameChanged) {
      $profile->setAppliedChange (UserProfile::CHG_NAME);
      
      if ($profile->getStatusID () != ProfileStatus::PROFILE_PENDING) {
        $profile->setStatusID (ProfileStatus::PROFILE_EDITED);
      }
    }         
    
    if ($isWebSiteChanged) {
      $profile->setAppliedChange (UserProfile::CHG_WEB_SITE);
      
      if ($profile->getStatusID () != ProfileStatus::PROFILE_PENDING) {
        $profile->setStatusID (ProfileStatus::PROFILE_EDITED);
      }
    }         
    
    $user->setName ($newName);
    $user->setLocationID ($this->request->getPost ('profileLocation', 'int'));
    $user->details->setPhone ($this->request->getPost ('profilePhone', 'string'));
    $user->details->setWebSite ($newWebSite);      
    $user->update ();      
  }
  
  /**
   * Returns true if user can review
   * 
   * @param \PTMU\Models\Users $visitor
   * @param \PTMU\Models\Users $agency
   * 
   * @returns boolean
   */
  protected function getCanReview ($visitor, $agency) {
    $canReview = false;
    
    if ($visitor && ($visitor->isRegular () && $visitor->isVerified ()) ){
      $rejected  = ReviewStatus::REVIEW_REJECTED;
      $canReview = !AgencyReviews::count ("userID = {$visitor->getUserID()} AND agencyID = {$agency->getUserID()} AND statusID != {$rejected} ");
    }
    
    return $canReview;
  }
}  
#16PTMU\Frontend\Controllers\AgencyProfileController->viewAction(11502, soft-touch-bodyworks)
#17Phalcon\Dispatcher->dispatch()
#18Phalcon\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/agency/11502/soft-touch-bodyworks
KeyValue
USERapache
HOME/var/www
FCGI_ROLERESPONDER
SCRIPT_FILENAME/var/www/html/public/index.php
QUERY_STRING_url=/agency/11502/soft-touch-bodyworks
REQUEST_METHODGET
CONTENT_TYPE
CONTENT_LENGTH
SCRIPT_NAME/index.php
REQUEST_URI/agency/11502/soft-touch-bodyworks
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_PORT45242
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_FLOAT1487645415.6659
REQUEST_TIME1487645415
#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/AgencyProfileController.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/Users.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