Пример #1
0
 /**
  * @param string $name
  * @return mixed
  * @throws \Exception
  */
 public function get($name)
 {
     if ($this->di->has($name)) {
         return $this->di->get($name);
     }
     throw new \Exception("Service \"{$name}\" is not defined");
 }
 protected function registerConfig()
 {
     $config = (require __DIR__ . '/config/config.php');
     if ($this->di->has('console.config')) {
         $config->merge($this->di->get('console.config'));
     }
     $this->di['console.config'] = $config;
 }
Пример #3
0
 /**
  * Constructor. Allows you to specify the initial settings for the widget.
  * Parameters can be passed as an associative array.
  * Also, the parameters can be set using the appropriate methods
  *
  * @param array $params
  * @throws \Phalcon\DI\Exception
  * @throws \Phalcon\Session\Exception
  */
 public function __construct(array $params = [])
 {
     if (DI::getDefault() === null) {
         throw new \Phalcon\DI\Exception('DI is not configured!');
     }
     if ($this->hasSession() === false) {
         throw new Exception('Session does not configured in DI');
     }
     if ($this->session->has(self::KEY) === true) {
         $this->user = $this->session->get(self::KEY);
     } else {
         $this->user = false;
     }
     parent::__construct($params);
 }
 /**
  * Called by the DebugBar when data needs to be collected
  * @return array Collected data
  */
 function collect()
 {
     $request = $this->request;
     $response = $this->response;
     $status = $response->getHeaders()->get('Status') ?: '200 ok';
     $responseHeaders = $response->getHeaders()->toArray() ?: headers_list();
     $cookies = $_COOKIE;
     unset($cookies[session_name()]);
     $cookies_service = $response->getCookies();
     if ($cookies_service) {
         $useEncrypt = true;
         if ($cookies_service->isUsingEncryption() && $this->di->has('crypt') && !$this->di['crypt']->getKey()) {
             $useEncrypt = false;
         }
         if (!$cookies_service->isUsingEncryption()) {
             $useEncrypt = false;
         }
         foreach ($cookies as $key => $vlaue) {
             $cookies[$key] = $cookies_service->get($key)->useEncryption($useEncrypt)->getValue();
         }
     }
     $data = array('status' => $status, 'request_query' => $request->getQuery(), 'request_post' => $request->getPost(), 'request_body' => $request->getRawBody(), 'request_cookies' => $cookies, 'request_server' => $_SERVER, 'response_headers' => $responseHeaders, 'response_body' => $request->isAjax() ? $response->getContent() : '');
     if (Version::getId() < 2000000 && $request->isAjax()) {
         $data['request_headers'] = '';
         // 1.3.x has a ajax bug , so we use empty string insdead.
     } else {
         $data['request_headers'] = $request->getHeaders();
     }
     $data = array_filter($data);
     if (isset($data['request_query']['_url'])) {
         unset($data['request_query']['_url']);
     }
     if (empty($data['request_query'])) {
         unset($data['request_query']);
     }
     if (isset($data['request_headers']['php-auth-pw'])) {
         $data['request_headers']['php-auth-pw'] = '******';
     }
     if (isset($data['request_server']['PHP_AUTH_PW'])) {
         $data['request_server']['PHP_AUTH_PW'] = '******';
     }
     foreach ($data as $key => $var) {
         if (!is_string($data[$key])) {
             $data[$key] = $this->formatVar($var);
         }
     }
     return $data;
 }
Пример #5
0
 /**
  * @param \Phalcon\DiInterface $di
  *
  * @return \Phalcon\Mvc\Application
  */
 protected function getApplication(\Phalcon\DiInterface $di)
 {
     if (!$di->has("application")) {
         return $this->getDefaultApplication($di);
     }
     return $di->get("application");
 }
Пример #6
0
 /**
  * @param \Phalcon\DiInterface $di
  *
  * @return \Phalcon\Cli\Console
  */
 protected function getConsole(\Phalcon\DiInterface $di)
 {
     if (!$di->has("console")) {
         return $this->getDefaultConsole($di);
     }
     return $di->get("console");
 }
