/** * Initialize Phalcon . */ public function __construct() { $executionTime = -microtime(true); define('APP_PATH', realpath('..') . '/'); $this->config = $config = new ConfigIni(APP_PATH . 'app/config/config.ini'); $this->di = new FactoryDefault(); $this->di->set('config', $config); $this->di->set('dispatcher', function () { $eventsManager = new EventsManager(); $eventsManager->attach('dispatch:beforeExecuteRoute', new SecurityPlugin()); $dispatcher = new Dispatcher(); $dispatcher->setEventsManager($eventsManager); return $dispatcher; }); $this->di->set('crypt', function () use($config) { $crypt = new Crypt(); $crypt->setKey($config->application->phalconCryptKey); return $crypt; }); $this->setDisplayErrors(); $this->title = $config->application->title; $this->registerDirs(); $this->setDB($config); $this->setViewProvider($config); $this->setURLProvider($config); $this->setSession(); $this->application = new Application($this->di); $this->application->view->executionTime = $executionTime; $this->setCSSCollection(); $this->setJSCollection(); $this->setTitle(); }
/** * Tests the encryption * * @author Nikolaos Dimopoulos <*****@*****.**> * @since 2014-10-17 */ public function testCryptEncryption() { $this->specify("encryption does not return correct results", function () { $tests = [md5(uniqid()) => str_repeat('x', mt_rand(1, 255)), time() . time() => str_shuffle('abcdefeghijklmnopqrst'), 'le$ki12432543543543543' => null]; $modes = [MCRYPT_MODE_ECB, MCRYPT_MODE_CBC, MCRYPT_MODE_CFB, MCRYPT_MODE_CFB, MCRYPT_MODE_NOFB]; $crypt = new PhTCrypt(); foreach ($modes as $mode) { $crypt->setMode($mode); foreach ($tests as $key => $test) { $crypt->setKey(substr($key, 0, 16)); $encryption = $crypt->encrypt($test); $actual = rtrim($crypt->decrypt($encryption), ""); expect($actual)->equals($test); } foreach ($tests as $key => $test) { $encryption = $crypt->encrypt($test, substr($key, 0, 16)); $actual = rtrim($crypt->decrypt($encryption, substr($key, 0, 16)), ""); expect($actual)->equals($test); } } }); }
return new MetaDataAdapter(array('metaDataDir' => $config->application->cacheDir . 'metaData/')); }); /** * Start the session the first time some component request the session service */ $di->set('session', function () { $session = new SessionAdapter(); $session->start(); return $session; }); /** * Crypt service */ $di->set('crypt', function () use($config) { $crypt = new Crypt(); $crypt->setKey($config->application->cryptSalt); return $crypt; }); /** * Dispatcher use a default namespace */ $di->set('dispatcher', function () { $dispatcher = new Dispatcher(); $dispatcher->setDefaultNamespace('Vokuro\\Controllers'); return $dispatcher; }); /** * Loading routes from the routes.php file */ $di->set('router', function () { return require __DIR__ . '/routes.php';
/** * 默认服务依赖注入 * */ protected function commonServices() { $mode = $this->mode; $di = $this->mode === 'CLI' ? new Cli() : new FactoryDefault(); // 日志 $di->set('logger', function () { $config = load('logger'); $adapter = $config['adapter']; $filename = $config[$adapter]['filename']; $filedir = dirname($filename); if (empty($config)) { throw new \Exception('logger config Require failed'); } if (!is_dir($filedir)) { mkdir($filedir, 0755, true); } $logger = new File($filename); $formatter = new Line(null, 'Y-m-d H:i:s'); $loglevel = config('app.loglevel'); $logger->setFormatter($formatter); $logger->setLogLevel($loglevel ? $loglevel : \Phalcon\Logger::ERROR); return $logger; }, true); $this->application->setDI($di); // 命名空间 $di->set('dispatcher', function () use($mode) { $dispatcher = new Dispatcher(); $dispatcher = $mode === 'CLI' ? new \Phalcon\CLI\Dispatcher() : new Dispatcher(); $bootstrap = load('bootstrap'); $default = $bootstrap['dispatcher']; $dispatcher->setDefaultNamespace($mode === 'CLI' ? $default['cli'] : $default['default']); return $dispatcher; }, true); // 路由 if ($load = load('router', null, true)) { if ($load instanceof Router) { $di->set('router', $load); } } // 视图 $di->set('view', function () { $view = new View(); $view->setViewsDir(APP_VIEW); return $view; }, true); // 加解密 if ($config = config('crypt')) { $di->set('crypt', function () use($config) { $crypt = new Crypt(); $crypt->setKey($config['authkey']); return $crypt; }, true); } // 默认缓存 if ($config = config('cache')) { $di->set('cache', function () use($config) { $cache = null; $adapter = strtolower($config['adapter']); $options = $config[$adapter]; $frontend = new Data(array('lifetime' => $config['lifetime'])); switch ($adapter) { case 'memcache': $cache = new Memcache($frontend, $options); break; case 'redis': if (empty($options['auth'])) { unset($options['auth']); } $cache = new \Phalcon\Extend\Cache\Backend\Redis($frontend, $options); break; } return $cache; }, true); } // Cookies if ($config = config('cookies')) { $di->set('cookies', function () use($config) { $cookies = new \Phalcon\Extend\Http\Response\Cookies($config); if (!config('crypt.authkey')) { $cookies->useEncryption(false); } return $cookies; }, true); } // Session if ($config = config('session')) { $di->set('session', function () use($config) { if (!empty($config['options'])) { foreach ($config['options'] as $name => $value) { ini_set("session.{$name}", $value); } } $adapter = strtolower($config['adapter']); $options = $config[$adapter]; switch ($adapter) { case 'memcache': $session = new SessionMemcache($options); break; case 'redis': $session = new \Phalcon\Extend\Session\Adapter\Redis($options); break; default: $session = new SessionFiles(); break; } $session->start(); return $session; }, true); } // Db if ($config = config('db')) { $di->set('db', function () use($config) { $mysql = new Mysql($config); if (debugMode()) { $eventsManager = new Manager(); $logger = new File(APP_LOG . DS . 'Mysql' . LOGEXT); $formatter = new Line(null, 'Y-m-d H:i:s'); $logger->setFormatter($formatter); $eventsManager->attach('db', function ($event, $mysql) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($mysql->getSQLStatement(), Logger::INFO); } if ($event->getType() == 'afterQuery') { } }); $mysql->setEventsManager($eventsManager); } return $mysql; }, true); } // DB 元信息 if ($config = config('metadata')) { $di->set('modelsMetadata', function () use($config) { $modelsMetadata = null; $adapter = strtolower($config['adapter']); $options = $config[$adapter]; switch ($adapter) { case 'memcache': $modelsMetadata = new MetaDataMemcache($options); break; case 'redis': if (empty($options['auth'])) { unset($options['auth']); } $modelsMetadata = new MetaDataRedis($options); break; } return $modelsMetadata; }, true); } $this->application->setDI($di); }
public function setKey($key) { return parent::setKey($key); }
$di->setShared('memory', function () { return new \Phalcon\Mvc\Model\MetaData\Memory(); }); // hold messages that should be returned to the client $di->setShared('registry', function () { return new \Phalcon\Registry(); }); // phalcon inflector? $di->setShared('inflector', function () { return new Inflector(); }); // one way to do reversable encryption $di->setShared('crypt', function () { $crypt = new Crypt(); // Set a global encryption key $crypt->setKey('%31.1e$i86e$f!8jz'); return $crypt; }); // one way to do reversable encryption $di->setShared('security', function () { $security = new Security(); // Set a global encryption key $security->setWorkFactor(12); return $security; }); // one way to do reversable encryption $di->setShared('paymentProcessor', function () { $setting = \PhalconRest\Models\Settings::findFirst(4); return new \PhalconRest\Libraries\Payments\StripeAdapter($setting->value); }); /**
$di->set('flash', function () { return new Flash(array('error' => 'alert alert-danger', 'success' => 'label label-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning')); }); $di->set('security', function () { $security = new Security(); $security->setWorkFactor(12); return $security; }); /** * Start the session the first time some component request the session service */ $di->setShared('session', function () { $session = new SessionAdapter(array('uniqueId' => 'my-app-1')); $session->start(); return $session; }); $di->set('cookies', function () { $cookies = new Cookies(); $cookies->useEncryption(false); return $cookies; }); $di->set('crypt', function () { $crypt = new Crypt(); $crypt->setKey($config->application->encryptKey); //Use your own key! return $crypt; }); //Register an user component $di->set('elements', function () { return new Elements(); });
$cache = new Phalcon\Cache\Backend\File($frontCache, ['cacheDir' => APP_URL . 'cache/model/']); break; case 'memcache': $cache = new Phalcon\Cache\Backend\Memcache($frontCache, ['host' => $config->memcache->host, 'port' => $config->memcache->port]); break; } return $cache; }; $di['cache'] = function () use($di) { return $di->get('modelsCache'); }; /** * Access Control List */ $di['auth'] = function () { return new Auth(); }; /** * Init cookie */ $di->set('cookies', function () { $cookies = new Cookies(); $cookies->useEncryption(true); return $cookies; }); $di->set('crypt', function () { $crypt = new Crypt(); $crypt->setMode(MCRYPT_MODE_CFB); $crypt->setKey('#1Pdj8$=dp?.ak#$'); return $crypt; });
/** * Initializes Crypt */ public function initCrypt($options = []) { $config = $this->di['config']; $this->di->set('crypt', function () use($config) { $crypt = new PhCrypt(); $crypt->setMode(MCRYPT_MODE_CFB); $crypt->setKey($config->app_crypt->encryptionkey); return $crypt; }); }
// Set the Logger Handler $di['logger'] = function () { return new FileLogger('../logs/debug.log'); }; //Register Volt as a service $di->set('voltService', function ($view, $di) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array("compiledPath" => COMPILED_VIEW_PATH, "compiledExtension" => ".php")); return $volt; }); $di->set('crypt', function () { $crypt = new Crypt(); // 使用 blowfish $crypt->setCipher('blowfish'); // 设置全局加密密钥 $crypt->setKey('blowfish'); return $crypt; }, true); // Setting up the view component $di['view'] = function () { $view = new View(); $view->setViewsDir('../app/views/'); $view->disableLevel(array(View::LEVEL_LAYOUT => true, View::LEVEL_MAIN_LAYOUT => true)); $view->registerEngines(array(".phtml" => 'voltService', ".volt" => 'voltService', ".json" => 'voltService')); return $view; }; // Setup a base URI so that all generated URIs include the "tutorial" folder $di['url'] = function () { $url = new Url(); $url->setBaseUri("/cgi/"); return $url;
$logger = new FileLogger("../apps/log/debug.log"); $eventManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); } $db = new DbAdapter(array('host' => $config->mysql->host, 'username' => $config->mysql->username, 'password' => $config->mysql->password, 'dbname' => $config->mysql->name)); if (DEBUG) { $db->setEventsManager($eventManager); } return $db; }); $di->set('crypt', function () use($config) { $crypt = new Crypt(); $crypt->setKey($config->crypt->key); return $crypt; }); $di->setShared('redis', function () use($config) { $redis = new Redis(); $redis->open($config->redis->host, $config->redis->port); return $redis; }); $di->setShared('session', function () { $session = new RedisSessionAdapter(array('path' => 'tcp://127.0.0.1:6379?weight=1')); $session->start(); return $session; }); $di->set('router', function () { $router = new Router(); $router->add("/:controller/:action/:params", array('module' => 'frontend', 'controller' => 1, 'action' => 2, 'params' => 3));
/** * Init crypt hash for cookie service. * * @param DI $di Dependency Injection. * @param Config $config Config object. * * @return void */ public function _initCrypt($di, $config) { $di->set('crypt', function () use($config) { $crypt = new PhCrypt(); $crypt->setMode(MCRYPT_MODE_CFB); $crypt->setKey($config->global->cookieEncryptionkey); return $crypt; }); }
<?php use Phalcon\DI\FactoryDefault, Phalcon\Mvc\View, Phalcon\Mvc\Dispatcher, Phalcon\Mvc\Url as UrlResolver, Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter, Phalcon\Mvc\View\Engine\Volt as VoltEngine, Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter, Phalcon\Session\Adapter\Files as SessionAdapter, Phalcon\Http\Response\Cookies, Phalcon\Events\Manager as EventsManager, Phalcon\Crypt, Phalcon\Logger\Adapter\File as FileLogger, Phalcon\Cache\Frontend\Data as FrontData, Phalcon\Cache\Backend\File as BackFile, Phalcon\Cache\Backend\Redis as BackRedis, MyApp\Plugins\SecurityPlugin; //$di = new Phalcon\Di(); $di = new FactoryDefault(); $di->set('config', function () use($config) { return $config; }, true); $di->set('router', function () { return require __DIR__ . '/routes.php'; }, true); $di->set('crypt', function () use($config) { $crypt = new Crypt(); $crypt->setKey($config->setting->cryptKey); return $crypt; }, true); $di->set('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }, true); $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir(BASE_DIR . $config->application->viewsDir); $view->registerEngines(array('.html' => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); $volt->setOptions(array('compiledPath' => BASE_DIR . $config->application->cacheDir, 'compiledSeparator' => '_')); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }, true);
/** * Register the session flash service with the Twitter Bootstrap classes */ $di->set('flash', function () { return new Flash(array('error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning')); }); /** * Start the session the first time some component request the session service */ $di->set('session', function () { $session = new SessionAdapter(); $session->start(); return $session; }); $di->set('cookies', function () { $cookies = new Cookies(); $cookies->useEncryption(false); return $cookies; }); $di->set('crypt', function () { $crypt = new Crypt(); $crypt->setKey('#1dj8$=dp?.ak//j1V$'); // Use your own key! return $crypt; }); $di->set('security', function () { $security = new Security(); // Set the password hashing factor to 12 rounds $security->setWorkFactor(12); return $security; }, true);
$di->set('redis', function () use($config) { if ($config->redis->enabled) { $redis = new Redis(); if ($config->redis->unixsocket) { $redis->connect($config->redis->unixsocket); } else { $redis->connect($config->redis->host, $config->redis->port); } return $redis; } else { return null; } }, true); $di->set('crypt', function () use($config) { $crypt = new Crypt(); $crypt->setKey($config->application->crypt->key); return $crypt; }); $di->set('url', function () use($config) { $url = new UrlResolver(); if (!$config->application->debug) { $url->setBaseUri($config->application->production->baseUri); $url->setStaticBaseUri($config->application->production->staticBaseUri); } else { $url->setBaseUri($config->application->development->baseUri); $url->setStaticBaseUri($config->application->development->staticBaseUri); } return $url; }, true); $di->set('volt', function ($view, $di) use($config) { $volt = new Volt($view, $di);
/** * Mail service */ $di->setShared('mailer', function () use($di) { $config = $di->get('config'); $mailManager = new MailManager($config->mailer, $config->site->mail); $mailManager->setDI($di); return $mailManager; }); /** * */ $di->set('crypt', function () use($di) { $config = $di->get('config'); $crypt = new Crypt(); $crypt->setKey($config->security->cryptKey); return $crypt; }); /** * Access Control List */ $di->set('acl', function () use($di) { $configDir = $di->getConfig()->path->configDir; $aclData = (require "{$configDir}/acl.php"); $acl = new Acl($aclData); return $acl; }); /** * */ $di->setShared('url', function () use($di) {
$di->set('flashSession', function () { $flash = new Session(['error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning']); return $flash; }); // Database connection is created based in the parameters defined in the configuration file $di->set('db', function () use($di) { return new Mysql(['host' => $di->get('config')->database->mysql->host, 'username' => $di->get('config')->database->mysql->username, 'password' => $di->get('config')->database->mysql->password, 'dbname' => $di->get('config')->database->mysql->dbname, 'options' => [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $di->get('config')->database->mysql->charset]]); }, true); $di->set('cookies', function () { $cookies = new Cookies(); $cookies->useEncryption(false); return $cookies; }, true); $di->set('crypt', function () use($di) { $crypt = new Crypt(); $crypt->setKey($di->get('config')->application->cryptSalt); //Use your own key! return $crypt; }); $di->set('security', function () { $security = new Security(); //Set the password hashing factor to 12 rounds $security->setWorkFactor(12); return $security; }, true); //Set the models cache service $di->set('modelsCache', function () { // Cache data for one day by default $frontCache = new Data(['lifetime' => 86400]); // Memcached connection settings $cache = new Memcache($frontCache, ['host' => 'localhost', 'port' => 11211]);
/** * cookie 设置 */ protected function initCookie() { $config = $this->config; if ($config->offsetExists('cookie') && $config->cookie->offsetExists('encry')) { $this->di['cookies'] = function () { $cookies = new Cookies(); $cookies->useEncryption(true); // 是否加密 return $cookies; }; $this->di['crypt'] = function () use($config) { $crypt = new Crypt(); $cryptKey = $config->cookie->offsetExists('cryptKey') ? $config->cookie->cryptKey : 'ice.deng@2015'; $crypt->setKey($cryptKey); return $crypt; }; } }