Пример #1
0
 /**
  * Applies methods set from hooks to an object in __construct()
  *
  * @param string $configKey
  */
 public static function applyHookMethods($configKey, &$object = null)
 {
     if (empty($object)) {
         $object = self;
     }
     if ($object instanceof Table) {
         $objectName = $object->alias();
     } else {
         $objectName = $object->name;
     }
     if (php_sapi_name() !== 'cli') {
         $prefix = ($prefix = Router::getRequest()->param('prefix')) ? Inflector::camelize($prefix) . '.' : '';
         $plugin = ($plugin = Router::getRequest()->param('plugin')) ? $plugin . '.' : '';
         $objectName = $prefix . $plugin . $objectName;
         $hookMethods = Configure::read($configKey . '.' . $objectName);
         if (is_array(Configure::read($configKey . '.*'))) {
             $hookMethods = Hash::merge(Configure::read($configKey . '.*'), $hookMethods);
         }
         if (is_array($hookMethods)) {
             foreach ($hookMethods as $method => $values) {
                 if (is_callable([$object, $method])) {
                     foreach ($values as $name => $config) {
                         $object->{$method}($name, $config);
                     }
                 }
             }
         }
     }
 }
 /**
  * testRequestAction method
  *
  * @return void
  */
 public function testRequestAction()
 {
     $this->assertNull(Router::getRequest(), 'request stack should be empty.');
     $result = $this->object->requestAction('');
     $this->assertFalse($result);
     $result = $this->object->requestAction('/request_action/test_request_action');
     $expected = 'This is a test';
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction(Configure::read('App.fullBaseUrl') . '/request_action/test_request_action');
     $expected = 'This is a test';
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction('/request_action/another_ra_test/2/5');
     $expected = 7;
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction('/tests_apps/index', array('return'));
     $expected = 'This is the TestsAppsController index view ';
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction('/tests_apps/some_method');
     $expected = 5;
     $this->assertEquals($expected, $result);
     $result = $this->object->requestAction('/request_action/paginate_request_action');
     $this->assertNull($result);
     $result = $this->object->requestAction('/request_action/normal_request_action');
     $expected = 'Hello World';
     $this->assertEquals($expected, $result);
     $this->assertNull(Router::getRequest(), 'requests were not popped off the stack, this will break url generation');
 }
Пример #3
0
 /**
  * Prepares the default language to use by the script.
  *
  * ### Detection Methods
  *
  * This method applies the following detection methods when looking for
  * language to use:
  *
  * - GET parameter: If `locale` GET parameter is present in current request, and
  *   if it's a valid language code, then will be used as current language and
  *   also will be persisted on `locale` session for further use.
  *
  * - URL: If current URL is prefixed with a valid language code and
  *   `url_locale_prefix` option is enabled, URL's language code will be used.
  *
  * - Locale session: If `locale` session exists it will be used.
  *
  * - User session: If user is logged in and has selected a valid preferred
  *   language it will be used.
  *
  * - Default: Site's language will be used otherwise.
  *
  * ### Locale Prefix
  *
  * If `url_locale_prefix` option is enabled, and current request's URL is not
  * language prefixed, user will be redirected to a locale-prefixed version of
  * the requested URL (using the language code selected as explained above).
  *
  * For example:
  *
  *     /article/demo-article.html
  *
  * Might redirects to:
  *
  *     /en_US/article/demo-article.html
  *
  * @param \Cake\Event\Event $event containing the request, response and
  *  additional parameters
  * @return void
  * @throws \Cake\Network\Exception\InternalErrorException When no valid request
  *  object could be found
  */
 public function beforeDispatch(Event $event)
 {
     parent::beforeDispatch($event);
     $request = Router::getRequest();
     if (empty($request)) {
         throw new InternalErrorException(__d('cms', 'No request object could be found.'));
     }
     $locales = array_keys(quickapps('languages'));
     $localesPattern = '(' . implode('|', array_map('preg_quote', $locales)) . ')';
     $rawUrl = str_replace_once($request->base, '', env('REQUEST_URI'));
     $normalizedURL = str_replace('//', '/', "/{$rawUrl}");
     if (!empty($request->query['locale']) && in_array($request->query['locale'], $locales)) {
         $request->session()->write('locale', $request->query['locale']);
         I18n::locale($request->session()->read('locale'));
     } elseif (option('url_locale_prefix') && preg_match("/\\/{$localesPattern}\\//", $normalizedURL, $matches)) {
         I18n::locale($matches[1]);
     } elseif ($request->session()->check('locale') && in_array($request->session()->read('locale'), $locales)) {
         I18n::locale($request->session()->read('locale'));
     } elseif ($request->is('userLoggedIn') && in_array(user()->locale, $locales)) {
         I18n::locale(user()->locale);
     } elseif (in_array(option('default_language'), $locales)) {
         I18n::locale(option('default_language'));
     } else {
         I18n::locale(CORE_LOCALE);
     }
     if (option('url_locale_prefix') && !$request->is('home') && !preg_match("/\\/{$localesPattern}\\//", $normalizedURL)) {
         $url = Router::url('/' . I18n::locale() . $normalizedURL, true);
         http_response_code(303);
         header("Location: {$url}");
         die;
     }
 }
