getRequest() public static method

Gets the current request object, or the first one.
public static getRequest ( boolean $current = false ) : CakeRequest | null
$current boolean True to get the current request object, or false to get the first one.
return CakeRequest | null Null if stack is empty.
 public function check_if_valid($controller)
 {
     //First we will ensure there is a token in the request
     $request = Router::getRequest();
     $token = false;
     if (isset($request->data['token'])) {
         $token = $request->data['token'];
     } elseif (isset($request->query['token'])) {
         $token = $request->query['token'];
     }
     if ($token != false) {
         if (strlen($token) != 36) {
             $result = array('success' => false, 'message' => array('message' => __('Token in wrong format')));
         } else {
             //Find the owner of the token
             $result = $this->find_token_owner($token);
         }
     } else {
         $result = array('success' => false, 'message' => array('message' => __('Token missing')));
     }
     //If it failed - set the controller up
     if ($result['success'] == false) {
         $controller->set(array('success' => $result['success'], 'message' => $result['message'], '_serialize' => array('success', 'message')));
         return false;
     } else {
         return $result['user'];
         //Return the user detail
     }
 }
Example #2
0
 /**
  * 指定されたURLに対応しRouterパース済のCakeRequestのインスタンスを返す
  *
  * @param string $url URL
  * @return CakeRequest
  */
 protected function _getRequest($url)
 {
     Router::$initialized = false;
     Router::reload();
     $request = new CakeRequest($url);
     // コンソールからのテストの場合、requestのパラメーターが想定外のものとなってしまうので調整
     if (isConsole()) {
         $baseUrl = Configure::read('App.baseUrl');
         if ($request->url === false) {
             $request->here = $baseUrl . '/';
         } elseif (preg_match('/^' . preg_quote($request->webroot, '/') . '/', $request->here)) {
             $request->here = $baseUrl . '/' . preg_replace('/^' . preg_quote($request->webroot, '/') . '/', '', $request->here);
         }
         if ($baseUrl) {
             if (preg_match('/^\\//', $baseUrl)) {
                 $request->base = $baseUrl;
             } else {
                 $request->base = '/' . $baseUrl;
             }
             $request->webroot = $baseUrl;
         } else {
             $request->base = '';
             $request->webroot = '/';
         }
     }
     Router::setRequestInfo($request);
     $params = Router::parse($request->url);
     unset($params['?']);
     $request = Router::getRequest(true);
     $request->addParams($params);
     return $request;
 }
Example #3
0
 /**
  * @author thientd
  */
 private function __getLoginName()
 {
     // in batch section.
     if (php_sapi_name() == 'cli') {
         return Configure::read('CONSOLE_MODIFIER_NAME');
     }
     $user = AuthComponent::user();
     // web, register section
     if (!$user) {
         return 'Register';
     }
     // web, login section
     $loginName = '';
     $request = Router::getRequest();
     if (isset($request->params['admin'])) {
         $loginName = Configure::read('ADMIN_MODIFIER_NAME');
     } elseif (isset($request->params['advisor'])) {
         if (isset($user['AdvisorProfile']['fullname'])) {
             $loginName = $user['AdvisorProfile']['fullname'];
         }
     } else {
         if (isset($user['UserProfile']['fullname'])) {
             $loginName = $user['UserProfile']['fullname'];
         }
     }
     if (mb_strlen($loginName) > 50) {
         $loginName = mb_substr($loginName, 0, 50);
     }
     return $loginName;
 }
 /**
  * Overriding _getController to use MPResponse instead of default one
  *
  * @see ExceptionRenderer::_getController
  * @param Exception $exception
  * @return CakeErrorController|Controller
  */
 protected function _getController($exception)
 {
     App::uses('AppController', 'Controller');
     App::uses('CakeErrorController', 'Controller');
     if (!($request = Router::getRequest(true))) {
         $request = new CakeRequest();
     }
     $response = new MPResponse();
     if (method_exists($exception, 'responseHeader')) {
         $response->header($exception->responseHeader());
     }
     if (class_exists('AppController')) {
         try {
             $controller = new CakeErrorController($request, $response);
             $controller->startupProcess();
         } catch (Exception $e) {
             if (!empty($controller) && $controller->Components->enabled('RequestHandler')) {
                 $controller->RequestHandler->startup($controller);
             }
         }
     }
     if (empty($controller)) {
         $controller = new Controller($request, $response);
         $controller->viewPath = 'Errors';
     }
     return $controller;
 }
