| #0 | Phalcon\Session\Bag->__construct
/var/www/html/johngold.net/src/app/Lib/Factory.php (167) <?php
namespace CLSystems\PhalCMS\Lib;
use CLSystems\PhalCMS\Lib\Api\Middleware\ApiKeyGuard;
use Phalcon\Encryption\Crypt;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Flash\Session;
use Phalcon\Html\Escaper;
use Phalcon\Html\TagFactory;
use Phalcon\Support\Debug;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Url;
use Phalcon\Config\Adapter\Ini;
use Phalcon\Di\FactoryDefault;
use Phalcon\Session\Manager;
use Phalcon\Session\Adapter\Stream;
use Phalcon\Session\Bag;
use Phalcon\Db\Adapter\Pdo\Mysql;
use CLSystems\PhalCMS\Lib\Helper\Asset;
use CLSystems\PhalCMS\Lib\Helper\Config;
use CLSystems\PhalCMS\Lib\Helper\Event;
use CLSystems\PhalCMS\Lib\Helper\Language;
use CLSystems\PhalCMS\Lib\Mvc\View\ViewBase;
use CLSystems\Php\Registry;
use Exception;
if (!function_exists('debugVar'))
{
function debugVar($var)
{
(new Debug)
->debugVar($var)
->listen(true, true)
->halt();
}
}
class Factory
{
/** @var Registry $config */
protected static $config;
/** @var CmsApplication $application */
protected static $application;
protected static function loadConfig()
{
if (!is_file(BASE_PATH . '/src/config.ini')) {
if (is_file(BASE_PATH . '/public/install.php')) {
$protocol = 'http';
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
$protocol .= 's';
}
header('location: ' . $protocol . '://' . $_SERVER['HTTP_HOST'] . '/install.php');
} else {
die('The config INI file not found at ' . BASE_PATH . '/src/config.ini');
}
}
require_once BASE_PATH . '/src/app/Config/Define.php';
require_once BASE_PATH . '/src/app/Config/Loader.php';
require_once BASE_PATH . '/vendor/autoload.php';
return new Ini(BASE_PATH . '/src/config.ini', INI_SCANNER_NORMAL);
}
public static function getApplication()
{
if (!isset(self::$application)) {
$config = self::loadConfig();
$dbPrefix = $config->path('DB.PREFIX');
try {
$db = new Mysql(
[
'host' => $config->path('DB.HOST'),
'username' => $config->path('DB.USER'),
'password' => $config->path('DB.PASS'),
'dbname' => $config->path('DB.NAME'),
'charset' => 'utf8mb4',
]
);
} catch (Exception $e) {
die($e->getMessage());
}
$registry = new Registry(
[
'siteTemplate' => $config->path('APP.TEMPLATE') ?? 'PhalCMS',
'core' => [
'plugins' => [
'CLSystems\\PhalCMS\\Plugin\\System\\Cms\\Cms',
],
'widgets' => [
'CLSystems\\PhalCMS\\Widget\\Code\\Code',
'CLSystems\\PhalCMS\\Widget\\Content\\Content',
'CLSystems\\PhalCMS\\Widget\\FlashNews\\FlashNews',
'CLSystems\\PhalCMS\\Widget\\LanguageSwitcher\\LanguageSwitcher',
'CLSystems\\PhalCMS\\Widget\\Login\\Login',
'CLSystems\\PhalCMS\\Widget\\Menu\\Menu',
],
],
]
);
if ($extraConfig = $db->fetchColumn('SELECT data FROM ' . $dbPrefix . 'config_data WHERE context = \'cms.config\'')) {
$registry->merge($extraConfig);
}
define('ADMIN_URI_PREFIX', $registry->get('adminPrefix', 'admin'));
define('DEVELOPMENT_MODE', $registry->get('development', 'Y') === 'Y');
Config::setDataContext('cms.config', $registry);
if (true === DEVELOPMENT_MODE) {
ini_set('display_errors', true);
error_reporting(E_ALL);
if (!defined('TEST_PHPUNIT_MODE')) {
(new Debug())->listen(true, false);
}
}
// Create DI Factory Default
$di = new FactoryDefault;
// Set URL service first to use debug
$di->setShared('url', new Url);
$di->setShared('config', $config);
$esc = new Escaper();
$tf = new TagFactory($esc);
$di->setShared('assets', new Asset($tf));
$di->setShared('modelsManager', new \Phalcon\Mvc\Model\Manager());
$di->getShared('modelsManager')->setModelPrefix($dbPrefix);
$di->setShared('db', $db);
$sess = new Escaper();
$di->setShared('flashSession', new Session($sess));
$di->getShared('flashSession')
->setAutoescape(false)
->setCssClasses(
[
'error' => 'uk-alert uk-alert-danger',
'success' => 'uk-alert uk-alert-success',
'notice' => 'uk-alert uk-alert-warning',
'warning' => 'uk-alert uk-alert-warning',
]
);
$di->setShared('session', function () {
$session = new Manager();
$adapter = new Stream([
'savePath' => CACHE_PATH . '/session',
]);
$session->setAdapter($adapter);
$session->start();
return $session;
});
$di->setShared('sessionBag', function () {
return new Bag('controller.persistent');
});
$di->setShared('router', function () {
$router = include CONFIG_PATH . '/Router.php';
Event::trigger('onBeforeServiceSetRouter', [$router], ['System', 'Cms']);
return $router;
});
// API services
$di->setShared('apiKeyGuard', function () {
return new ApiKeyGuard();
});
$di->setShared('crypt', new Crypt());
$di->getShared('crypt')
->setCipher('aes-256-ctr')
->setKey($config->path('SECRET.CRYPT_KEY'));
$di->setShared('eventsManager', function () { return new EventsManager(); });
$di->setShared('dispatcher', function () use ($di) {
$dispatcher = new Dispatcher();
// Ensure events manager is set
$dispatcher->setEventsManager($di->getShared('eventsManager'));
return $dispatcher;
});
$di->getShared('dispatcher')
->setEventsManager($di->getShared('eventsManager'));
$di->setShared('view', ViewBase::getInstance($di));
// Initialise config data
self::$config = new Registry($config->toArray());
// Initialise application
self::$application = new CmsApplication($di);
// Initialise languages
Language::initialise();
}
return self::$application;
}
public static function getConfig()
{
return self::$config;
}
public static function getService($name, $parameters = null)
{
$di = self::getApplication()->getDI();
switch ($name) {
case 'url':
case 'view':
case 'db':
case 'modelsMetadata':
case 'modelsManager':
case 'session':
case 'flashSession':
case 'cookies':
case 'security':
case 'dispatcher':
case 'router':
case 'filter':
case 'crypt':
case 'request':
case 'response':
return $di->getShared($name, $parameters);
}
return $di->get($name, $parameters);
}
}
|
| #4 | Phalcon\Di\Injectable->__get
/var/www/html/johngold.net/src/app/Lib/Mvc/Controller/UserController.php (25) <?php
namespace CLSystems\PhalCMS\Lib\Mvc\Controller;
use CLSystems\PhalCMS\Lib\Helper\Config;
use CLSystems\PhalCMS\Lib\Helper\State;
use CLSystems\PhalCMS\Lib\Helper\User;
use CLSystems\PhalCMS\Lib\Helper\Date;
use CLSystems\PhalCMS\Lib\Helper\Form;
use CLSystems\PhalCMS\Lib\Helper\Uri;
use CLSystems\PhalCMS\Lib\Helper\Text;
use CLSystems\PhalCMS\Lib\Helper\Mail;
use CLSystems\PhalCMS\Lib\Mvc\Model\User as UserModel;
use Exception;
use function CLSystems\PhalCMS\Lib\debugVar;
class UserController extends ControllerBase
{
public function accountAction()
{
$user = User::getInstance();
if ($user->isGuest())
{
$this->view->setVar('registerData', $this->persistent->get('user.register.data', []));
$this->view->pick('User/Account');
}
else
{
$this->view->setVar('user', $user);
$this->view->pick('User/Logout');
}
}
public function forgotAction()
{
$this->view->pick('User/Forgot');
}
public function requestAction()
{
if ($this->request->isPost()
&& Form::checkToken()
)
{
$type = $this->request->getPost('requestType', ['trim'], 'P');
$email = filter_var($this->request->getPost('email', ['string'], ''), FILTER_VALIDATE_EMAIL);
$params = [
'conditions' => 'email = :email: AND active = :yes:',
'bind' => [
'email' => $email,
'yes' => 'Y',
],
];
if (!empty($email)
&& ($user = UserModel::findFirst($params))
&& $user->save(['token' => sha1($user->username . ':' . $user->password)])
)
{
$siteName = Config::get('siteName');
if ('P' === $type)
{
// Send reset password
$user->save(['token' => sha1($user->username . ':' . $user->password)]);
$link = Uri::getInstance(['uri' => 'user/reset/' . $user->token])->toString(false, true);
$subject = Text::_('user-reset-request-subject', ['siteName' => $siteName]);
$body = Text::_('user-reset-request-body', ['siteName' => $siteName, 'name' => $user->name, 'link' => $link]);
Mail::sendMail($user->email, $subject, str_replace('\n', PHP_EOL, $body));
$this->view->setVars(
[
'title' => Text::_('user-request-completed-title', ['email' => $user->email]),
'message' => Text::_('user-request-completed-msg', ['siteName' => $siteName, 'email' => $user->email]),
]
);
$this->persistent->set('user.token.' . $user->token, true);
}
else
{
// Send remind username
$subject = Text::_('username-remind-request-subject', ['siteName' => $siteName]);
$body = Text::_('username-remind-request-body', ['siteName' => $siteName, 'name' => $user->name, 'username' => $user->username]);
Mail::sendMail($user->email, $subject, str_replace('\n', PHP_EOL, $body));
$this->view->setVars(
[
'title' => Text::_('username-remind-completed-title', ['email' => $user->email]),
'message' => Text::_('username-remind-completed-msg', ['siteName' => $siteName, 'email' => $user->email]),
]
);
}
$this->view->pick('User/Completed');
}
}
else
{
return $this->response->redirect(Uri::route('user/forgot'), true);
}
}
public function loginAction()
{
if (($forward = $this->request->get('forward'))
&& ($uri = Uri::fromUrl($forward))
&& $uri->isInternal()
)
{
$redirect = $forward;
}
else
{
$redirect = Uri::route('user/account');
}
if (!User::getInstance()->isGuest())
{
return $this->response->redirect($redirect, true);
}
if ($this->request->isPost())
{
if (!Form::checkToken())
{
return $this->response->redirect($redirect, true);
}
$username = $this->request->getPost('username');
$password = $this->request->getPost('password');
$entity = UserModel::findFirst(
[
'conditions' => 'username = :username: AND active = :yes:',
'bind' => [
'username' => $username,
'yes' => 'Y',
],
]
);
if (!$entity || !$this->security->checkHash($password, $entity->password))
{
$this->flashSession->error(Text::_('login-fail-message'));
return $this->response->redirect(Uri::route('user/account', true), true);
}
/** @var UserModel $entity */
// Update latest visit date
$entity->assign(['lastVisitedDate' => Date::getInstance()->toSql()])->save();
User::getInstance($entity)->setActive();
}
return $this->response->redirect($redirect, true);
}
public function logoutAction()
{
$user = User::getInstance();
if ($user->isGuest()
|| !$this->request->isPost()
|| !Form::checkToken()
)
{
$this->flash->error(Text::_('access-denied'));
return $this->response->redirect(Uri::route(), true);
}
if ($this->cookies->has('cms.site.language'))
{
$this->cookies->delete('cms.site.language');
}
if ($this->cookies->has('cms.user.remember'))
{
$this->cookies->delete('cms.user.remember');
}
$user->logout();
return $this->response->redirect(Uri::route('user/account'), true);
}
public function registerAction()
{
if ($this->request->isGet()
|| !Form::checkToken()
|| 'Y' !== Config::get('allowUserRegistration')
)
{
$this->accountAction();
}
$postData = $this->request->getPost();
$validData = [];
$errorMsg = [];
$fields = [
'name' => Text::_('your-name'),
'username' => Text::_('username'),
'email' => Text::_('email'),
'password' => Text::_('password'),
'confirmPassword' => Text::_('confirm-password'),
];
$data = array(
'secret' => "0x4642BD05b3c691Dc43715bDb492BEF255351aAB1",
'response' => $postData['h-captcha-response']
);
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, "https://hcaptcha.com/siteverify");
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($verify);
$responseData = json_decode($response, true);
// var_dump($responseData); die;
if(false === $responseData['success'])
{
$this->flashSession->error(Text::_('register-fail-message'));
return $this->response->redirect(Uri::route('user/account', true), true);
}
foreach ($fields as $name => $text)
{
$validData[$name] = trim($postData[$name]);
if (empty($postData[$name]))
{
$errorMsg[] = Text::_('required-field-msg', ['field' => $text]);
}
}
$validData['email'] = filter_var($validData['email'], FILTER_VALIDATE_EMAIL);
if (false === $validData['email'])
{
$errorMsg[] = Text::_('invalid-email-msg');
}
$test = User::validatePassword($validData['password']);
if ($test instanceof Exception)
{
$errorMsg[] = $test->getMessage();
}
if ($validData['password'] !== $validData['confirmPassword'])
{
$errorMsg[] = Text::_('password-not-match');
}
if (!empty($validData['username']) || !empty($validData['email']))
{
if (!empty($validData['username']))
{
$userExists = UserModel::findFirst(
[
'conditions' => 'username = :username:',
'bind' => [
'username' => $validData['username'],
],
]
);
if ($userExists)
{
$errorMsg[] = Text::_('the-username-existed-msg', ['username' => $validData['username']]);
}
}
if (!empty($validData['email']))
{
$userExists = UserModel::findFirst(
[
'conditions' => 'email = :email:',
'bind' => [
'email' => $validData['email'],
],
]
);
if ($userExists)
{
$errorMsg[] = Text::_('the-user-email-existed-msg', ['email' => $validData['email']]);
}
}
}
// A = auto activate, E = by email, N = by admin
$newUserActivation = Config::get('newUserActivation', 'E');
$completed = false;
if (empty($errorMsg))
{
// Start register new user
State::setMark('user.registering', true);
$userEntity = new UserModel;
$userEntity->id = 0;
$userEntity->name = $validData['name'];
$userEntity->username = $validData['username'];
$userEntity->email = $validData['email'];
$userEntity->password = $this->security->hash($validData['password']);
$userEntity->role = 'R';
$userEntity->active = 'A' === $newUserActivation ? 'Y' : 'N';
$userEntity->createdAt = date('Y-m-d H:i:s');
$userEntity->token = 'E' === $newUserActivation ? sha1($userEntity->username . ':' . $userEntity->password) : null;
$userEntity->params = [
'timezone' => Config::get('timezone', 'UTC'),
'avatar' => '',
];
if ($userEntity->save())
{
$siteName = Config::get('siteName');
if ('E' === $newUserActivation)
{
$link = Uri::getInstance(['uri' => 'user/activate/' . $userEntity->token])->toString(true, true);
$subject = Text::_('activate-email-subject', ['username' => $userEntity->username, 'siteName' => $siteName]);
$body = Text::_('activate-email-body', ['name' => $userEntity->name, 'siteName' => $siteName, 'link' => $link]);
Mail::sendMail($userEntity->email, $subject, str_replace('\n', PHP_EOL, $body));
}
$mailToAdmin = Config::get('mailToAdminWhenNewUser', 'Y') === 'Y';
$adminEmail = filter_var(Config::get('adminEmail', ''), FILTER_VALIDATE_EMAIL);
if ($mailToAdmin
&& !empty($adminEmail)
&& ($adminEmail = filter_var($adminEmail, FILTER_VALIDATE_EMAIL))
)
{
$subject = Text::_('activate-email-subject', ['username' => $userEntity->username, 'siteName' => $siteName]);
$body = Text::_('email-notification-new-user-body', ['name' => $userEntity->name, 'username' => $userEntity->username, 'siteName' => $siteName]);
Mail::sendMail($adminEmail, $subject, str_replace('\n', PHP_EOL, $body));
}
}
else
{
$errorMsg[] = Text::_('user-register-failure-msg');
}
// Check errors again
$errorMsg = array_unique($errorMsg);
if (empty($errorMsg))
{
$completed = true;
switch ($newUserActivation)
{
case 'A':
$this->view->setVar('message', Text::_('user-register-success-msg'));
break;
case 'E':
$this->view->setVar('message', Text::_('user-activate-by-email-msg'));
break;
case 'N':
$this->view->setVar('message', Text::_('user-activate-by-admin-msg'));
break;
}
$this->persistent->remove('user.register.data');
$this->view->setVar('title', Text::_('user-register-completed-msg', ['name' => $userEntity->name]));
$this->view->pick('User/Completed');
}
}
if (!$completed)
{
$this->persistent->set('user.register.data', $postData);
$this->flashSession->warning(implode('<br/>', $errorMsg));
$this->accountAction();
}
}
public function activateAction()
{
$token = $this->dispatcher->getParam('token', ['alphanum'], '');
$params = [
'conditions' => 'token = :token: AND active = :no:',
'bind' => [
'token' => $token,
'no' => 'N',
],
];
if (empty($token)
|| strlen($token) !== 40
|| !($user = UserModel::findFirst($params))
)
{
return $this->response->redirect(Uri::route(), true);
}
$user->token = null;
$user->active = 'Y';
if ($user->save())
{
$this->view->setVars(
[
'title' => Text::_('user-activate-completed-msg', ['name' => $user->name]),
'message' => Text::_('user-activate-success-msg'),
]
);
$this->view->pick('User/Completed');
}
else
{
return $this->dispatcher->forward(
[
'controller' => 'error',
'action' => 'show',
]
);
}
}
public function resetAction()
{
$token = $this->dispatcher->getParam('token', ['alphanum'], '');
$params = [
'conditions' => 'token = :token: AND active = :yes:',
'bind' => [
'token' => $token,
'yes' => 'Y',
],
];
if (empty($token)
|| strlen($token) !== 40
|| !($user = UserModel::findFirst($params))
)
{
return $this->response->redirect(Uri::route('user/forgot'), true);
}
if (!$this->persistent->has('user.token.' . $token))
{
$user->token = null;
$user->save();
return $this->response->redirect(Uri::route('user/forgot'), true);
}
if ($this->request->isGet())
{
$this->view->setVar('token', $token);
$this->view->pick('User/Reset');
}
elseif ($this->request->isPost()
&& Form::checkToken()
)
{
$password1 = $this->request->getPost('password', ['string'], '');
$password2 = $this->request->getPost('confirmPassword', ['string'], '');
$test = User::validatePassword($password1);
if ($test instanceof Exception)
{
$this->flashSession->warning($test->getMessage());
return $this->response->redirect(Uri::route('user/reset/' . $token), true);
}
if (empty($password1)
|| $password1 !== $password2
)
{
$this->flashSession->warning(Text::_('pwd-empty-or-not-match-msg'));
return $this->response->redirect(Uri::route('user/reset/' . $token), true);
}
$user->token = null;
$user->password = $this->security->hash($password1);
if ($user->save())
{
$this->persistent->remove('user.token.' . $token);
$this->flashSession->success(Text::_('update-password-success-msg'));
return $this->response->redirect(Uri::route('user/account'), true);
}
$this->flashSession->error(Text::_('update-password-failure-msg'));
return $this->response->redirect(Uri::route('user/reset/' . $token), true);
}
else
{
return $this->response->redirect(Uri::route('user/forgot'), true);
}
}
}
|
| #8 | Phalcon\Mvc\Application->handle
/var/www/html/johngold.net/src/app/Lib/CmsApplication.php (117) <?php
namespace CLSystems\PhalCMS\Lib;
use Phalcon\Autoload\Loader;
use Phalcon\Http\Response;
use Phalcon\Events\Event;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\View;
use CLSystems\PhalCMS\Lib\Helper\Asset;
use CLSystems\PhalCMS\Lib\Helper\Config;
use CLSystems\PhalCMS\Lib\Helper\Uri;
use CLSystems\PhalCMS\Lib\Helper\State;
use CLSystems\PhalCMS\Lib\Helper\User;
use CLSystems\PhalCMS\Lib\Helper\Event as EventHelper;
use CLSystems\PhalCMS\Lib\Mvc\View\ViewBase;
use CLSystems\Php\Registry;
use MatthiasMullie\Minify;
use Exception;
class CmsApplication extends Application
{
public function execute()
{
try {
$eventsManager = $this->di->getShared('eventsManager');
$eventsManager->attach('application:beforeSendResponse', $this);
$plugins = EventHelper::getPlugins();
$systemEvents = [
'application:beforeSendResponse',
'dispatch:beforeExecuteRoute',
'dispatch:beforeException',
'dispatch:beforeDispatch',
'dispatch:afterDispatch',
'dispatch:afterInitialize',
];
foreach ($plugins['System'] as $className => $config) {
$handler = EventHelper::getHandler($className, $config);
foreach ($systemEvents as $systemEvent) {
$eventsManager->attach($systemEvent, $handler);
}
}
// Update view dirs
define('TPL_SITE_PATH', APP_PATH . '/Tmpl/Site/' . Config::get('siteTemplate', 'PhalCMS'));
define('TPL_ADMINISTRATOR_PATH', APP_PATH . '/Tmpl/Administrator');
define('TPL_SYSTEM_PATH', APP_PATH . '/Tmpl/System');
if (Uri::isClient('site')) {
$viewDirs = [
TPL_SITE_PATH . '/Tmpl/',
TPL_SITE_PATH . '/',
];
} else {
$viewDirs = [
TPL_ADMINISTRATOR_PATH . '/',
];
}
foreach (['System', 'Cms'] as $plgGroup) {
if (isset($plugins[$plgGroup])) {
/**
* @var string $pluginClass
* @var Registry $pluginConfig
*/
foreach ($plugins[$plgGroup] as $pluginClass => $pluginConfig) {
$pluginName = $pluginConfig->get('manifest.name');
$pluginPath = PLUGIN_PATH . '/' . $plgGroup . '/' . $pluginName;
$psrPaths = [];
if (is_dir($pluginPath . '/Tmpl')) {
$viewDirs[] = $pluginPath . '/Tmpl/';
}
if (is_dir($pluginPath . '/Lib')) {
$psrPaths['CLSystems\\PhalCMS\\Lib'] = $pluginPath . '/Lib';
}
if (is_dir($pluginPath . '/Widget')) {
$psrPaths['CLSystems\\PhalCMS\\Widget'] = $pluginPath . '/Widget';
}
if ($psrPaths) {
(new Loader)
->setNamespaces($psrPaths, true)
->register();
}
}
}
}
$viewDirs[] = TPL_SYSTEM_PATH . '/';
/** @var ViewBase $view */
$view = $this->di->getShared('view');
$requestUri = $_SERVER['REQUEST_URI'];
if (Config::get('siteOffline') === 'Y'
&& !User::getInstance()->access('super')
) {
$this->view->setMainView('Offline/Index');
if (strpos($requestUri, '/user/') !== 0) {
$requestUri = '';
}
} else {
$view->setMainView('Index');
}
$view->setViewsDir($viewDirs);
$this->setEventsManager($eventsManager);
$this->handle($requestUri)->send();
} catch (Exception $e) {
if (true === DEVELOPMENT_MODE) {
// Let Phalcon Debug catch this
throw $e;
}
try {
if (User::getInstance()->access('super')) {
State::setMark('exception', $e);
}
/**
* @var Dispatcher $dispatcher
* @var View $view
*/
$dispatcher = $this->getDI()->getShared('dispatcher');
$dispatcher->setControllerName(Uri::isClient('administrator') ? 'admin_error' : 'error');
$dispatcher->setActionName('show');
$dispatcher->setParams(
[
'code' => $e->getCode(),
'message' => $e->getMessage(),
]
);
$view = $this->getDI()->getShared('view');
$view->start();
$dispatcher->dispatch();
$view->render(
$dispatcher->getControllerName(),
$dispatcher->getActionName(),
$dispatcher->getParams()
);
$view->finish();
echo $view->getContent();
} catch (Exception $e2) {
debugVar($e2->getMessage());
}
}
}
protected function getCompressor($type)
{
if ('css' === $type) {
$compressor = new Minify\CSS;
$compressor->setImportExtensions(
[
'gif' => 'data:image/gif',
'png' => 'data:image/png',
'svg' => 'data:image/svg+xml',
]
);
} else {
$compressor = new Minify\JS;
}
return $compressor;
}
protected function compressAssets()
{
$basePath = PUBLIC_PATH . '/assets';
$assets = Factory::getService('assets');
foreach (Asset::getFiles() as $type => $files) {
$fileName = md5(implode(':', $files)) . '.' . $type;
$filePath = $basePath . '/compressed/' . $fileName;
$fileUri = DOMAIN . '/assets/compressed/' . $fileName . (DEVELOPMENT_MODE ? '?' . time() : '');
$hasAsset = is_file($filePath);
$ucType = ucfirst($type);
$addFunc = 'add' . $ucType;
if ($hasAsset && !DEVELOPMENT_MODE) {
call_user_func_array([$assets, $addFunc], [$fileUri, false]);
continue;
}
$compressor = self::getCompressor($type);
foreach ($files as $file) {
$compressor->add($file);
}
if (!is_dir($basePath . '/compressed/')) {
mkdir($basePath . '/compressed/', 0777, true);
}
if ($compressor->minify($filePath)) {
// echo "  " . $filePath . "<br/>";
chmod($filePath, 0777);
call_user_func_array([$assets, $addFunc], [$fileUri, false]);
}
unset($compressor);
}
}
public function beforeSendResponse(Event $event, CmsApplication $app, Response $response)
{
$request = $this->di->getShared('request');
if ($request->isAjax()) {
return;
}
/** @var Asset $assets */
$this->compressAssets();
$assets = $this->di->getShared('assets');
// Compress CSS
ob_start();
$assets->outputCss();
$assets->outputInlineCss();
$content = str_replace('</head>', ob_get_clean() . '</head>', $response->getContent());
// Compress JS
ob_start();
$assets->outputJs();
$assets->outputInlineJs();
$code = Asset::getCode() . ob_get_clean();
// Extra code (in the footer)
$content = str_replace('</body>', $code . '</body>', $content);
$response->setContent($content);
}
}
|