Пример #7
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * 获取全局配置
      */
     $config = $di->has('config') ? $di->getShared('config') : null;
     /**
      * 各模块可自定义config文件并替换全局的config配置
      */
     if (file_exists($this->modulePath . '/config/config.php')) {
         $override = new Config(include $this->modulePath . '/config/config.php');
         if ($config instanceof Config) {
             $config->merge($override);
         } else {
             $config = $override;
         }
     }
     //重置全局配置
     $di->setShared('config', $config);
     /**
      * 设置各个模块的视图目录
      */
     $view = new View();
     //$view->setViewsDir($this->modulePath . '/views/default/');
     $view->setViewsDir(FRONTEND_PUBLIC_PATH . 'views/default/');
     $view->registerEngines(['.volt' => 'volt', '.php' => 'volt', '.html' => 'volt']);
     $di->set('view', $view);
 }
Пример #8
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * Read common configuration
      */
     $config = $di->has('config') ? $di->getShared('config') : null;
     /**
      * Try to load local configuration
      */
     if (file_exists(__DIR__ . '/config/config.php')) {
         $override = new Config(include __DIR__ . '/config/config.php');
         if ($config instanceof Config) {
             $config->merge($override);
         } else {
             $config = $override;
         }
     }
     /**
      * Setting up the view component
      */
     $view = $di->get('view');
     $view->setViewsDir($config->get('application')->viewsDir);
     $di->set('view', $view);
     // add default namespace
     $dispatcher = $di->get('dispatcher');
     $dispatcher->setDefaultNamespace("Application\\Frontend\\Controllers");
     $di->set('dispatcher', $dispatcher);
 }
Пример #9
0
 /**
  * Setups extra services (if not exist) required by mongo service
  *
  * @param DiInterface $di
  */
 public function setupExtraServices(DiInterface $di)
 {
     if (!$di->has('collectionManager')) {
         $di->set('collectionManager', function () {
             return new Manager();
         });
     }
 }
Пример #10
0
 /**
  * Checks if a service is registered in the DI
  *
  * @param string $serviceName
  * @return boolean
  * @throws Exception
  */
 public function hasService($serviceName)
 {
     if (is_string($serviceName) === false) {
         throw new Exception('Invalid parameter type.');
     }
     if (is_object($this->_dependencyInjector) === false) {
         $this->_dependencyInjector = new FactoryDefault();
     }
     return $this->_dependencyInjector->has($serviceName);
 }
Пример #11
0
 /**
  * Sets the DependencyInjector container
  */
 public function setDI(DiInterface $dependencyInjector)
 {
     /**
      * We automatically set ourselves as application service
      */
     if (!$dependencyInjector->has("application")) {
         $dependencyInjector->set("application", $this);
     }
     $this->_dependencyInjector = $dependencyInjector;
 }
Пример #12
0
 /**
  * Sends the cookie to the HTTP client
  * Stores the cookie definition in session
  *
  * @return \Phalcon\Http\Cookie
  * @throws Exception
  */
 public function send()
 {
     //@note no interface validation
     if (is_object($this->_dependencyInjector) === true) {
         if ($this->_dependencyInjector->has('session') === true) {
             $definition = array();
             if ($this->_expire !== 0) {
                 $definition['expire'] = $this->_expire;
             }
             if (empty($this->_path) === false) {
                 $definition['path'] = $this->_path;
             }
             if (empty($this->_domain) === false) {
                 $definition['domain'] = $this->_domain;
             }
             if (empty($this->_secure) === false) {
                 $definition['secure'] = $this->_secure;
             }
             if (empty($this->_httpOnly) === false) {
                 $definition['httpOnly'] = $this->_httpOnly;
             }
             //The definition is stored in session
             if (count($definition) !== 0) {
                 $session = $this->_dependencyInjector->getShared('session');
                 if (is_null($session) === false) {
                     if ($session instanceof SessionInterface === false) {
                         throw new Exception('Wrong session service.');
                     }
                     $session->set('_PHCOOKIE_' . $this->_name, $definition);
                 }
             }
         }
     }
     /* Encryption */
     if ($this->_useEncryption === true && empty($this->_value) === false) {
         if (is_object($this->_dependencyInjector) === false) {
             //@note wrong exception message
             throw new Exception("A dependency injection object is required to access the 'filter' service");
         }
         $crypt = $this->_dependencyInjector->getShared('crypt');
         if ($crypt instanceof CryptInterface === false) {
             throw new Exception('Wrong crypt service.');
         }
         //Encrypt the value also coding it with base64
         $value = $crypt->encryptBase64($this->_value);
     }
     //Sets the cookie using the standard 'setcookie' function
     //@note use 'bool' as type for the last two parameter
     setcookie((string) $this->_name, (string) $value, (int) $this->_expire, (string) $this->_path, (string) $this->_domain, (bool) $this->_secure, (bool) $this->_httpOnly);
     return $this;
 }