Example #5
0
 public static 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>', trim($trace), '</pre>', '', '<h2>', 'Request:', '</h2>', '', '<h3>URL</h3>', self::getUrl(), '<h3>Client IP</h3>', self::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("\n", $msg);
 }
 /**
  * __construct
  *
  * @access public
  * @return void
  */
 function __construct()
 {
     parent::__construct();
     $this->_set(Router::getPaths());
     $this->request = Router::getRequest(false);
     $this->constructClasses();
     $this->Components->trigger('initialize', array(&$this));
     $this->_set(array('cacheAction' => false, 'viewPath' => 'errors'));
 }
 /**
  * Get a custom InfinitasErrorController instance
  * 
  * This instance tries to load up the very minimum to display the error
  * page. If anything goes wrong it falls back to the default CakeErrorController
  *
  * @param Exception $exception The exception to get a controller for.
  * 
  * @return Controller
  */
 protected function _getController($exception)
 {
     App::uses('InfinitasErrorController', 'Controller');
     if (!($request = Router::getRequest(true))) {
         $request = new CakeRequest();
     }
     $response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
     try {
         return new InfinitasErrorController($request, $response);
     } catch (Exception $e) {
         return parent::_getController($exception);
     }
 }
Example #8
0
 /**
  * 管理システムかチェック
  * 
  * 《注意》by ryuring
  * 処理の内容にCakeRequest や、Router::parse() を使おうとしたが、
  * Router::parse() を利用すると、Routing情報が書き換えられてしまうので利用できない。
  * Router::reload() や、Router::setRequestInfo() で調整しようとしたがうまくいかなかった。
  * 
  * @return boolean
  */
 public static function isAdminSystem($url = null)
 {
     if (!$url) {
         $request = Router::getRequest(true);
         if ($request) {
             $url = $request->url;
         } else {
             return false;
         }
     }
     $adminPrefix = Configure::read('Routing.prefixes.0');
     return (bool) (preg_match('/^(|\\/)' . $adminPrefix . '\\//', $url) || preg_match('/^(|\\/)' . $adminPrefix . '$/', $url));
 }
Example #9
0
 public function __construct($id = false, $table = null, $ds = null)
 {
     // Auto set recursive to -1
     $this->recursive = -1;
     // Auto attach containable behaviour
     $this->actsAs[] = 'Containable';
     // Fetch language
     $this->language = Configure::read('Config.language');
     // Never use NOW() in MySQL queries, since it depends on the MySQL server timezone
     $this->MysqlNow = date("Y-m-d H:i:s");
     // Set db already slugged models and fields to avoid recursive slug to get in there
     $this->dbSlugged = array();
     $this->request = Router::getRequest();
     $this->isAdmin = isset($this->request->params['admin']);
     parent::__construct($id, $table, $ds);
     // Remove all relationship conditions if in admin mode
     if ($this->isAdmin) {
         foreach ($this->belongsTo as &$belongsTo) {
             $belongsTo['conditions'] = array();
         }
         foreach ($this->hasOne as &$hasOne) {
             $hasOne['conditions'] = array();
         }
         foreach ($this->hasMany as &$hasMany) {
             $hasMany['conditions'] = array();
         }
         foreach ($this->hasAndBelongsToMany as &$hasAndBelongsToMany) {
             $hasAndBelongsToMany['conditions'] = array();
         }
     } else {
         // Automatically add slug field to model with name fields and no slug field
         if (!in_array($this->alias, $this->dbSlugged)) {
             if ($this->hasField('name_fr') && $this->hasField('name_en')) {
                 $this->virtualFields['slug'] = sprintf('%s.name_%s', $this->alias, $this->language);
                 // Add localized name field
                 if (!$this->hasField('name')) {
                     $this->virtualFields['name'] = sprintf('%s.name_%s', $this->alias, $this->language);
                 }
             }
             // Title fields
             if ($this->hasField('title')) {
                 $this->virtualFields['slug'] = sprintf('%s.title', $this->alias);
             }
         }
     }
     // Global use of number helper
     App::uses('CakeNumber', 'Utility');
 }