Пример #4
0
 /**
  * get the body for htmll message
  *
  * @access private
  * @author sakuragawa
  */
 private function getHtml($message, $file, $line, $context = null)
 {
     $params = Router::getRequest();
     $trace = Debugger::trace(array('start' => 2, 'format' => 'base'));
     $session = isset($_SESSION) ? $_SESSION : array();
     $msg = array('<p><strong>', $message, '</strong></p>', '<p>', $file . '(' . $line . ')', '</p>', '', '<h2>', 'Backtrace:', '</h2>', '', '<pre>', self::dumper($trace), '</pre>', '', '<h2>', 'Request:', '</h2>', '', '<h3>URL</h3>', $this->url(), '<h3>Client IP</h3>', $this->getClientIp(), '<h3>Referer</h3>', env('HTTP_REFERER'), '<h3>Parameters</h3>', self::dumper($params), '<h3>Cake root</h3>', APP, '', '<h2>', 'Environment:', '</h2>', '', self::dumper($_SERVER), '', '<h2>', 'Session:', '</h2>', '', self::dumper($session), '', '<h2>', 'Cookie:', '</h2>', '', self::dumper($_COOKIE), '', '<h2>', 'Context:', '</h2>', '', self::dumper($context), '');
     return join("", $msg);
 }
Пример #5
0
 public function afterLogin($event)
 {
     $entity = $event->data['user'];
     $entity->isNew(false);
     $entity->last_login = new Time();
     $entity->last_ip = Router::getRequest(true)->clientIp();
     TableRegistry::get('users')->save($entity);
 }
Пример #6
0
 /**
  * Gets content's details page URL.
  *
  * Content's details URL's follows the syntax below:
  *
  *     http://example.com/{content-type-slug}/{content-slug}{CONTENT_EXTENSION}
  *
  * Example:
  *
  *     http://example.com/blog-article/my-first-article.html
  *
  * @return string
  */
 protected function _getUrl()
 {
     $url = Router::getRequest()->base;
     if (option('url_locale_prefix')) {
         $url .= '/' . I18n::locale();
     }
     $url .= "/{$this->content_type_slug}/{$this->slug}";
     return Router::normalize($url) . CONTENT_EXTENSION;
 }
 /**
  * Validate a google recaptcha.
  *
  * @param string $value The captcha value.
  * @param array $context The form context.
  * @return bool
  */
 public static function googleRecaptcha($value, $context)
 {
     $httpClient = new Client();
     $googleReponse = $httpClient->post('https://www.google.com/recaptcha/api/siteverify', ['secret' => Configure::read('Google.Recaptcha.secret'), 'response' => $value, 'remoteip' => Router::getRequest()->clientIp()]);
     $result = json_decode($googleReponse->body(), true);
     if (!empty($result['error-codes'])) {
         Log::error('Google Recaptcha: ' . $result['error-codes'][0]);
     }
     return (bool) $result['success'];
 }
Пример #8
0
 /**
  * {@inheritDoc}
  *
  * The entity to which this instance is attached to will be removed from
  * resulting result set if its publishing date does not match current date, this
  * constraint is not applied on the backend section of the site.
  */
 public function beforeFind(Field $field, array $options, $primary)
 {
     if ($primary && !Router::getRequest()->isAdmin() && !empty($field->extra['from']['timestamp']) && !empty($field->extra['to']['timestamp'])) {
         $now = time();
         if ($field->extra['from']['timestamp'] > $now || $now > $field->extra['to']['timestamp']) {
             return null;
             // remove entity from result set
         }
     }
     return true;
 }
Пример #9
0
 /**
  * Return the content of CakePHP App.base.
  * If the App.base value is false, it returns the generated URL automatically
  * by mimicking how CakePHP add the base to its URL.
  *
  * @return string the application base directory
  */
 protected function _getAppBase()
 {
     $baseUrl = Configure::read('App.base');
     if (!$baseUrl) {
         $request = Router::getRequest(true);
         if (!$request) {
             $baseUrl = '';
         } else {
             $baseUrl = $request->base;
         }
     }
     return $baseUrl . '/';
 }
 /**
  * {@inheritDoc}
  */
 protected function _getController()
 {
     if (!($request = Router::getRequest(true))) {
         $request = new Request();
     }
     $response = new Response();
     try {
         $controller = new TestAppsErrorController($request, $response);
         $controller->layout = 'banana';
     } catch (\Exception $e) {
         $controller = new Controller($request, $response);
         $controller->viewPath = 'Error';
     }
     return $controller;
 }
