/** * construct method */ public function __construct($request = null, $response = null) { $request->addParams(Router::parse('/auth_test')); $request->here = '/auth_test'; $request->webroot = '/'; Router::setRequestInfo($request); parent::__construct($request, $response); }
/** * Filters the BrowserKit request to the cake one. * * @param \Symfony\Component\BrowserKit\Request $request BrowserKit request. * @return \Cake\Network\Request Cake request. */ protected function filterRequest(\Symfony\Component\BrowserKit\Request $request) { $url = preg_replace('/^https?:\\/\\/[a-z0-9\\-\\.]+/', '', $request->getUri()); $_ENV = $environment = ['REQUEST_METHOD' => $request->getMethod()] + $request->getServer(); $props = ['url' => $url, 'post' => (array) $request->getParameters(), 'files' => (array) $request->getFiles(), 'cookies' => (array) $request->getCookies(), 'session' => $this->getSession(), 'environment' => $environment]; $this->cake['request'] = new Request($props); // set params Router::setRequestInfo($this->cake['request']); $this->cake['request']->params = Router::parse($url); return $this->cake['request']; }
/** * Adds a comment in DB and redirects * * @return void */ public function add() { $comment = $this->Comments->newEntity(); // the body field should be empty as it's a honeypot for bots if ($this->request->is('post') && empty($this->request->data('body'))) { $data = $this->request->data; // Preparing data if (!empty($this->Auth->user('id'))) { $data['user_id'] = $this->Auth->user('id'); $data['name'] = $this->Auth->user('username'); $data['email'] = $this->Auth->user('email'); } else { $data['user_id'] = null; } unset($data['body']); // Getting the route $route = Router::parse(str_replace(Router::url('/', true), '', $this->referer(true))); $data['fkid'] = $route['pass'][0]; $data['model'] = $route['controller']; $comment = $this->Comments->patchEntity($comment, $data); if ($this->Comments->save($comment)) { if ($comment->allow_contact) { $this->Flash->success(__d('elabs', 'Thank you for your comment. The author will contact you soon.')); } else { $this->Flash->success(__d('elabs', 'Thank you for your comment.')); } $this->redirect($this->referer()); } else { $this->Flash->error(__d('elabs', 'The comment could not be saved. Please try again.')); } } $this->redirect($this->referer()); }
/** * 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 void */ public function beforeDispatch(Event $event) { $request = $event->data['request']; Router::setRequestInfo($request); if (empty($request->params['controller'])) { $params = Router::parse($request->url); $request->addParams($params); } }
/** * Generates the opauth callback url * * @return string Full translated URL with base path. */ protected function _generateOpauthCompleteUrl() { $url = Configure::read('Opauth.complete_url'); if (!is_array($url)) { $url = Router::parse($url); } $url['?'] = ['social' => $this->request->query('code')]; return Router::url($url, true); }
public function index() { if ($this->request->is('ajax')) { if ($this->request->is('post')) { $request = $this->request->data('request'); $requestParams = Router::parse($request); $this->AdminBar->createAdminBar($requestParams); $this->layout = 'AdminBar.ajax'; } } }
/** * @param ServerRequestInterface $request The request. * @param ResponseInterface $response The response. * @param callable $next The next middleware to call * @return RedirectResponse */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) { try { $params = (array) $request->getAttribute('params', []); if (empty($params['controller'])) { $path = $request->getUri()->getPath(); $request = $request->withAttribute('params', Router::parse($path, $request->getMethod())); } } catch (RedirectException $e) { return new RedirectResponse($e->getMessage(), $e->getCode(), $response->getHeaders()); } return $next($request, $response); }
/** * Check if the user can access to the given URL. * * @param array $params The params to check. * * @return bool */ public function check(array $params = []) { if (!$this->request->session()->read('Auth.User')) { return false; } $params += ['_base' => false]; $url = Router::url($params); $params = Router::parse($url); $user = [$this->Authorize->config('userModel') => $this->request->session()->read('Auth.User')]; $request = new Request(); $request->addParams($params); $action = $this->Authorize->action($request); return $this->Acl->check($user, $action); }
/** * This method provides conditional output of the desired link only if the current user has access to the controller action referenced by the * link. * @return Returns the constructed link if the current user has access to the controller action referenced by the link or false, if not. * @see \Cake\View\Helper\HtmlHelper::link() for additional information on the parameters. */ public function link($title, $url = null, array $options = []) { $parsedRoute = Router::parse(Router::url($url !== null ? $url : $title)); $annAuthorization = AnnAuthorization::getInstance(); $userId = $this->request->session()->read('Auth.User.id'); $controller = $parsedRoute['controller']; $action = $parsedRoute['action']; $pass = $parsedRoute['pass']; $requestAuthorized = $annAuthorization->authorizeRequest($userId, $controller, $action, $pass, $this->request); if ($requestAuthorized) { return $this->Html->link($title, $url, $options); } return false; }
/** * 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 void|Cake\Network\Response A response will be returned when a redirect route is encountered. */ public function beforeDispatch(Event $event) { $request = $event->data['request']; Router::setRequestInfo($request); try { if (empty($request->params['controller'])) { $params = Router::parse($request->url); $request->addParams($params); } } catch (RedirectException $e) { $response = $event->data['response']; $response->statusCode($e->getCode()); $response->header('Location', $e->getMessage()); return $response; } }
/** * Checks a url for the route that will be applied. * * @param string $url The URL to parse * @return null|false */ public function check($url) { try { $route = Router::parse($url); foreach (Router::routes() as $r) { if ($r->match($route)) { $name = isset($r->options['_name']) ? $r->options['_name'] : $r->getName(); break; } } $output = [['Route name', 'URI template', 'Defaults'], [$name, $url, json_encode($route)]]; $this->helper('table')->output($output); $this->out(); } catch (MissingRouteException $e) { $this->err("<warning>'{$url}' did not match any routes.</warning>"); $this->out(); return false; } }
/** * @param string $label * @param \Cake\View\Helper\HtmlHelper $htmlHelper * * In order to make a trail of breadcrumbs we must: * 1. Emit any number of trail elements, in a view, using $htmlHelper->addCrumb(). * 2. Emit the beginning of the trail in a layout, using $thmlHelper->getCrumbs(). * 3. addCrumbs and getCrumbs provide the necessary information so that when the time * comes to actually render the trail, the Cake software can do this. * * The problem with this plan is that some views can be reached via more than one path. * How can the view know which path led to it? The basic answer is to save a path * in the session, with each step towards a particular view, and use that path to * generate the trail using a suitable number of invocations of addCrumb. Each view's * url is added to the session trail, as well as a suitable label to be used in the trail. */ public function makeTrail($label, $htmlHelper) { // 1. Read the present trail or init if none. $sessionVar = 'breadcrumbs'; //$this->request->session()->delete($sessionVar); $sessionCrumbs = $this->request->session()->read($sessionVar); if (is_null($sessionCrumbs)) { $sessionCrumbs = []; } // 2. Get the present url and parse into a parameter array $requestUrl = $this->request->url; $requestUrlParams = \Cake\Routing\Router::parse($requestUrl); // 3. Build a new trail array by looking for the existing // url in the existing trail array. This effectively removes // any elements of the existing trail array, that are after the // present url. $newArray = []; foreach ($sessionCrumbs as $key => $crumb) { if ($key == $requestUrl) { break; } else { $newArray[$key] = $crumb; } } // 3.1 Whether this is new or the last item matched, add it here $newArray[$requestUrl] = ['label' => $label, 'params' => $requestUrlParams]; // 4. Save the trail to the session $this->request->session()->write($sessionVar, $newArray); // 5. Now add the crumbs the ordinary way foreach ($newArray as $key => $crumb) { if ($key == $requestUrl) { break; } // no crumb for this url $htmlHelper->addCrumb($crumb['label'], $crumb['params']); } }
/** * test that the returned URL doesn't contain the base URL. * * @see https://cakephp.lighthouseapp.com/projects/42648/tickets/3922-authcomponentredirecturl-prepends-appbaseurl * * @return void This test method doesn't return anything. */ public function testRedirectUrlWithBaseSet() { $App = Configure::read('App'); Configure::write('App', ['dir' => APP_DIR, 'webroot' => 'webroot', 'base' => false, 'baseUrl' => '/cake/index.php']); $url = '/users/login'; $this->Auth->request = $this->Controller->request = new Request($url); $this->Auth->request->addParams(Router::parse($url)); $this->Auth->request->url = Router::normalize($url); Router::setRequestInfo($this->Auth->request); $this->Auth->config('loginAction', ['controller' => 'users', 'action' => 'login']); $this->Auth->config('loginRedirect', ['controller' => 'users', 'action' => 'home']); $result = $this->Auth->redirectUrl(); $this->assertEquals('/users/home', $result); $this->assertFalse($this->Auth->session->check('Auth.redirect')); Configure::write('App', $App); Router::reload(); }
/** * Combine auto with post * also allows whitelisting certain actions for autoRedirect (use Controller::$autoRedirectActions) * * @param mixed $whereTo URL * @param bool $conditionalAutoRedirect false to skip whitelisting * @param int $status * @return \Cake\Network\Response */ public function autoPostRedirect($whereTo, $conditionalAutoRedirect = true, $status = 302) { $referer = $this->Controller->referer($whereTo, true); if (!$conditionalAutoRedirect && !empty($referer)) { return $this->postRedirect($referer, $status); } if (!empty($referer)) { $referer = Router::parse($referer); } if ($conditionalAutoRedirect && !empty($this->Controller->autoRedirectActions) && is_array($referer) && !empty($referer['action'])) { // Be sure that controller offset exists, otherwise you // will run into problems, if you use url rewriting. $refererController = null; if (isset($referer['controller'])) { $refererController = $referer['controller']; } // fixme if (!isset($this->Controller->autoRedirectActions)) { $this->Controller->autoRedirectActions = []; } foreach ($this->Controller->autoRedirectActions as $action) { list($controller, $action) = pluginSplit($action); if (!empty($controller) && $refererController !== '*' && $refererController !== $controller) { continue; } if (empty($controller) && $refererController !== $this->Controller->request->params['controller']) { continue; } if (!in_array($referer['action'], $this->Controller->autoRedirectActions, true)) { continue; } return $this->autoRedirect($whereTo, true, $status); } } return $this->postRedirect($whereTo, $status); }
/** * Returns possible URL combinations for the given URL or current request's URL. * * ### Example: * * For the given URL, `/admin/content/manage/index/arg1/arg2?get1=v1&get2=v2` * where: * * - `/admin`: Prefix. * - `/content`: Plugin name. * - `/manage`: Controller name. * - `/index`: Controller's action. * - `/arg1` and `/arg2`: Action's arguments. * - `get1` and `get2`: GET arguments. * * The following array will be returned by this method: * * ```php * [ * "/admin/content/content/index/arg1/arg2?get1=v1&get2=v2", * "/admin/content/content/arg1/arg2", * "/admin/content/arg1/arg2", * "/admin/content/arg1", * "/admin/content", * ] * ``` * * @param string|null $url The URL to chunk as string value, set to null * will use current request URL. * @return array */ protected function _urlChunk($url = null) { if (empty($url)) { $url = '/' . $this->_controller->request->url; } $cacheKey = 'urlChunk_' . md5($url); $cache = static::cache($cacheKey); if ($cache !== null) { return $cache; } $parsedURL = Router::parse($url); $out = [$url]; $passArguments = []; if (!empty($parsedURL['?'])) { unset($parsedURL['?']); } if (!empty($parsedURL['pass'])) { $passArguments = $parsedURL['pass']; $parsedURL['pass'] = null; $parsedURL = array_merge($parsedURL, $passArguments); } // "/controller_name/index" -> "/controller" if ($parsedURL['action'] === 'index') { $parsedURL['action'] = null; $out[] = Router::url($parsedURL); } // "/plugin_name/plugin_name/action_name" -> "/plugin_name/action_name" if (!empty($parsedURL['plugin']) && strtolower($parsedURL['controller']) === strtolower($parsedURL['plugin'])) { $parsedURL['plugin'] = null; $out[] = Router::url($parsedURL); } foreach (array_reverse($passArguments) as $pass) { unset($parsedURL[array_search($pass, $parsedURL)]); $out[] = Router::url($parsedURL); } $out = array_map(function ($value) { if (str_starts_with($value, $this->_controller->request->base)) { return str_replace_once($this->_controller->request->base, '', $value); } return $value; }, $out); return static::cache($cacheKey, array_unique($out)); }
/** * Determine the path for a given url array. * * @param array $url The url parameters. * @return string */ public function getPathFromUrl($url) { $cacheKey = md5(serialize($url)); return Cache::remember($cacheKey, function () use($url) { $plugin = 'App'; $action = 'index'; $parsedUrl = !is_array($url) ? Router::parse($url) : $url; if (isset($parsedUrl['plugin']) && !empty($parsedUrl['plugin'])) { $plugin = $parsedUrl['plugin']; } $controller = $parsedUrl['controller']; if (isset($parsedUrl['action']) && $parsedUrl['action'] !== '') { $action = $parsedUrl['action']; } return $plugin . '.' . $controller . '.' . $action; }, 'wasabi/core/guardian_paths'); }
protected function filterMustBeCleared($options) { $current_path = $this->getComparisonPath($this->request->params); $referer_path = $this->getComparisonPath(Router::parse($this->request->referer(true))); if ($current_path == $referer_path) { return false; } else { $plugin = isset($this->request->params['plugin']) ? $this->request->params['plugin'] : null; $prefix = isset($this->request->params['prefix']) ? $this->request->params['prefix'] : null; $controller = $this->request->params['controller']; $action = $this->request->params['action']; $pass = isset($this->request->params['pass']) ? $this->request->params['pass'] : []; $query = isset($this->request->params['?']) ? $this->request->params['?'] : []; $referer = Router::parse($this->request->referer(true)); $referer_plugin = isset($referer['plugin']) ? $referer['plugin'] : null; $referer_prefix = isset($referer['prefix']) ? $referer['prefix'] : null; $referer_controller = $referer['controller']; $referer_action = $referer['action']; $referer_pass = isset($referer['pass']) ? $referer['pass'] : []; $referer_query = isset($referer['?']) ? $referer['?'] : []; if ($plugin == $referer_plugin && $prefix == $referer_prefix && $controller == $referer_controller) { if (isset($options['keep_filter_actions']) && is_array($options['keep_filter_actions'])) { if (in_array($referer_action, $options['keep_filter_actions'])) { return false; } } } } return true; }
/** * Test dispatching into the TestPlugin in the TestApp * * @return void */ public function testTestPluginDispatch() { $Dispatcher = new TestDispatcher(); Plugin::load(array('TestPlugin', 'TestPluginTwo')); Router::reload(); Router::parse('/'); $url = new Request('/test_plugin/tests/index'); $response = $this->getMock('Cake\\Network\\Response'); $Dispatcher->dispatch($url, $response, array('return' => 1)); $this->assertTrue(class_exists('TestPlugin\\Controller\\TestsController')); $this->assertTrue(class_exists('TestPlugin\\Controller\\TestPluginAppController')); $this->assertTrue(class_exists('TestPlugin\\Controller\\Component\\PluginsComponent')); $this->assertEquals('tests', $url->params['controller']); $this->assertEquals('test_plugin', $url->params['plugin']); $this->assertEquals('index', $url->params['action']); }
/** * Checks whether the user is allowed to access a specific URL * * @param array $user user to check with * @param array|string $url url to check * @return void */ public function urlAllowed($user, $url) { if (empty($url)) { return false; } if (is_array($url)) { // prevent plugin confusion $url = Hash::merge(['plugin' => null], $url); $url = Router::url($url); // strip off the base path $url = Router::normalize($url); } $route = Router::parse($url); if (empty($route['controller']) || empty($route['action'])) { return false; } return $this->isAuthorized($user, $route['plugin'], $route['controller'], $route['action']); }
/** * test using a custom route class for route connection * * @return void */ public function testUsingCustomRouteClass() { Plugin::load('TestPlugin'); Router::connect('/:slug', ['plugin' => 'TestPlugin', 'action' => 'index'], ['routeClass' => 'PluginShortRoute', 'slug' => '[a-z_-]+']); $result = Router::parse('/the-best'); $expected = ['plugin' => 'TestPlugin', 'controller' => 'TestPlugin', 'action' => 'index', 'slug' => 'the-best', 'pass' => [], '_matchedRoute' => '/:slug']; $this->assertEquals($expected, $result); }
public function isLinkActive($url) { //TODO: Maybe more intelligent active link detection $currentUrl = Router::url($this->request->params); if (!empty($this->request->base) || $this->request->base != '/') { $currentUrl = str_replace($this->request->base, '', $currentUrl); } if (!is_array($url)) { $url = Router::parse($url); } if ($this->request->params['controller'] == $url['controller']) { $url = Router::normalize($url); return (bool) preg_match("/^(" . preg_quote($url, "/") . ")/", trim($currentUrl)); } }
/** * Configures the instance * * @param View $View CakePHP View instance * @param array $config helper config */ public function __construct(\Cake\View\View $View, array $config = []) { parent::__construct($View, $config); $this->_currentUrl = Router::parse(Router::url()); }
/** * Lets you do functional tests of a controller action. * * ### Options: * * - `data` The data to use for POST or PUT requests. If `method` is GET * and `query` is empty, the data key will be used as GET parameters. By setting * `data to a string you can simulate XML or JSON payloads allowing you to test * REST webservices. * - `query` The query string parameters to set. * - `cookies` The cookie data to use for the request. * - `method` POST or GET. Defaults to GET. * - `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 $url The url to test * @param array $options See options * @return mixed */ protected function _testAction($url = '', $options = array()) { $this->vars = $this->result = $this->view = $this->contents = $this->headers = null; $this->_session = $this->_session ?: new Session(); $options += array('query' => array(), 'data' => array(), 'cookies' => array(), 'method' => 'GET', 'return' => 'result'); $method = strtoupper($options['method']); $_SERVER['REQUEST_METHOD'] = $method; if ($method === 'GET' && is_array($options['data']) && empty($options['query'])) { $options['query'] = $options['data']; $options['data'] = array(); } $requestData = array('url' => $url, 'cookies' => $options['cookies'], 'query' => $options['query'], 'session' => $this->_session); if (is_array($options['data'])) { $requestData['post'] = $options['data']; } $request = $this->getMock('Cake\\Network\\Request', array('_readInput', 'method'), array($requestData)); $request->expects($this->any())->method('method')->will($this->returnValue($method)); if (is_string($options['data'])) { $request->expects($this->any())->method('_readInput')->will($this->returnValue($options['data'])); } if ($this->loadRoutes) { Router::reload(); } $request->addParams(Router::parse($request->url)); // Handle redirect routes. if (!isset($request->params['controller']) && Router::getRequest()) { $this->headers = Router::getRequest()->response->header(); return; } $stubFilter = new StubControllerFilter(); $dispatch = DispatcherFactory::create(); $dispatch->addFilter($stubFilter); if ($this->_dirtyController) { $this->controller = null; } if ($this->controller === null && $this->autoMock) { $plugin = ''; if (!empty($request->params['plugin'])) { $plugin = $request->params['plugin'] . '.'; } $controllerName = $request->params['controller']; if (!empty($request->params['prefix'])) { $controllerName = Inflector::camelize($request->params['prefix']) . '/' . $controllerName; } $this->generate($plugin . $controllerName, [], $request); } $params = array(); if ($options['return'] === 'result') { $params['return'] = 1; $params['bare'] = 1; $params['requested'] = 1; } $request->addParams($params); $response = $this->getMock('Cake\\Network\\Response', array('send', 'stop')); $stubFilter->response = $response; $stubFilter->testController = $this->controller; $this->result = $dispatch->dispatch($request, $response); $this->controller = $stubFilter->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 = $response->header(); return $this->{$options['return']}; }
/** * Applies Routing and additionalParameters to the request to be dispatched. * If Routes have not been loaded they will be loaded, and app/Config/routes.php will be run. * * @param \Cake\Event\Event $event containing the request, response and additional params * @return void */ public function parseParams(Event $event) { $request = $event->data['request']; Router::setRequestInfo($request); if (empty($request->params['controller'])) { $params = Router::parse($request->url); $request->addParams($params); } if (!empty($event->data['additionalParams'])) { $request->addParams($event->data['additionalParams']); } }
/** * Checks if the given user has permission to perform an action. * * @param array $params The params to check. * * @return string */ public function hasPermission(array $params = []) { $params += ['controller' => 'Permissions', '_base' => false, 'prefix' => 'chat']; $url = Router::url($params); $params = Router::parse($url); $request = new Request(); $request->addParams($params); $action = $this->Authorize->action($request); $user = [$this->Authorize->config('userModel') => $this->_session->read('Auth.User')]; return $this->Acl->check($user, $action); }
/** * test setting redirect routes * * @return void */ public function testRouteRedirection() { $routes = new RouteCollection(); Router::setRouteCollection($routes); Router::redirect('/blog', array('controller' => 'posts'), array('status' => 302)); Router::connect('/:controller', array('action' => 'index')); $this->assertEquals(2, count($routes)); $routes->get(0)->response = $this->getMock('Cake\\Network\\Response', array('_sendHeader', 'stop')); $this->assertEquals(302, $routes->get(0)->options['status']); Router::parse('/blog'); $header = $routes->get(0)->response->header(); $this->assertEquals(Router::url('/posts', true), $header['Location']); $this->assertEquals(302, $routes->get(0)->response->statusCode()); $routes->get(0)->response = $this->getMock('Cake\\Network\\Response', array('_sendHeader')); Router::parse('/not-a-match'); $this->assertSame([], $routes->get(0)->response->header()); }
/** * Check if a given url is authorized * * @param Event $event event * * @return bool */ public function isUrlAuthorized(Event $event) { $url = Hash::get((array) $event->data, 'url'); if (empty($url)) { return false; } if (is_array($url)) { $requestUrl = Router::reverse($url); $requestParams = Router::parse($requestUrl); } else { try { //remove base from $url if exists $normalizedUrl = Router::normalize($url); $requestParams = Router::parse($normalizedUrl); } catch (MissingRouteException $ex) { //if it's a url pointing to our own app if (substr($normalizedUrl, 0, 1) === '/') { throw $ex; } return true; } $requestUrl = $url; } // check if controller action is allowed if ($this->_isActionAllowed($requestParams)) { return true; } // check we are logged in $user = $this->_registry->getController()->Auth->user(); if (empty($user)) { return false; } $request = new Request($requestUrl); $request->params = $requestParams; $isAuthorized = $this->_registry->getController()->Auth->isAuthorized(null, $request); return $isAuthorized; }
/** * Check if a given url is authorized * * @param Event $event event * * @return bool */ public function isUrlAuthorized(Event $event) { $user = $this->_registry->getController()->Auth->user(); if (empty($user)) { return false; } $url = Hash::get((array) $event->data, 'url'); if (empty($url)) { return false; } if (is_array($url)) { $requestUrl = Router::reverse($url); $requestParams = Router::parse($requestUrl); } else { $requestParams = Router::parse($url); $requestUrl = $url; } $request = new Request($requestUrl); $request->params = $requestParams; $isAuthorized = $this->_registry->getController()->Auth->isAuthorized(null, $request); return $isAuthorized; }
/** * Get the url for the given page. * * @param int $page * * @return string */ public function getUrl($page) { $url = Router::parse(Router::url()); $url['page'] = $page; return Router::fullBaseUrl() . Router::url($url); }