Example #10
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 `CakeErrorController` normally, or if an error is repeated
  * a bare controller will be used.
  *
  * @param Exception $exception The exception to get a controller for.
  * @return Controller
  */
 protected function _getController($exception)
 {
     if (!($request = Router::getRequest(true))) {
         $request = new CakeRequest();
     }
     // If outside of plugin, use default handling
     if ($request->params['plugin'] !== 'forum') {
         return parent::_getController($exception);
     }
     $response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
     $controller = new ForumAppController($request, $response);
     $controller->viewPath = 'Errors';
     $controller->constructClasses();
     $controller->startupProcess();
     return $controller;
 }
 protected function _getController($exception)
 {
     App::uses('TestAppsErrorController', 'Controller');
     if (!($request = Router::getRequest(true))) {
         $request = new CakeRequest();
     }
     $response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
     try {
         $controller = new TestAppsErrorController($request, $response);
         $controller->layout = 'banana';
     } catch (Exception $e) {
         $controller = new Controller($request, $response);
         $controller->viewPath = 'Errors';
     }
     return $controller;
 }
 protected function _getController($exception)
 {
     App::uses('TestAppsErrorController', 'Controller');
     if (!($request = Router::getRequest(TRUE))) {
         $request = new CakeRequest();
     }
     $response = new CakeResponse();
     try {
         $controller = new TestAppsErrorController($request, $response);
         $controller->layout = 'banana';
     } catch (Exception $e) {
         $controller = new Controller($request, $response);
         $controller->viewPath = 'Errors';
     }
     return $controller;
 }
Example #13
0
 protected function _getController($exception)
 {
     if (Configure::read('debug') > 0) {
         if (get_class($exception) == 'MissingTableException') {
             // had to put this in because debugger would fix the error and you'd never see it
             debug($exception->getMessage());
         } elseif (get_class($exception) == 'PDOException') {
             // had to put this in because debugger would fix the error and you'd never see it
             debug($exception->getMessage());
         }
     }
     App::uses('AppErrorController', 'Controller');
     if (!($request = Router::getRequest(false))) {
         $request = new CakeRequest();
     }
     $response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
     $Controller = new AppErrorController($request, $response);
     //Needed to add this check to allow errors from testing to be displayed WHY DIDN'T WE COMMENT THE REMOVAL OF IT THEN!!!
     //if(!defined('APP_TEST_CASES')) {
     if (get_class($exception) == 'MissingPluginException') {
         try {
             $Controller->handleMissingPlugin($request, $exception);
         } catch (Exception $e) {
             debug($e->getMessage());
             exit;
         }
     } else {
         try {
             $Controller->handleAlias($request, $exception);
             // checks for alias match
         } catch (Exception $e) {
             try {
                 $Controller->handleNotFound($request, $response, $e, $exception);
             } catch (Exception $e) {
                 $Controller = new Controller($request, $response);
                 $Controller->viewPath = 'Errors';
             }
         }
     }
     //}
     return $Controller;
 }
Example #14
0
 /**
  * Check wither the routing table has a specific route
  * @param Router $router
  * @return bool
  */
 public function has(Router $router)
 {
     $found = false;
     foreach ($this->_routingTable as $routeID => $routeDetails) {
         if (preg_match("/^" . str_replace('/', '\\/', $routeDetails['_url_']) . "\$/i", $router->getFinalRequestedId()) && in_array($router->getRequest()->getMethod(), $this->_routingTable[$routeID]['_method_'])) {
             $found = true;
             break;
         }
     }
     $router->setController($this->_routingTable[$routeID]['_controller_']);
     $router->setAction($this->_routingTable[$routeID]['_action_']);
     if (!empty($router->getParams())) {
         $index = 0;
         $parameters = array();
         $routerFetchedParameters = $router->getParams();
         foreach ($this->_routingTable[$routeID]['_params_'] as $parameter) {
             $parameters[$parameter] = $routerFetchedParameters[$index++];
         }
         $router->setParams($parameters);
     }
     return $found;
 }