Пример #11
0
 /**
  * Read a value from POST data.
  *
  * It reads the first input and removes that value from the stack,
  * so consecutive readings are supported as follow:
  *
  * **Incoming POST data array**
  *
  * ```php
  * [
  *     'input1' => 'value1',
  *     'input2' => 'value2',
  *     'input3' => 'value3',
  * ]
  * ```
  *
  * **Reading from POST**:
  *
  * ```php
  * $this->read(); // returns "value1"
  * $this->read(); // returns "value2"
  * $this->read(); // returns "value3"
  * $this->read(); // returns false
  * ```
  *
  * @return mixed The value from POST data
  */
 public function read()
 {
     $request = Router::getRequest();
     if (!empty($request) && empty($this->_postData)) {
         $this->_postData = (array) $request->data();
     }
     if (!empty($this->_postData)) {
         $keys = array_keys($this->_postData);
         $first = array_shift($keys);
         $value = $this->_postData[$first];
         unset($this->_postData[$first]);
         return $value;
     }
     return false;
 }
 public static function createJob($data)
 {
     //Fill in current Routing details so the queued email can
     //generate correct absolute urls
     $request = Router::getRequest();
     $data['fullBaseUrl'] = Router::fullBaseUrl() . (empty($request) ? null : $request->base);
     $data['settings']['domain'] = empty($request) ? null : $request->host();
     if (Configure::read('debugEmailRedirect')) {
         if (empty($request)) {
             $loggedInUser = [];
         } else {
             //If we're proxied, then make sure to get *actual* login, not
             //proxied
             $loggedInUser = $request->session()->read('proxy.realUser');
             if (empty($loggedInUser)) {
                 $loggedInUser = $request->session()->read('Auth.User');
             }
         }
         if (empty($loggedInUser['emailAddress'])) {
             $to = '*****@*****.**';
         } else {
             if (empty($loggedInUser['name'])) {
                 $to = $loggedInUser['emailAddress'];
             } else {
                 $to = [$loggedInUser['emailAddress'] => $loggedInUser['name']];
             }
         }
         $originalTo = [];
         $toFields = ['to', 'addTo', 'cc', 'addCC', 'bcc', 'addBcc'];
         foreach ($toFields as $toField) {
             if (!empty($data['settings'][$toField])) {
                 foreach ((array) $data['settings'][$toField] as $originalEmail => $originalName) {
                     if (is_int($originalEmail)) {
                         $originalTo[] = $originalName;
                     } else {
                         $originalTo[] = "{$originalName} <{$originalEmail}>";
                     }
                 }
                 unset($data['settings'][$toField]);
             }
         }
         $data['vars']['originalTo'] = implode(', ', $originalTo);
         $data['settings']['to'] = $to;
     }
     return TableRegistry::get('Queue.QueuedTasks')->createJob('BYUEmail', $data);
 }
Пример #13
0
 /**
  * Applies Routing and additionalParameters to the request to be dispatched.
  * If Routes have not been loaded they will be loaded, and config/routes.php will be run.
  *
  * @param \Cake\Event\Event $event containing the request, response and additional params
  * @return \Cake\Network\Response|null A response will be returned when a redirect route is encountered.
  */
 public function beforeDispatch(Event $event)
 {
     $request = $event->data['request'];
     if (Router::getRequest(true) !== $request) {
         Router::setRequestInfo($request);
     }
     try {
         if (empty($request->params['controller'])) {
             $params = Router::parse($request->url, $request->method());
             $request->addParams($params);
         }
     } catch (RedirectException $e) {
         $event->stopPropagation();
         $response = $event->data['response'];
         $response->statusCode($e->getCode());
         $response->header('Location', $e->getMessage());
         return $response;
     }
 }
Пример #14
0
/**
 * Retrieves current user's information (logged in or not) as an entity object.
 *
 * **Usage:**
 *
 * ```php
 * $user = user();
 * echo user()->name;
 * // prints "Anonymous" if not logged in
 * ```
 * @return \User\Model\Entity\UserSession
 */
function user()
{
    static $user = null;
    if ($user instanceof UserSession) {
        return $user;
    }
    $request = Router::getRequest();
    if ($request && $request->is('userLoggedIn')) {
        $properties = $request->session()->read('Auth.User');
        if (!empty($properties['roles'])) {
            foreach ($properties['roles'] as &$role) {
                unset($role['_joinData']);
                $role = new Entity($role);
            }
        } else {
            $properties['roles'] = [];
        }
        $properties['roles'][] = TableRegistry::get('User.Roles')->get(ROLE_ID_AUTHENTICATED, ['cache' => 'default']);
    } else {
        $properties = ['id' => null, 'name' => __d('user', 'Anonymous'), 'username' => __d('user', 'anonymous'), 'email' => __d('user', '(no email)'), 'locale' => I18n::locale(), 'roles' => [TableRegistry::get('User.Roles')->get(ROLE_ID_ANONYMOUS, ['cache' => 'default'])]];
    }
    $user = new UserSession($properties);
    return $user;
}
Пример #15
0
 /**
  * Dispatches a Request & Response
  *
  * @param \Cake\Network\Request $request The request to dispatch.
  * @param \Cake\Network\Response $response The response to dispatch.
  * @return \Cake\Network\Response a modified/replaced response.
  */
 public function dispatch(Request $request, Response $response)
 {
     if (Router::getRequest(true) !== $request) {
         Router::pushRequest($request);
     }
     $beforeEvent = $this->dispatchEvent('Dispatcher.beforeDispatch', compact('request', 'response'));
     $request = $beforeEvent->data['request'];
     if ($beforeEvent->result instanceof Response) {
         return $beforeEvent->result;
     }
     // Use the controller built by an beforeDispatch
     // event handler if there is one.
     if (isset($beforeEvent->data['controller'])) {
         $controller = $beforeEvent->data['controller'];
     } else {
         $controller = $this->factory->create($request, $response);
     }
     $response = $this->_invoke($controller);
     if (isset($request->params['return'])) {
         return $response;
     }
     $afterEvent = $this->dispatchEvent('Dispatcher.afterDispatch', compact('request', 'response'));
     return $afterEvent->data['response'];
 }