Пример #13
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * Read common configuration
      */
     $config = $di->has('config') ? $di->getShared('config') : null;
     /**
      * Try to load local configuration
      */
     if (file_exists(__DIR__ . '/config/config.php')) {
         $override = new Config(include __DIR__ . '/config/config.php');
         if ($config instanceof Config) {
             $config->merge($override);
         } else {
             $config = $override;
         }
     }
     /**
      * Setting up the view component
      */
     $view = $di->get('view');
     $view->setViewsDir($config->get('application')->viewsDir);
     $di->set('view', $view);
     // register helper
     $di->setShared('adminHelper', function () {
         return new \Application\Admin\Librarys\voltHelper();
     });
     /**
      * Database connection is created based in the parameters defined in the configuration file
      */
     $di['db'] = function () use($config) {
         $config = $config->database->toArray();
         $dbAdapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $config['adapter'];
         unset($config['adapter']);
         return new $dbAdapter($config);
     };
     // add default namespace
     $dispatcher = $di->get('dispatcher');
     $dispatcher->setDefaultNamespace("Application\\Admin\\Controllers");
     $di->set('dispatcher', $dispatcher);
     // register menu
     $di->set('AdminMenus', function () {
         return require __DIR__ . '/config/menus.php';
     });
 }
Пример #14
0
 /**
  * Get identity.
  *
  * @param \Phalcon\Mvc\Model $model
  * @return mixed
  */
 protected function getModelIdentity(PhalconModel $model)
 {
     if (property_exists($model, 'id')) {
         return $model->id;
     }
     if (!$this->di->has('modelsMetadata')) {
         return null;
     }
     $primaryKeys = $this->di->get('modelsMetadata')->getPrimaryKeyAttributes($model);
     switch (count($primaryKeys)) {
         case 0:
             return null;
         case 1:
             return $model->{$primaryKeys[0]};
         default:
             return array_intersect_key(get_object_vars($model), array_flip($primaryKeys));
     }
 }
Пример #15
0
 /**
  * @param \Phalcon\DiInterface $di
  * @return mixed
  */
 public function initialize(\Phalcon\DiInterface $di)
 {
     /** @var \Phalcon\Config $config */
     $config = $di->get('config');
     $viewConfig = isset($config->application->view) ? $config->application->view->toArray() : [];
     if ($di->has('view')) {
         /** @var \Phalcon\Mvc\View $view */
         $view = $di->get('view');
         $viewEngines = $view->getRegisteredEngines();
         if (!$viewEngines) {
             $viewEngines = [];
         }
         $viewEngines['.twig'] = function ($this, $di) use($viewConfig) {
             return new \Phalcon\Mvc\View\Engine\Twig($this, $di, $viewConfig);
         };
         $view->registerEngines($viewEngines);
     }
 }
Пример #16
0
 /**
  * @param \Phalcon\DiInterface $di
  * @return mixed
  */
 public function initialize(\Phalcon\DiInterface $di)
 {
     /** @var \Phalcon\Config $config */
     $config = $di->get('config');
     $viewConfig = isset($config->application->view) ? $config->application->view->toArray() : [];
     if ($di->has('view')) {
         /** @var \Phalcon\Mvc\View $view */
         $view = $di->get('view');
         $viewEngines = $view->getRegisteredEngines();
         if (!$viewEngines) {
             $viewEngines = [];
         }
         $viewEngines['.volt'] = function ($this, $di) use($viewConfig) {
             $volt = new VoltEngine($this, $di);
             $volt->setOptions($viewConfig);
             $volt->getCompiler()->addFilter('toString', (new ToStringFilter())->getFilter());
             return $volt;
         };
         $view->registerEngines($viewEngines);
     }
 }