Example #15
0
 public function beforeFind($queryData)
 {
     if (isset(Router::getRequest()->query['Search'])) {
         $search = Router::getRequest()->query['Search'];
         if (isset($search['Table']) && $search['Table'] == $this->alias) {
             unset($search['Table']);
             foreach ($search as $key => $val_parent) {
                 foreach ($val_parent as $key_child => $val) {
                     if (is_array($val) && !empty($val)) {
                         if (isset($val['from']) && $val['from'] != '') {
                             $queryData['conditions'][$key . '.' . $key_child . '  >=  '] = $val['from'];
                         }
                         if (isset($val['from_date']) && $val['from_date'] != '') {
                             $queryData['conditions'][$key . '.' . $key_child . '  >=  '] = sqlFormatDate($val['from_date']);
                         }
                         if (isset($val['to']) && $val['to'] != '') {
                             $queryData['conditions'][$key . '.' . $key_child . '  <=  '] = $val['to'];
                         }
                         if (isset($val['to_date']) && $val['to_date'] != '') {
                             $queryData['conditions'][$key . '.' . $key_child . '  <=  '] = sqlFormatDate($val['to_date']);
                         }
                     } else {
                         if ($val != '') {
                             if ($key_child == 'id') {
                                 $queryData['conditions'][$key . '.' . $key_child . ' = '] = $val;
                             } else {
                                 $queryData['conditions'][$key . '.' . $key_child . ' LIKE '] = '%' . $val . '%';
                             }
                         }
                     }
                 }
             }
             //print_r($queryData);die;
             return $queryData;
         }
     }
 }
Example #16
0
 /**
  * Normalizes a 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;
 }
 /**
  * testRequestAction method
  *
  * @return void
  */
 public function testRequestAction()
 {
     App::build(array('Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS), 'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS), 'Controller' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS)), App::RESET);
     $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(FULL_BASE_URL . '/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->assertTrue($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');
 }
Example #18
0
 /**
  * Lets you do functional tests of a controller action.
  *
  * ### Options:
  *
  * - `data` Will be used as the request data. If the `method` is GET,
  *   data will be used a GET params. If the `method` is POST, it will be used
  *   as POST data. By setting `$options['data']` to a string, you can simulate XML or JSON
  *   payloads to your controllers allowing you to test REST webservices.
  * - `method` POST or GET. Defaults to POST.
  * - `return` Specify the return type you want. Choose from:
  *     - `vars` Get the set view variables.
  *     - `view` Get the rendered view, without a layout.
  *     - `contents` Get the rendered view including the layout.
  *     - `result` Get the return value of the controller action. Useful
  *       for testing requestAction methods.
  *
  * @param string|array $url The URL to test.
  * @param array $options See options
  * @return mixed The specified return type.
  * @triggers ControllerTestCase $Dispatch, array('request' => $request)
  */
 protected function _testAction($url, $options = array())
 {
     $this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
     $options += array('data' => array(), 'method' => 'POST', 'return' => 'result');
     if (is_array($url)) {
         $url = Router::url($url);
     }
     $restore = array('get' => $_GET, 'post' => $_POST);
     $_SERVER['REQUEST_METHOD'] = strtoupper($options['method']);
     if (is_array($options['data'])) {
         if (strtoupper($options['method']) === 'GET') {
             $_GET = $options['data'];
             $_POST = array();
         } else {
             $_POST = $options['data'];
             $_GET = array();
         }
     }
     $request = $this->getMock('CakeRequest', array('_readInput'), array($url));
     if (is_string($options['data'])) {
         $request->expects($this->any())->method('_readInput')->will($this->returnValue($options['data']));
     }
     $Dispatch = new ControllerTestDispatcher();
     foreach (Router::$routes as $route) {
         if ($route instanceof RedirectRoute) {
             $route->response = $this->getMock('CakeResponse', array('send'));
         }
     }
     $Dispatch->loadRoutes = $this->loadRoutes;
     $Dispatch->parseParams(new CakeEvent('ControllerTestCase', $Dispatch, array('request' => $request)));
     if (!isset($request->params['controller']) && Router::currentRoute()) {
         $this->headers = Router::currentRoute()->response->header();
         return null;
     }
     if ($this->_dirtyController) {
         $this->controller = null;
     }
     $plugin = empty($request->params['plugin']) ? '' : Inflector::camelize($request->params['plugin']) . '.';
     if ($this->controller === null && $this->autoMock) {
         $this->generate($plugin . Inflector::camelize($request->params['controller']));
     }
     $params = array();
     if ($options['return'] === 'result') {
         $params['return'] = 1;
         $params['bare'] = 1;
         $params['requested'] = 1;
     }
     $Dispatch->testController = $this->controller;
     $Dispatch->response = $this->getMock($this->_responseClass, array('send', '_clearBuffer'));
     $this->result = $Dispatch->dispatch($request, $Dispatch->response, $params);
     // Clear out any stored requests.
     while (Router::getRequest()) {
         Router::popRequest();
     }
     $this->controller = $Dispatch->testController;
     $this->vars = $this->controller->viewVars;
     $this->contents = $this->controller->response->body();
     if (isset($this->controller->View)) {
         $this->view = $this->controller->View->fetch('__view_no_layout__');
     }
     $this->_dirtyController = true;
     $this->headers = $Dispatch->response->header();
     $_GET = $restore['get'];
     $_POST = $restore['post'];
     return $this->{$options['return']};
 }
 /**
  * Get the controller instance to handle the exception.
  * Override this method in subclasses to customize the controller used.
  * This method returns the built in `CakeErrorController` normally, or if an error is repeated
  * a bare controller will be used.
  *
  * @param Exception $exception The exception to get a controller for.
  * @return Controller
  */
 protected function _getController($exception)
 {
     App::uses('CakeErrorController', 'Controller');
     if (!($request = Router::getRequest(true))) {
         $request = new CakeRequest();
     }
     $response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
     try {
         if (class_exists('AppController')) {
             $controller = new CakeErrorController($request, $response);
         }
     } catch (Exception $e) {
     }
     if (empty($controller)) {
         $controller = new Controller($request, $response);
         $controller->viewPath = 'Errors';
     }
     return $controller;
 }