Пример #16
0
 /**
  * test get request.
  *
  * @return void
  */
 public function testGetRequest()
 {
     $requestA = new Request('/');
     $requestB = new Request('/posts');
     Router::pushRequest($requestA);
     Router::pushRequest($requestB);
     $this->assertSame($requestA, Router::getRequest(false));
     $this->assertSame($requestB, Router::getRequest(true));
 }
Пример #17
0
 /**
  * Calls a controller's method from any location. Can be used to connect controllers together
  * or tie plugins into a main application. requestAction can be used to return rendered views
  * or fetch the return value from controller actions.
  *
  * Under the hood this method uses Router::reverse() to convert the $url parameter into a string
  * URL. You should use URL formats that are compatible with Router::reverse()
  *
  * ### Examples
  *
  * A basic example getting the return value of the controller action:
  *
  * ```
  * $variables = $this->requestAction('/articles/popular');
  * ```
  *
  * A basic example of request action to fetch a rendered page without the layout.
  *
  * ```
  * $viewHtml = $this->requestAction('/articles/popular', ['return']);
  * ```
  *
  * You can also pass the URL as an array:
  *
  * ```
  * $vars = $this->requestAction(['controller' => 'articles', 'action' => 'popular']);
  * ```
  *
  * ### Passing other request data
  *
  * You can pass POST, GET, COOKIE and other data into the request using the appropriate keys.
  * Cookies can be passed using the `cookies` key. Get parameters can be set with `query` and post
  * data can be sent using the `post` key.
  *
  * ```
  * $vars = $this->requestAction('/articles/popular', [
  *   'query' => ['page' => 1],
  *   'cookies' => ['remember_me' => 1],
  * ]);
  * ```
  *
  * ### Sending environment or header values
  *
  * By default actions dispatched with this method will use the global $_SERVER and $_ENV
  * values. If you want to override those values for a request action, you can specify the values:
  *
  * ```
  * $vars = $this->requestAction('/articles/popular', [
  *   'environment' => ['CONTENT_TYPE' => 'application/json']
  * ]);
  * ```
  *
  * ### Transmitting the session
  *
  * By default actions dispatched with this method will use the standard session object.
  * If you want a particular session instance to be used, you need to specify it.
  *
  * ```
  * $vars = $this->requestAction('/articles/popular', [
  *   'session' => new Session($someSessionConfig)
  * ]);
  * ```
  *
  * @param string|array $url String or array-based url.  Unlike other url arrays in CakePHP, this
  *    url will not automatically handle passed arguments in the $url parameter.
  * @param array $extra if array includes the key "return" it sets the autoRender to true.  Can
  *    also be used to submit GET/POST data, and passed arguments.
  * @return mixed Boolean true or false on success/failure, or contents
  *    of rendered action if 'return' is set in $extra.
  * @deprecated 3.3.0 You should refactor your code to use View Cells instead of this method.
  */
 public function requestAction($url, array $extra = [])
 {
     if (empty($url)) {
         return false;
     }
     if (($index = array_search('return', $extra)) !== false) {
         $extra['return'] = 0;
         $extra['autoRender'] = 1;
         unset($extra[$index]);
     }
     $extra += ['autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1];
     $baseUrl = Configure::read('App.fullBaseUrl');
     if (is_string($url) && strpos($url, $baseUrl) === 0) {
         $url = Router::normalize(str_replace($baseUrl, '', $url));
     }
     if (is_string($url)) {
         $params = ['url' => $url];
     } elseif (is_array($url)) {
         $defaultParams = ['plugin' => null, 'controller' => null, 'action' => null];
         $params = ['params' => $url + $defaultParams, 'base' => false, 'url' => Router::reverse($url)];
         if (empty($params['params']['pass'])) {
             $params['params']['pass'] = [];
         }
     }
     $current = Router::getRequest();
     if ($current) {
         $params['base'] = $current->base;
         $params['webroot'] = $current->webroot;
     }
     $params['post'] = $params['query'] = [];
     if (isset($extra['post'])) {
         $params['post'] = $extra['post'];
     }
     if (isset($extra['query'])) {
         $params['query'] = $extra['query'];
     }
     if (isset($extra['cookies'])) {
         $params['cookies'] = $extra['cookies'];
     }
     if (isset($extra['environment'])) {
         $params['environment'] = $extra['environment'] + $_SERVER + $_ENV;
     }
     unset($extra['environment'], $extra['post'], $extra['query']);
     $params['session'] = isset($extra['session']) ? $extra['session'] : new Session();
     $request = new Request($params);
     $request->addParams($extra);
     $dispatcher = DispatcherFactory::create();
     // If an application is using PSR7 middleware,
     // we need to 'fix' their missing dispatcher filters.
     $needed = ['routing' => RoutingFilter::class, 'controller' => ControllerFactoryFilter::class];
     foreach ($dispatcher->filters() as $filter) {
         if ($filter instanceof RoutingFilter) {
             unset($needed['routing']);
         }
         if ($filter instanceof ControllerFactoryFilter) {
             unset($needed['controller']);
         }
     }
     foreach ($needed as $class) {
         $dispatcher->addFilter(new $class());
     }
     $result = $dispatcher->dispatch($request, new Response());
     Router::popRequest();
     return $result;
 }
Пример #18
0
 /**
  * Constructor
  *
  * @param \Cake\Network\Request|null $request Request instance.
  * @param \Cake\Network\Response|null $response Response instance.
  * @param \Cake\Event\EventManager|null $eventManager Event manager instance.
  * @param array $viewOptions View options. See View::$_passedVars for list of
  *   options which get set as class properties.
  */
 public function __construct(Request $request = null, Response $response = null, EventManager $eventManager = null, array $viewOptions = [])
 {
     if (isset($viewOptions['view'])) {
         $this->template($viewOptions['view']);
     }
     if (isset($viewOptions['viewPath'])) {
         $this->templatePath($viewOptions['viewPath']);
     }
     foreach ($this->_passedVars as $var) {
         if (isset($viewOptions[$var])) {
             $this->{$var} = $viewOptions[$var];
         }
     }
     $this->eventManager($eventManager);
     $this->request = $request;
     $this->response = $response;
     if (empty($this->request)) {
         $this->request = Router::getRequest(true);
     }
     if (empty($this->request)) {
         $this->request = new Request();
         $this->request->base = '';
         $this->request->here = $this->request->webroot = '/';
     }
     if (empty($this->response)) {
         $this->response = new Response();
     }
     $this->Blocks = new ViewBlock();
     $this->initialize();
     $this->loadHelpers();
 }
Пример #19
0
 /**
  * Gets default context to use.
  *
  * @return \CMS\View\View
  */
 protected static function _getDefaultContext()
 {
     if (!static::$_defaultContext) {
         static::$_defaultContext = new View(Router::getRequest(), null, EventManager::instance(), []);
     }
     return static::$_defaultContext;
 }
Пример #20
0
 /**
  * Checks to see if the given URL can be parsed by this route.
  *
  * If the route can be parsed an array of parameters will be returned; if not
  * false will be returned. String URLs are parsed if they match a routes regular expression.
  *
  * @param string $url The URL to attempt to parse.
  * @return array|false Boolean false on failure, otherwise an array of parameters.
  */
 public function parse($url)
 {
     $request = Router::getRequest(true) ?: Request::createFromGlobals();
     if (empty($this->_compiledRoute)) {
         $this->compile();
     }
     list($url, $ext) = $this->_parseExtension($url);
     if (!preg_match($this->_compiledRoute, urldecode($url), $route)) {
         return false;
     }
     if (isset($this->defaults['_method'])) {
         $method = $request->env('REQUEST_METHOD');
         if (!in_array($method, (array) $this->defaults['_method'], true)) {
             return false;
         }
     }
     array_shift($route);
     $count = count($this->keys);
     for ($i = 0; $i <= $count; $i++) {
         unset($route[$i]);
     }
     $route['pass'] = [];
     // Assign defaults, set passed args to pass
     foreach ($this->defaults as $key => $value) {
         if (isset($route[$key])) {
             continue;
         }
         if (is_int($key)) {
             $route['pass'][] = $value;
             continue;
         }
         $route[$key] = $value;
     }
     if (isset($route['_args_'])) {
         $pass = $this->_parseArgs($route['_args_'], $route);
         $route['pass'] = array_merge($route['pass'], $pass);
         unset($route['_args_']);
     }
     if (isset($route['_trailing_'])) {
         $route['pass'][] = $route['_trailing_'];
         unset($route['_trailing_']);
     }
     if (!empty($ext)) {
         $route['_ext'] = $ext;
     }
     // restructure 'pass' key route params
     if (isset($this->options['pass'])) {
         $j = count($this->options['pass']);
         while ($j--) {
             if (isset($route[$this->options['pass'][$j]])) {
                 array_unshift($route['pass'], $route[$this->options['pass'][$j]]);
             }
         }
     }
     return $route;
 }
Пример #21
0
 /**
  * Get the controller instance to handle the exception.
  * Override this method in subclasses to customize the controller used.
  * This method returns the built in `ErrorController` normally, or if an error is repeated
  * a bare controller will be used.
  *
  * @return \Cake\Controller\Controller
  */
 protected function _getController()
 {
     if (!($request = Router::getRequest(true))) {
         $request = Request::createFromGlobals();
     }
     $response = new Response();
     try {
         $controller = new ErrorController($request, $response);
         $controller->startupProcess();
     } catch (Exception $e) {
         if (!empty($controller) && isset($controller->RequestHandler)) {
             $event = new Event('Controller.startup', $controller);
             $controller->RequestHandler->startup($event);
         }
     }
     if (empty($controller)) {
         $controller = new Controller($request, $response);
         $controller->viewPath = 'Error';
     }
     return $controller;
 }
Пример #22
0
 /**
  * Generates a formatted error message
  *
  * @param \Exception $exception Exception instance
  * @return string Formatted message
  */
 protected function _getMessage(Exception $exception)
 {
     $exception = $exception instanceof PHP7ErrorException ? $exception->getError() : $exception;
     $config = $this->_options;
     $message = sprintf("[%s] %s", get_class($exception), $exception->getMessage());
     $debug = Configure::read('debug');
     if ($debug && method_exists($exception, 'getAttributes')) {
         $attributes = $exception->getAttributes();
         if ($attributes) {
             $message .= "\nException Attributes: " . var_export($exception->getAttributes(), true);
         }
     }
     if (PHP_SAPI !== 'cli') {
         $request = Router::getRequest();
         if ($request) {
             $message .= "\nRequest URL: " . $request->here();
         }
     }
     if (!empty($config['trace'])) {
         $message .= "\nStack Trace:\n" . $exception->getTraceAsString() . "\n\n";
     }
     return $message;
 }
Пример #23
0
 /**
  * Calls a controller's method from any location. Can be used to connect controllers together
  * or tie plugins into a main application. requestAction can be used to return rendered views
  * or fetch the return value from controller actions.
  *
  * Under the hood this method uses Router::reverse() to convert the $url parameter into a string
  * URL. You should use URL formats that are compatible with Router::reverse()
  *
  * ### Examples
  *
  * A basic example getting the return value of the controller action:
  *
  * ```
  * $variables = $this->requestAction('/articles/popular');
  * ```
  *
  * A basic example of request action to fetch a rendered page without the layout.
  *
  * ```
  * $viewHtml = $this->requestAction('/articles/popular', ['return']);
  * ```
  *
  * You can also pass the URL as an array:
  *
  * ```
  * $vars = $this->requestAction(['controller' => 'articles', 'action' => 'popular']);
  * ```
  *
  * ### Passing other request data
  *
  * You can pass POST, GET, COOKIE and other data into the request using the appropriate keys.
  * Cookies can be passed using the `cookies` key. Get parameters can be set with `query` and post
  * data can be sent using the `post` key.
  *
  * ```
  * $vars = $this->requestAction('/articles/popular', [
  *   'query' => ['page' => 1],
  *   'cookies' => ['remember_me' => 1],
  * ]);
  * ```
  *
  * ### Sending environment or header values
  *
  * By default actions dispatched with this method will use the global $_SERVER and $_ENV
  * values. If you want to override those values for a request action, you can specify the values:
  *
  * ```
  * $vars = $this->requestAction('/articles/popular', [
  *   'environment' => ['CONTENT_TYPE' => 'application/json']
  * ]);
  * ```
  *
  * ### Transmitting the session
  *
  * By default actions dispatched with this method will use the standard session object.
  * If you want a particular session instance to be used, you need to specify it.
  *
  * ```
  * $vars = $this->requestAction('/articles/popular', [
  *   'session' => new Session($someSessionConfig)
  * ]);
  * ```
  *
  * @param string|array $url String or array-based url.  Unlike other url arrays in CakePHP, this
  *    url will not automatically handle passed arguments in the $url parameter.
  * @param array $extra if array includes the key "return" it sets the autoRender to true.  Can
  *    also be used to submit GET/POST data, and passed arguments.
  * @return mixed Boolean true or false on success/failure, or contents
  *    of rendered action if 'return' is set in $extra.
  */
 public function requestAction($url, array $extra = [])
 {
     if (empty($url)) {
         return false;
     }
     if (($index = array_search('return', $extra)) !== false) {
         $extra['return'] = 0;
         $extra['autoRender'] = 1;
         unset($extra[$index]);
     }
     $extra += ['autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1];
     $baseUrl = Configure::read('App.fullBaseUrl');
     if (is_string($url) && strpos($url, $baseUrl) === 0) {
         $url = Router::normalize(str_replace($baseUrl, '', $url));
     }
     if (is_string($url)) {
         $params = ['url' => $url];
     } elseif (is_array($url)) {
         $defaultParams = ['plugin' => null, 'controller' => null, 'action' => null];
         $params = ['params' => $url + $defaultParams, 'base' => false, 'url' => Router::reverse($url)];
         if (empty($params['params']['pass'])) {
             $params['params']['pass'] = [];
         }
     }
     $current = Router::getRequest();
     if ($current) {
         $params['base'] = $current->base;
         $params['webroot'] = $current->webroot;
     }
     $params['post'] = $params['query'] = [];
     if (isset($extra['post'])) {
         $params['post'] = $extra['post'];
     }
     if (isset($extra['query'])) {
         $params['query'] = $extra['query'];
     }
     if (isset($extra['cookies'])) {
         $params['cookies'] = $extra['cookies'];
     }
     if (isset($extra['environment'])) {
         $params['environment'] = $extra['environment'] + $_SERVER + $_ENV;
     }
     unset($extra['environment'], $extra['post'], $extra['query']);
     $params['session'] = isset($extra['session']) ? $extra['session'] : new Session();
     $request = new Request($params);
     $request->addParams($extra);
     $dispatcher = DispatcherFactory::create();
     $result = $dispatcher->dispatch($request, new Response());
     Router::popRequest();
     return $result;
 }
Пример #24
0
 /**
  * [beforeFind description]
  *
  * @param  Event $event [description]
  * @param  Query $query [description]
  * @param array  $options
  *
  * @return $this|array|Query [type]          [description]
  *
  * ### Options
  * `images` When setting images to false nothing will be added to the query and no image fields will be returned in the resultset and will probably
  * speed up overall performance
  */
 public function beforeFind(Event $event, Query $query, $options = [])
 {
     if (isset($options['images']) && !$options['images']) {
         return $query;
     }
     $fields = $this->config('fields');
     $contain = $conditions = [];
     foreach ($fields as $field => $type) {
         $field = $this->_fieldName($field);
         $contain[$field] = $conditions;
     }
     /**
      * @param $row
      * @param $key
      * @param $mapReduce MapReduce
      */
     $mapper = function ($row, $key, $mapReduce) use($fields) {
         foreach ($fields as $field => $type) {
             $name = $this->_fieldName($field, false);
             $image = isset($row[$name]) ? $row[$name] : null;
             // make sure we set the correct registry alias for the entity so
             // we can access the entity's repository from the ImageHelper
             if (!empty($image)) {
                 if (is_array($image)) {
                     foreach ($image as &$imageEntity) {
                         $this->_setEntitySource($imageEntity);
                     }
                 } else {
                     $this->_setEntitySource($image);
                 }
             }
             if ($image === null) {
                 unset($row[$name]);
                 continue;
             }
             $row[$field] = $image;
             unset($row[$name]);
         }
         if ($row instanceof Entity) {
             $row->clean();
         }
         $mapReduce->emitIntermediate($row, $key);
     };
     /**
      * @param $items
      * @param $key
      * @param $mapReduce MapReduce
      */
     $reducer = function ($items, $key, $mapReduce) {
         if (isset($items[0])) {
             $mapReduce->emit($items[0], $key);
         }
     };
     $request = Router::getRequest();
     if (!isset($request->params['prefix']) || $request->params['prefix'] !== 'admin') {
         //TODO zuniverzálnit
         foreach ($contain as $key => &$item) {
             $item['conditions'] = [$key . '.active' => true];
         }
     }
     $q = $query->contain($contain)->mapReduce($mapper, $reducer);
     return $q;
 }
 /**
  * Test that exceptions can be rendered when a request hasn't been registered
  * with Router
  *
  * @return void
  */
 public function testRenderWithNoRequest()
 {
     Router::reload();
     $this->assertNull(Router::getRequest(false));
     $exception = new Exception('Terrible');
     $ExceptionRenderer = new ExceptionRenderer($exception);
     $result = $ExceptionRenderer->render();
     $this->assertContains('Internal Error', $result->body());
     $this->assertEquals(500, $result->statusCode());
 }
Пример #26
0
 /**
  * Get the controller instance to handle the exception.
  * Override this method in subclasses to customize the controller used.
  * This method returns the built in `ErrorController` normally, or if an error is repeated
  * a bare controller will be used.
  *
  * @return \Cake\Controller\Controller
  * @triggers Controller.startup $controller
  */
 protected function _getController()
 {
     if (!($request = Router::getRequest(true))) {
         $request = Request::createFromGlobals();
     }
     $response = new Response();
     try {
         $class = App::className('Error', 'Controller', 'Controller');
         $controller = new $class($request, $response);
         $controller->startupProcess();
         $startup = true;
     } catch (Exception $e) {
         $startup = false;
     }
     // Retry RequestHandler, as another aspect of startupProcess()
     // could have failed. Ignore any exceptions out of startup, as
     // there could be userland input data parsers.
     if ($startup === false && !empty($controller) && isset($controller->RequestHandler)) {
         try {
             $event = new Event('Controller.startup', $controller);
             $controller->RequestHandler->startup($event);
         } catch (Exception $e) {
         }
     }
     if (empty($controller)) {
         $controller = new Controller($request, $response);
     }
     return $controller;
 }
Пример #27
0
 /**
  * Generates a formatted error message
  *
  * @param \Exception $exception Exception instance
  * @return string Formatted message
  */
 protected function _getMessage(\Exception $exception)
 {
     $message = sprintf("[%s] %s", get_class($exception), $exception->getMessage());
     if (method_exists($exception, 'getAttributes')) {
         $attributes = $exception->getAttributes();
         if ($attributes) {
             $message .= "\nException Attributes: " . var_export($exception->getAttributes(), true);
         }
     }
     if (php_sapi_name() !== 'cli') {
         $request = Router::getRequest();
         if ($request) {
             $message .= "\nRequest URL: " . $request->here();
         }
     }
     $message .= "\nStack Trace:\n" . $exception->getTraceAsString() . "\n\n";
     return $message;
 }
Пример #28
0
 /**
  * Checks to see if the given URL can be parsed by this route.
  *
  * If the route can be parsed an array of parameters will be returned; if not
  * false will be returned. String URLs are parsed if they match a routes regular expression.
  *
  * @param string $url The URL to attempt to parse.
  * @return mixed Boolean false on failure, otherwise an array or parameters
  */
 public function parse($url)
 {
     $request = Router::getRequest(true) ?: Request::createFromGlobals();
     if (!$this->compiled()) {
         $this->compile();
     }
     list($url, $ext) = $this->_parseExtension($url);
     if (!preg_match($this->_compiledRoute, urldecode($url), $route)) {
         return false;
     }
     foreach ($this->defaults as $key => $val) {
         $key = (string) $key;
         if ($key[0] === '[' && preg_match('/^\\[(\\w+)\\]$/', $key, $header)) {
             if (isset($this->_headerMap[$header[1]])) {
                 $header = $this->_headerMap[$header[1]];
             } else {
                 $header = 'http_' . $header[1];
             }
             $header = strtoupper($header);
             $val = (array) $val;
             $h = false;
             foreach ($val as $v) {
                 if ($request->env($header) === $v) {
                     $h = true;
                 }
             }
             if (!$h) {
                 return false;
             }
         }
     }
     array_shift($route);
     $count = count($this->keys);
     for ($i = 0; $i <= $count; $i++) {
         unset($route[$i]);
     }
     $route['pass'] = [];
     // Assign defaults, set passed args to pass
     foreach ($this->defaults as $key => $value) {
         if (isset($route[$key])) {
             continue;
         }
         if (is_int($key)) {
             $route['pass'][] = $value;
             continue;
         }
         $route[$key] = $value;
     }
     if (isset($route['_args_'])) {
         $pass = $this->_parseArgs($route['_args_'], $route);
         $route['pass'] = array_merge($route['pass'], $pass);
         unset($route['_args_']);
     }
     if (isset($route['_trailing_'])) {
         $route['pass'][] = $route['_trailing_'];
         unset($route['_trailing_']);
     }
     if (!empty($ext)) {
         $route['_ext'] = $ext;
     }
     // restructure 'pass' key route params
     if (isset($this->options['pass'])) {
         $j = count($this->options['pass']);
         while ($j--) {
             if (isset($route[$this->options['pass'][$j]])) {
                 array_unshift($route['pass'], $route[$this->options['pass'][$j]]);
             }
         }
     }
     return $route;
 }
Пример #29
0
 /**
  * Normalizes an URL for purposes of comparison.
  *
  * Will strip the base path off and replace any double /'s.
  * It will not unify the casing and underscoring of the input value.
  *
  * @param array|string $url URL to normalize Either an array or a string URL.
  * @return string Normalized URL
  */
 public static function normalize($url = '/')
 {
     if (is_array($url)) {
         $url = Router::url($url);
     }
     if (preg_match('/^[a-z\\-]+:\\/\\//', $url)) {
         return $url;
     }
     $request = Router::getRequest();
     if (!empty($request->base) && stristr($url, $request->base)) {
         $url = preg_replace('/^' . preg_quote($request->base, '/') . '/', '', $url, 1);
     }
     $url = '/' . $url;
     while (strpos($url, '//') !== false) {
         $url = str_replace('//', '/', $url);
     }
     $url = preg_replace('/(?:(\\/$))/', '', $url);
     if (empty($url)) {
         return '/';
     }
     return $url;
 }
Пример #30
0
 * `:action` markers.
 *
 */
Router::defaultRouteClass('Route');
Router::addUrlFilter(function ($params, $request) {
    if (isset($request->params['lang']) && !isset($params['lang'])) {
        $params['lang'] = $request->params['lang'];
    } elseif (!isset($params['lang'])) {
        $params['lang'] = Router::getRequest()->session()->read('lang');
        // set your default language here
    }
    return $params;
});
$lang = 'en';
if (Router::getRequest()->session()->check('Config.language')) {
    $lang = Router::getRequest()->session()->read('Config.language');
}
Router::redirect('/', "/{$lang}/");
Router::connect('/:lang/', ['controller' => 'Home', 'action' => 'index']);
Router::connect('/:lang/:controller', ['action' => 'index']);
Router::connect('/:lang/:controller/about', ['action' => 'about']);
Router::connect('/:lang/:controller/search', ['action' => 'search']);
Router::connect('/:lang/:controller/profile', ['action' => 'profile']);
Router::connect('/:lang/:controller/settings', ['action' => 'settings']);
Router::connect('/:lang/:controller/add', ['action' => 'add']);
Router::connect('/:lang/:controller/view/:id', ['action' => 'view'], ['id' => '\\d+', 'pass' => ['id']]);
Router::connect('/:lang/:controller/edit/:id', ['action' => 'edit'], ['id' => '\\d+', 'pass' => ['id']]);
Router::connect('/:lang/:controller/delete/:id', ['action' => 'delete'], ['id' => '\\d+', 'pass' => ['id']]);
Router::connect('/:lang/:controller/roledata_list/:id', ['action' => 'roledata_list'], ['id' => '\\d+', 'pass' => ['id']]);
Router::connect('/:lang/:controller/login', ['action' => 'login']);
Router::connect('/:lang/:controller/logout', ['action' => 'logout']);