Пример #17
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * Read common configuration
      */
     $config = $di->has('config') ? $di->getShared('config') : null;
     /**
      * Try to load local configuration
      */
     if (file_exists(__DIR__ . '/config/config.php')) {
         $override = new Config(include __DIR__ . '/config/config.php');
         if ($config instanceof Config) {
             $config->merge($override);
         } else {
             $config = $override;
         }
     }
     $di->setShared('config', $config);
     /**
      * Setting up the view component
      */
     $view = $di->get('view');
     $view->setViewsDir($config->get('application')->viewsDir);
     $di->set('view', $view);
     // register helper
     $di->setShared('adminHelper', function () {
         return new \Application\Admin\Librarys\voltHelper();
     });
     // add default namespace
     $dispatcher = $di->get('dispatcher');
     $dispatcher->setDefaultNamespace("Application\\Admin\\Controllers");
     $di->set('dispatcher', $dispatcher);
     // register menu
     $di->set('AdminMenus', function () {
         return require __DIR__ . '/config/menus.php';
     });
 }
Пример #18
0
 /**
  * Dispatches a handle action taking into account the routing parameters
  *
  * @return object|boolean
  */
 public function dispatch()
 {
     if (is_object($this->_dependencyInjector) === false) {
         $this->_throwDispatchException('A dependency injection container is required to access related dispatching services', self::EXCEPTION_NO_DI);
         return false;
     }
     if (is_object($this->_eventsManager) === true) {
         if ($this->_eventsManager->fire('dispatch:beforeDispatchLoop', $this) === false) {
             return false;
         }
     }
     $numberDispatches = 0;
     $this->_finished = false;
     $handler = null;
     while (true) {
         //Loop until finished is false
         if ($this->_finished === true) {
             break;
         }
         ++$numberDispatches;
         //Throw an exception after 256 consecutive forwards
         if ($numberDispatches >= 256) {
             $this->_throwDispatchException('Dispatcher has detected a cyclic routing causing stability problems', self::EXCEPTION_CYCLIC_ROUTING);
             break;
         }
         $this->_finished = true;
         //If the current namespace is null we use the set in $this->_defaultNamespace
         if (is_null($this->_namespaceName) === true) {
             $this->_namespaceName = $this->_defaultNamespace;
         }
         //If the handler is null we use the set in $this->_defaultHandler
         if (is_null($this->_handlerName) === true) {
             $this->_handlerName = $this->_defaultHandler;
         }
         //If the action is null we use the set in $this->_defaultAction
         if (is_null($this->_actionName) === true) {
             $this->_actionName = $this->_defaultAction;
         }
         //Calling beforeDispatch
         if (is_object($this->_eventsManager) === true) {
             if ($this->_eventsManager->fire('dispatch:beforeDispatch', $this) === false) {
                 continue;
             }
             //Check if the user made a forward in the listener
             if ($this->_finished === false) {
                 continue;
             }
         }
         //We don't camelize the classes if they are in namespaces
         $p = strpos($this->_handlerName, '\\');
         if ($p === false) {
             $camelizedClass = Text::camelize($this->_handlerName);
         } elseif ($p === 0) {
             //@note this only handles one leading slash
             $camelizedClass = substr($this->_handlerName, strlen($this->_handlerName) + 1);
         } else {
             $camelizedClass = $this->_handlerName;
         }
         //Create the complete controller class name prepending the namespace
         if (is_null($this->_namespaceName) === false) {
             if (strrpos($this->_namespaceName, '\\') === strlen($this->_namespaceName) - 1) {
                 $handlerClass = $this->_namespaceName . $camelizedClass . $this->_handlerSuffix;
             } else {
                 $handlerClass = $this->_namespaceName . '\\' . $camelizedClass . $this->_handlerSuffix;
             }
         } else {
             $handlerClass = $camelizedClass . $this->_handlerSuffix;
         }
         //Handlers are retrieved as shared instances from the Service Container
         if ($this->_dependencyInjector->has($handlerClass) === false) {
             //Check using autoloading
             if (class_exists($handlerClass) === false) {
                 if ($this->_throwDispatchException($handlerClass . ' handler class cannot be loaded', self::EXCEPTION_HANDLER_NOT_FOUND) === false) {
                     if ($this->_finished === false) {
                         continue;
                     }
                 }
                 break;
             }
         }
         //Handlers must be only objects
         $handler = $this->_dependencyInjector->getShared($handlerClass);
         if (is_object($handler) === false) {
             if ($this->_throwDispatchException('Invalid handler returned from the services container', self::EXCEPTION_INVALID_HANDLER) === false) {
                 if ($this->_finished === false) {
                     continue;
                 }
             }
             break;
         }
         //If the object was recently created in the DI we initialize it
         $wasFresh = $this->_dependencyInjector->wasFreshInstance();
         $this->_activeHandler = $handler;
         //Check if the method exists in the handler
         $actionMethod = $this->_actionName . $this->_actionSuffix;
         if (method_exists($handler, $actionMethod) === false) {
             //Call beforeNotFoundAction
             if (is_object($this->_eventsManager) === true) {
                 if ($this->_eventsManager->fire('dispatch:beforeNotFoundAction', $this) === false) {
                     continue;
                 }
                 if ($this->_finished === false) {
                     continue;
                 }
             }
             if ($this->_throwDispatchException('Action \'' . $this->_actionName . '\' was not found on handler \'' . $this->_handlerName . '\'', self::EXCEPTION_ACTION_NOT_FOUND) === false) {
                 if ($this->_finished === false) {
                     continue;
                 }
             }
             break;
         }
         //Calling beforeExecuteRoute
         if (is_object($this->_eventsManager) === true) {
             if ($this->_eventsManager->fire('dispatch:beforeExecuteRoute', $this) === false) {
                 continue;
             }
             //Check if the user made a forward in the listener
             if ($this->_finished === false) {
                 continue;
             }
         }
         //Calling beforeExecuteRoute as callback and event
         if (method_exists($handler, 'beforeExecuteRoute') === true) {
             if ($handler->beforeExecuteRoute($this) === false) {
                 continue;
             }
             //Check if the user made a forward in the listener
             if ($this->_finished === false) {
                 continue;
             }
         }
         //Check if params is an array
         if (is_array($this->_params) === false) {
             if ($this->_throwDispatchException('Action parameters must be an Array', self::EXCEPTION_INVALID_PARAMS) === false) {
                 if ($this->_finished === false) {
                     continue;
                 }
             }
             break;
         }
         //Call the 'initialize' method just once per request
         if ($wasFresh === true) {
             if (method_exists($handler, 'initialize') === true) {
                 $handler->initialize();
             }
         }
         //Call the method with/without exceptions if an events manager is present
         if (is_object($this->_eventsManager) === true) {
             try {
                 //Call the method allowing exceptions
                 $m = new ReflectionMethod($handler, $actionMethod);
                 $value = $m->invokeArgs($handler, $this->_params);
             } catch (\Exception $exception) {
                 //Copy the exception to rethrow it later if needed
                 //Try to handle the exception
                 if ($this->_handleException($exception) === false) {
                     if ($this->_finished === false) {
                         continue;
                     }
                 } else {
                     //Exception wasn't handled, rethrow it
                     throw new Exception($exception);
                 }
             }
             //Update the latest value produced by the latest handler
             $this->_returnedValue = $value;
         } else {
             //Call the method handling exceptions as normal
             $this->_returnedValue = call_user_func_array(array($handler, $actionMethod), $this->_params);
         }
         $this->_lastHandler = $handler;
         //Calling afterExecuteRoute
         if (is_object($this->_eventsManager) === true) {
             if ($this->_eventsManager->fire('dispatch:afterExecuteRoute', $this) === false) {
                 continue;
             }
             if ($this->_finished === false) {
                 continue;
             }
             //Calling afetDispatch
             $this->_eventsManager->fire('dispatch:afterDispatch', $this);
         }
         //Calling afterExecuteRoute as callback and event
         if (method_exists($handler, 'afterExecuteRoute') === true) {
             if ($handler->afterExecuteRoute($this, $this->_returnedValue) === false) {
                 continue;
             }
             if ($this->_finished === false) {
                 continue;
             }
         }
     }
     //Call afterDispatchLoop
     if (is_object($this->_eventsManager) === true) {
         $this->_eventsManager->fire('dispatch:afterDispatchLoop', $this);
     }
     return $handler;
 }