Example #20
0
 /**
  * Build and set all the view properties needed to render the templated emails.
  * If there is no template set, the $content will be returned in a hash
  * of the text content types for the email.
  *
  * @param string $content The content passed in from send() in most cases.
  * @return array The rendered content with html and text keys.
  */
 protected function _renderTemplates($content)
 {
     $types = $this->_getTypes();
     $rendered = array();
     if (empty($this->_template)) {
         foreach ($types as $type) {
             $rendered[$type] = $this->_encodeString($content, $this->charset);
         }
         return $rendered;
     }
     $viewClass = $this->_viewRender;
     if ($viewClass !== 'View') {
         list($plugin, $viewClass) = pluginSplit($viewClass, true);
         $viewClass .= 'View';
         App::uses($viewClass, $plugin . 'View');
     }
     $View = new $viewClass(null);
     $View->viewVars = $this->_viewVars;
     $View->helpers = $this->_helpers;
     if (!($request = Router::getRequest(true))) {
         $request = new CakeRequest('/', false);
         $request->base = '';
         $request->here = $request->webroot = '/';
     }
     $View->request = $request;
     list($templatePlugin, $template) = pluginSplit($this->_template);
     list($layoutPlugin, $layout) = pluginSplit($this->_layout);
     if ($templatePlugin) {
         $View->plugin = $templatePlugin;
     } elseif ($layoutPlugin) {
         $View->plugin = $layoutPlugin;
     }
     foreach ($types as $type) {
         $View->set('content', $content);
         $View->hasRendered = false;
         $View->viewPath = $View->layoutPath = 'Emails' . DS . $type;
         $render = $View->render($template, $layout);
         $render = str_replace(array("\r\n", "\r"), "\n", $render);
         $rendered[$type] = $this->_encodeString($render, $this->charset);
     }
     return $rendered;
 }
Example #21
0
 /**
  * Reverse route
  *
  * @param array $url Array of parameters to convert to a string.
  * @return mixed either false or a string URL.
  */
 public function match($url)
 {
     // フロント以外のURLの場合にマッチしない
     if (!empty($url['admin'])) {
         return false;
     }
     // プラグイン確定
     if (empty($url['plugin'])) {
         $plugin = 'Core';
     } else {
         $plugin = Inflector::camelize($url['plugin']);
     }
     // アクション確定
     if (!empty($url['action'])) {
         $action = $url['action'];
     } else {
         $action = 'index';
     }
     $params = $url;
     unset($params['plugin']);
     unset($params['controller']);
     unset($params['action']);
     unset($params['entityId']);
     // コンテンツタイプ確定、できなければスルー
     $type = $this->_getContentTypeByParams($url);
     if ($type) {
         unset($params['action']);
     } else {
         $type = $this->_getContentTypeByParams($url, false);
     }
     if (!$type) {
         return false;
     }
     // エンティティID確定
     $entityId = $contentId = null;
     if (isset($url['entityId'])) {
         $entityId = $url['entityId'];
     } else {
         $request = Router::getRequest(true);
         if (!empty($request->params['entityId'])) {
             $entityId = $request->params['entityId'];
         }
         if (!empty($request->params['Content']['alias_id'])) {
             $contentId = $request->params['Content']['id'];
         }
     }
     // コンテンツ確定、できなければスルー
     if ($type == 'Page') {
         $pass = [];
         foreach ($params as $key => $param) {
             if (!is_string($key)) {
                 $pass[] = $param;
                 unset($params[$key]);
             }
         }
         $strUrl = '/' . implode('/', $pass);
     } else {
         $Content = ClassRegistry::init('Content');
         if ($contentId) {
             $conditions = ['Content.id' => $contentId];
         } else {
             $conditions = ['Content.plugin' => $plugin, 'Content.type' => $type, 'Content.entity_id' => $entityId];
         }
         $strUrl = $Content->field('url', $conditions);
     }
     if (!$strUrl) {
         return false;
     }
     // URL生成
     $site = BcSite::findByUrl($strUrl);
     if ($site && $site->useSubDomain) {
         $strUrl = preg_replace('/^\\/' . preg_quote($site->alias, '/') . '\\//', '/', $strUrl);
     }
     $pass = [];
     $named = [];
     $setting = Configure::read('BcContents.items.' . $plugin . '.' . $type);
     if (!$params) {
         if (empty($setting['omitViewAction']) && $setting['routes']['view']['action'] != $action) {
             $strUrl .= '/' . $action;
         }
     } else {
         if (empty($setting['omitViewAction'])) {
             $strUrl .= '/' . $action;
         }
         foreach ($params as $key => $param) {
             if (!is_numeric($key)) {
                 if ($key == 'page' && !$param) {
                     $param = 1;
                 }
                 if (!is_array($param)) {
                     $named[] = $key . ':' . $param;
                 }
             } else {
                 $pass[] = $param;
             }
         }
     }
     if ($pass) {
         $strUrl .= '/' . implode('/', $pass);
     }
     if ($named) {
         $strUrl .= '/' . implode('/', $named);
     }
     return $strUrl;
 }
Example #22
0
 /**
  * Test that exceptions can be rendered when an 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);
     $ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('statusCode', '_sendHeader'));
     $ExceptionRenderer->controller->response->expects($this->once())->method('statusCode')->with(500);
     ob_start();
     $ExceptionRenderer->render();
     $result = ob_get_clean();
     $this->assertContains('Internal Error', $result);
 }
Example #23
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 `CakeErrorController` normally, or if an error is repeated
  * a bare controller will be used.
  *
  * @param Exception $exception The exception to get a controller for.
  * @return Controller
  */
 protected function _getController($exception)
 {
     static $__previousError = null;
     App::import('Controller', 'CakeError');
     if ($__previousError != $exception) {
         $__previousError = $exception;
         $controller = new CakeErrorController(Router::getRequest(false));
     } else {
         $controller = new Controller(Router::getRequest(false));
         $controller->viewPath = 'errors';
     }
     return $controller;
 }
Example #24
0
<?php

$request = Router::getRequest();
if (strpos($request->url, 'install') === false) {
    $url = array('plugin' => 'install', 'controller' => 'install');
    Router::redirect('/*', $url, array('status' => 307));
}
Example #25
0
 /**
  * Constructor
  *
  * @param Controller $controller A controller object to pull View::_passedVars from.
  */
 public function __construct(Controller $controller = null)
 {
     if (is_object($controller)) {
         $count = count($this->_passedVars);
         for ($j = 0; $j < $count; $j++) {
             $var = $this->_passedVars[$j];
             $this->{$var} = $controller->{$var};
         }
         $this->_eventManager = $controller->getEventManager();
     }
     if (empty($this->request) && !($this->request = Router::getRequest(true))) {
         $this->request = new CakeRequest(null, false);
         $this->request->base = '';
         $this->request->here = $this->request->webroot = '/';
     }
     if (is_object($controller) && isset($controller->response)) {
         $this->response = $controller->response;
     } else {
         $this->response = new CakeResponse();
     }
     $this->Helpers = new HelperCollection($this);
     $this->Blocks = new ViewBlock();
     $this->loadHelpers();
     parent::__construct();
 }
 /**
  * Get the controller instance to handle the exception.
  * Override this method in subclasses to customize the controller used.
  * This method returns the built in `CakeErrorController` normally, or if an error is repeated
  * a bare controller will be used.
  *
  * @param Exception $exception The exception to get a controller for.
  * @return Controller
  */
 protected function _getController($exception)
 {
     App::uses('AppController', 'Controller');
     App::uses('CakeErrorController', 'Controller');
     if (!($request = Router::getRequest(true))) {
         $request = new CakeRequest();
     }
     $response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
     try {
         $controller = new CakeErrorController($request, $response);
         $controller->startupProcess();
     } catch (Exception $e) {
         if (!empty($controller) && $controller->Components->enabled('RequestHandler')) {
             $controller->RequestHandler->startup($controller);
         }
     }
     if (empty($controller)) {
         $controller = new Controller($request, $response);
         $controller->viewPath = 'Errors';
     }
     return $controller;
 }