Пример #19
0
 /**
  * {@inheritdoc}
  */
 public function verifyRequiredServices(DiInterface $di)
 {
     if (!$di->has('db')) {
         throw new NoRequiredServiceException();
     }
 }
Пример #20
0
 public static function handle(\Exception $e, \Phalcon\DiInterface $di)
 {
     if ($e instanceof \FA\Exception\NotLoggedIn) {
         // Redirect to login page for not-logged-in users.
         $flash = $di['flash'];
         $flash->addMessage('<b>Error:</b> You must be logged in to access this page!', 'red');
         // Set referrer for login redirection.
         $session = $di['session'];
         $session = $session->get('referrer_login');
         $session->url = $di['url']->current();
         // Redirect to login page.
         $login_url = $di['url']->get('account/login');
         $response = $di->get('response');
         $response->redirect($login_url, 302);
         $response->send();
         return;
     } elseif ($e instanceof \FA\Exception\PermissionDenied) {
         // Bounce back to homepage for permission-denied users.
         $di['flash']->addMessage('You do not have permission to access this portion of the site.', \FA\Flash::ERROR);
         $home_url = $di['url']->get('');
         $response = $di['response'];
         $response->redirect($home_url, 302);
         $response->send();
         return;
     } elseif ($e instanceof \Phalcon\Mvc\Dispatcher\Exception) {
         // Handle 404 page not found exception
         if ($di->has('view')) {
             $view = $di['view'];
             $view->disable();
         }
         $view = \FA\Phalcon\View::getView(array());
         $result = $view->getRender('error', 'pagenotfound');
         $response = $di['response'];
         $response->setStatusCode(404, "Not Found");
         $response->setContent($result);
         $response->send();
         return;
     } elseif ($e instanceof \FA\Exception\Bootstrap) {
         // Bootstrapping error; cannot render template for error display.
         if (FA_APPLICATION_ENV != 'production') {
             self::renderPretty($e, $di);
             return;
         } else {
             $response = $di->get('response');
             $response->setStatusCode(500, "Internal Server Error");
             $exception_msg = "<b>Application core exception: </b>\n<blockquote>" . $e->getMessage() . "</blockquote>" . "\n" . "on line <b>" . $e->getLine() . "</b> of <i>" . $e->getFile() . "</i>";
             $response->setContent($exception_msg);
             $response->send();
             return;
         }
     } else {
         if ($di->has('view')) {
             $view = $di->get('view');
             $view->disable();
         }
         $show_debug = false;
         if ($di->has('acl')) {
             $acl = $di->get('acl');
             if ($acl->isAllowed('administer all')) {
                 $show_debug = true;
             }
         }
         if (FA_APPLICATION_ENV != 'production') {
             $show_debug = true;
         }
         if ($show_debug) {
             self::renderPretty($e, $di);
             return;
         } else {
             $view = \FA\Phalcon\View::getView(array());
             $view->setVar('exception', $e);
             $result = $view->getRender('error', 'general');
             $response = $di->get('response');
             $response->setStatusCode(500, "Internal Server Error");
             $response->setContent($result);
             $response->send();
             return;
         }
     }
 }
Пример #21
0
 /**
  * Normalize bootstrap key-value
  *
  * @param DiInterface $container Container to prepare
  * @param mixed $key Key for bootstrap
  * @return  mixed value for $key
  */
 private static function normalizeBootstrapValue(DiInterface $container, $key)
 {
     if (is_string($key)) {
         if ($container->has($key)) {
             return $container->get($key);
         }
         if (class_exists($key)) {
             return new $key();
         }
     }
     if (is_object($key)) {
         return $key;
     }
     return;
 }