Example #27
0
 /**
  * test that setRequestInfo can accept arrays and turn that into a CakeRequest object.
  *
  * @return void
  */
 public function testSetRequestInfoLegacy()
 {
     Router::setRequestInfo(array(array('plugin' => null, 'controller' => 'images', 'action' => 'index', 'url' => array('url' => 'protected/images/index')), array('base' => '', 'here' => '/protected/images/index', 'webroot' => '/')));
     $result = Router::getRequest();
     $this->assertEquals($result->controller, 'images');
     $this->assertEquals($result->action, 'index');
     $this->assertEquals($result->base, '');
     $this->assertEquals($result->here, '/protected/images/index');
     $this->assertEquals($result->webroot, '/');
 }
Example #28
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 `CakeErrorController` normally, or if an error is repeated
  * a bare controller will be used.
  *
  * @param Exception $exception The exception to get a controller for.
  * @return Controller
  */
 protected function _getController($exception)
 {
     App::uses('AppController', 'Controller');
     App::uses('CakeErrorController', 'Controller');
     if (!($request = Router::getRequest(true))) {
         $request = new CakeRequest();
     }
     $response = new CakeResponse();
     if (method_exists($exception, 'responseHeader')) {
         $response->header($exception->responseHeader());
     }
     if (class_exists('AppController')) {
         try {
             $controller = new CakeErrorController($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) && $controller->Components->enabled('RequestHandler')) {
             try {
                 $controller->RequestHandler->startup($controller);
             } catch (Exception $e) {
             }
         }
     }
     if (empty($controller)) {
         $controller = new Controller($request, $response);
         $controller->viewPath = 'Errors';
     }
     return $controller;
 }
 /**
  * Generates a formatted error message
  *
  * @param Exception $exception Exception instance
  * @return string Formatted message
  */
 protected static function _getMessage($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 !== 'cli') {
         $request = Router::getRequest();
         if ($request) {
             $message .= "\nRequest URL: " . $request->here();
         }
     }
     $message .= "\nStack Trace:\n" . $exception->getTraceAsString();
     return $message;
 }
 /**
  * testDisplayWithHerePrefix
  *
  * @return void
  */
 public function testDisplayWithHerePrefix()
 {
     Router::setRequestInfo(array(array('admin' => true, 'prefix' => 'admin', 'controller' => 'users', 'action' => 'action'), array('base' => '/', 'webroot' => '/', 'here' => '/admin/users/action')));
     $request = Router::getRequest(true);
     $this->Menu->setRequest($request);
     $this->Menu->add(array(array('Action', array('admin' => null, 'controller' => 'posts', 'action' => 'action', 'arg')), array('Controller', array('admin' => null, 'controller' => 'comments', 'action' => 'action')), array('Plugin', array('admin' => null, 'plugin' => 'cms', 'controller' => 'cms', 'action' => 'action')), array('Prefix', array('admin' => true, 'controller' => 'users', 'action' => 'action')), array('Exact', '/a/b/c')));
     $expected = '<ul>' . '<li><a href="/posts/action/arg">Action</a></li>' . '<li><a href="/comments/action">Controller</a></li>' . '<li><a href="/cms/cms/action">Plugin</a></li>' . '<li class="active"><a href="/admin/users/action">Prefix</a></li>' . '<li><a href="/a/b/c">Exact</a></li>' . '</ul>';
     $result = $this->Menu->display(array('active' => 'prefix'));
     $this->assertSame($expected, $result);
 }