reverse() public static method

Works similarly to Router::url(), but since parsed URL's contain additional 'pass' and 'named' as well as 'url.url' keys. Those keys need to be specially handled in order to reverse a params array into a string URL. This will strip out 'autoRender', 'bare', 'requested', and 'return' param names as those are used for CakePHP internals and should not normally be part of an output URL.
public static reverse ( CakeRequest | array $params, boolean $full = false ) : string
$params CakeRequest | array The params array or CakeRequest object that needs to be reversed.
$full boolean Set to true to include the full URL including the protocol when reversing the URL.
return string The string that is the reversed result of the array
 /**
  * Parses a string url into an array. Parsed urls will result in an automatic
  * redirection
  *
  * @param string $url The url to parse
  * @return boolean False on failure
  */
 public function parse($url)
 {
     $params = parent::parse($url);
     if (!$params) {
         return false;
     }
     if (!$this->response) {
         $this->response = new CakeResponse();
     }
     $redirect = $this->redirect;
     if (count($this->redirect) == 1 && !isset($this->redirect['controller'])) {
         $redirect = $this->redirect[0];
     }
     if (isset($this->options['persist']) && is_array($redirect)) {
         $redirect += array('named' => $params['named'], 'pass' => $params['pass'], 'url' => array());
         $redirect = Router::reverse($redirect);
     }
     $status = 301;
     if (isset($this->options['status']) && ($this->options['status'] >= 300 && $this->options['status'] < 400)) {
         $status = $this->options['status'];
     }
     $this->response->header(array('Location' => Router::url($redirect, true)));
     $this->response->statusCode($status);
     $this->response->send();
     $this->_stop();
 }
Example #2
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.
  *
  * @param mixed $url String or array-based url.
  * @param array $extra if array includes the key "return" it sets the AutoRender to true.
  * @return mixed Boolean true or false on success/failure, or contents
  *    of rendered action if 'return' is set in $extra.
  */
 public function requestAction($url, $extra = array())
 {
     if (empty($url)) {
         return false;
     }
     App::uses('Dispatcher', 'Routing');
     if (in_array('return', $extra, true)) {
         $extra = array_merge($extra, array('return' => 0, 'autoRender' => 1));
     }
     if (is_array($url) && !isset($extra['url'])) {
         $extra['url'] = array();
     }
     $extra = array_merge(array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra);
     if (is_string($url)) {
         $request = new CakeRequest($url);
     } elseif (is_array($url)) {
         $params = $url + array('pass' => array(), 'named' => array(), 'base' => false);
         $params = array_merge($params, $extra);
         $request = new CakeRequest(Router::reverse($params), false);
         if (isset($params['data'])) {
             $request->data = $params['data'];
         }
     }
     $dispatcher = new Dispatcher();
     return $dispatcher->dispatch($request, new CakeResponse(), $extra);
 }
Example #3
0
 public function testRoutableContentTypes()
 {
     $Type = ClassRegistry::init('Type');
     $type = $Type->create(array('title' => 'Press Release', 'alias' => 'press-release', 'description' => ''));
     $Type->save($type);
     $type = $Type->findByAlias('press-release');
     CroogoRouter::routableContentTypes();
     $params = array('url' => array(), 'controller' => 'nodes', 'action' => 'index', 'type' => 'press-release');
     $result = Router::reverse($params);
     $this->assertEquals('/nodes/index/type:press-release', $result);
     $type['Type']['params'] = 'routes=1';
     $Type->save($type);
     CroogoRouter::routableContentTypes();
     $result = Router::reverse($params);
     $this->assertEquals('/press-release', $result);
 }
Example #4
0
 /**
  * Test that extensions work with Router::reverse()
  *
  * @return void
  */
 public function testReverseWithExtension()
 {
     Router::parseExtensions('json');
     $request = new CakeRequest('/posts/view/1.json');
     $request->addParams(array('controller' => 'posts', 'action' => 'view', 'pass' => array(1), 'named' => array(), 'ext' => 'json'));
     $request->query = array();
     $result = Router::reverse($request);
     $expected = '/posts/view/1.json';
     $this->assertEquals($expected, $result);
 }
Example #5
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()
  *
  * #### Passing POST and GET data
  *
  * POST and GET data can be simulated in requestAction. Use `$extra['url']` for
  * GET data. The `$extra['data']` parameter allows POST data simulation.
  *
  * @param string|array $url String or array-based URL. Unlike other URL arrays in CakePHP, this
  *    URL will not automatically handle passed and named 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 named/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, $extra = array())
 {
     if (empty($url)) {
         return false;
     }
     if (($index = array_search('return', $extra)) !== false) {
         $extra['return'] = 0;
         $extra['autoRender'] = 1;
         unset($extra[$index]);
     }
     $arrayUrl = is_array($url);
     if ($arrayUrl && !isset($extra['url'])) {
         $extra['url'] = array();
     }
     if ($arrayUrl && !isset($extra['data'])) {
         $extra['data'] = array();
     }
     $extra += array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1);
     $data = isset($extra['data']) ? $extra['data'] : null;
     unset($extra['data']);
     if (is_string($url) && strpos($url, Router::fullBaseUrl()) === 0) {
         $url = Router::normalize(str_replace(Router::fullBaseUrl(), '', $url));
     }
     if (is_string($url)) {
         $request = new CakeRequest($url);
     } elseif (is_array($url)) {
         $params = $url + array('pass' => array(), 'named' => array(), 'base' => false);
         $params = $extra + $params;
         $request = new CakeRequest(Router::reverse($params));
     }
     if (isset($data)) {
         $request->data = $data;
     }
     $dispatcher = new Dispatcher();
     $result = $dispatcher->dispatch($request, new CakeResponse(), $extra);
     Router::popRequest();
     return $result;
 }
Example #6
0
 /**
  * Sets the params when $url is passed as an array to Object::requestAction();
  * Merges the $url and $additionalParams and creates a string url.
  *
  * @param array $url Array or request parameters
  * @param array $additionalParams Array of additional parameters.
  * @return string $url The generated url string.
  * @access private
  */
 function __extractParams($url, $additionalParams = array())
 {
     $defaults = array('pass' => array(), 'named' => array(), 'form' => array());
     $params = array_merge($defaults, $url, $additionalParams);
     $this->params = $params;
     $params += array('base' => false, 'url' => array());
     return ltrim(Router::reverse($params), '/');
 }
Example #7
0
 /**
  * Removed archived records from paginated lists by default.
  *
  * @param void
  * @return void
  */
 private function __handlePaginatorArchivable($object)
 {
     $options = $this->_getPaginatorVars($object, 'is_archived');
     if (!empty($options['schema']['is_archived'])) {
         $this->redirect(Router::reverse($this->request->params + array('filter' => 'archived:0', 'url' => null)));
     }
 }
 /**
  * Main execution method.  Handles redirecting of invalid users, and processing
  * of login form data.
  *
  * @param Controller $controller A reference to the instantiating controller object
  * @return boolean
  */
 public function startup($controller)
 {
     if ($controller->name == 'CakeError') {
         return true;
     }
     $methods = array_flip(array_map('strtolower', $controller->methods));
     $action = strtolower($controller->request->params['action']);
     $isMissingAction = $controller->scaffold === false && !isset($methods[$action]);
     if ($isMissingAction) {
         return true;
     }
     if (!$this->_setDefaults()) {
         return false;
     }
     $request = $controller->request;
     $url = '';
     if (isset($request->url)) {
         $url = $request->url;
     }
     $url = Router::normalize($url);
     $loginAction = Router::normalize($this->loginAction);
     $allowedActions = $this->allowedActions;
     $isAllowed = $this->allowedActions == array('*') || in_array($action, array_map('strtolower', $allowedActions));
     if ($loginAction != $url && $isAllowed) {
         return true;
     }
     if ($loginAction == $url) {
         if (empty($request->data)) {
             if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
                 $this->Session->write('Auth.redirect', $controller->referer(null, true));
             }
         }
         return true;
     } else {
         if (!$this->_getUser()) {
             if (!$request->is('ajax')) {
                 $this->flash($this->authError);
                 $this->Session->write('Auth.redirect', Router::reverse($request));
                 $controller->redirect($loginAction);
                 return false;
             } elseif (!empty($this->ajaxLogin)) {
                 $controller->viewPath = 'Elements';
                 echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
                 $this->_stop();
                 return false;
             } else {
                 $controller->redirect(null, 403);
             }
         }
     }
     if (empty($this->authorize) || $this->isAuthorized($this->user())) {
         return true;
     }
     $this->flash($this->authError);
     $controller->redirect($controller->referer('/'), null, true);
     return false;
 }
Example #9
0
 /**
  * This is used instead of the above on one site who's feature I'm integrating.
  * I only see serializedTemplateRequest() being used in updateTemplateSettings() anyway.. so might be able to just use this.
  * 
  * @param array $data
  * @return string
  */
 public function _url($data)
 {
     if (empty($data['Webpage']['url']) && !empty($data['Webpage']['id'])) {
         $data = array('admin' => false, 'plugin' => 'webpages', 'controller' => 'webpages', 'action' => 'view', $data['Webpage']['id']);
     }
     if ($data['plugin'] == 'webpages' && $data['controller'] == 'webpages' && $data['action'] == 'view') {
         return 'webpages/webpages/view/' . $data[0] . '/';
         // webpages get special treatment
         $url = @Router::reverse($data);
         // seems to be returning the slug URL; possibly because we are now using routes.php
         $url = strpos($url, '/') === 0 ? substr($url, 1) . '/' : $url . '/';
     } elseif ($data['action'] == 'index') {
         $url = $data['plugin'] . '/' . $data['controller'] . '/' . $data['action'] . '*';
     } else {
         unset($data['pass']);
         unset($data['named']);
         $url = @Router::reverse($data) . '/*';
     }
     return $url;
 }
 /**
  * Authorize user
  * 
  * Accepts a `client_id` and optional `client_secret` query string and, 
  * based on a `response_type`, returns a newly minted `code` or `token`.
  * 
  * @author	Anthony Putignano <*****@*****.**>
  * @since	0.1
  * @return	void
  */
 public function authorize()
 {
     $user_id = $this->Session->read('Auth.' . $this->authorizeActionSettings['userIdKey']);
     if (empty($user_id)) {
         $this->Session->write('Auth.redirect', Router::reverse($this->request));
         return $this->redirect($this->authorizeActionSettings['loginUrl'], 401);
     }
     $client_data = $this->OAuth2->validateAuthorizeRequest();
     if (empty($client_data)) {
         return false;
     }
     $api_key = $client_data['client_id'];
     $post_scope = !empty($this->request->data['scope']) ? $this->request->data['scope'] : null;
     $get_scope = !empty($this->request->query['scope']) ? $this->request->query['scope'] : null;
     $scope = !empty($post_scope) ? $post_scope : $get_scope;
     if (!isset($this->OAuth2Authorization)) {
         $this->loadModel('OAuth2.OAuth2Authorization');
     }
     $existing_authorization = $this->OAuth2Authorization->getExisting($api_key, $user_id, $scope);
     $show_permissions_page = false;
     if (empty($existing_authorization) && $this->request->is('get')) {
         $show_permissions_page = true;
     }
     $proceed_with_authorization = false;
     if (!empty($existing_authorization) || $this->request->is('post')) {
         $proceed_with_authorization = true;
     }
     if ($show_permissions_page) {
         $this->set('client', $client_data);
     } elseif ($proceed_with_authorization) {
         $allow = false;
         if (!empty($existing_authorization) || !empty($this->request->data['allow'])) {
             $allow = true;
         }
         $response = $this->OAuth2->handleAuthorizeRequest($allow, $user_id);
         if (empty($response)) {
             return false;
         }
         return $this->redirect($response->getHttpHeader('Location'), $response->getStatusCode());
     }
 }
Example #11
0
 /**
  * beforeFilter
  *
  * @return	void
  */
 public function beforeFilter()
 {
     parent::beforeFilter();
     $isRequestView = $this->request->is('requestview');
     $isUpdate = $this->request->is('update');
     $isAdmin = $this->request->is('admin');
     $isInstall = $this->request->is('install');
     $isMaintenance = $this->request->is('maintenance');
     // 設定されたサイトURLとリクエストされたサイトURLが違う場合は設定されたサイトにリダイレクト
     if ($isAdmin) {
         if ($this->request->is('ssl')) {
             $siteUrl = Configure::read('BcEnv.sslUrl');
         } else {
             $siteUrl = Configure::read('BcEnv.siteUrl');
         }
         if ($siteUrl && siteUrl() != $siteUrl) {
             $this->redirect($siteUrl . preg_replace('/^\\//', '', Router::reverse($this->request, false)));
         }
     }
     // メンテナンス
     if (!empty($this->siteConfigs['maintenance']) && Configure::read('debug') < 1 && !$isMaintenance && !$isAdmin && !BcUtil::isAdminUser()) {
         if (!empty($this->request->params['return']) && !empty($this->request->params['requested'])) {
             return;
         } else {
             $redirectUrl = '/maintenance';
             if ($this->request->params['Site']['alias']) {
                 $redirectUrl = '/' . $this->request->params['Site']['alias'] . $redirectUrl;
             }
             $this->redirect($redirectUrl);
         }
     }
     // セキュリティ設定
     $this->Security->blackHoleCallback = '_blackHoleCallback';
     if (!BC_INSTALLED || $isUpdate) {
         $this->Security->validatePost = false;
     }
     if ($isAdmin) {
         $this->Security->validatePost = false;
         $corePlugins = Configure::read('BcApp.corePlugins');
         if (BC_INSTALLED && (!$this->plugin || in_array($this->plugin, $corePlugins)) && Configure::read('debug') === 0) {
             $this->Security->csrfCheck = true;
         } else {
             $this->Security->csrfCheck = false;
         }
         // SSLリダイレクト設定
         if (Configure::read('BcApp.adminSsl')) {
             $adminSslMethods = array_filter(get_class_methods(get_class($this)), array($this, '_adminSslMethods'));
             if ($adminSslMethods) {
                 $this->Security->requireSecure = $adminSslMethods;
             }
         }
     }
     //$this->Security->validatePost = false;
     // 送信データの文字コードを内部エンコーディングに変換
     $this->__convertEncodingHttpInput();
     // $this->request->query['url'] の調整
     // 環境によって?キーにamp;が付加されてしまうため
     if (isset($this->request->query) && is_array($this->request->query)) {
         foreach ($this->request->query as $key => $val) {
             if (strpos($key, 'amp;') === 0) {
                 $this->request->query[substr($key, 4)] = $val;
                 unset($this->request->query[$key]);
             }
         }
     }
     // コンソールから利用される場合、$isInstall だけでは判定できないので、BC_INSTALLED も判定に入れる
     if (!BC_INSTALLED || $isInstall || $isUpdate) {
         return;
     }
     // Ajax ヘッダー
     if ($this->request->is('ajax')) {
         // キャッシュ対策
         header("Cache-Control: no-cache, must-revalidate");
         header("Cache-Control: post-check=0, pre-check=0", false);
         header("Pragma: no-cache");
     }
     // テーマ内プラグインのテンプレートをテーマに梱包できるようにプラグインパスにテーマのパスを追加
     // ===============================================================================
     // 実際には、プラグインの場合も下記パスがテンプレートの検索対象となっている為不要だが、
     // ビューが存在しない場合に、プラグインテンプレートの正規のパスがエラーメッセージに
     // 表示されてしまうので明示的に指定している。
     // (例)
     // [変更後] app/webroot/theme/demo/blog/news/index.php
     // [正 規] app/plugins/blog/views/theme/demo/blog/news/index.php
     // 但し、CakePHPの仕様としてはテーマ内にプラグインのテンプレートを梱包できる仕様となっていないので
     // 将来的には、blog / mail / feed をプラグインではなくコアへのパッケージングを検討する必要あり。
     // ※ AppView::_pathsも関連している
     // ===============================================================================
     $pluginThemePath = WWW_ROOT . 'theme' . DS . $this->theme . DS;
     $pluginPaths = Configure::read('pluginPaths');
     if ($pluginPaths && !in_array($pluginThemePath, $pluginPaths)) {
         Configure::write('pluginPaths', am(array($pluginThemePath), $pluginPaths));
     }
     // 認証設定
     if (isset($this->BcAuthConfigure)) {
         $authConfig = array();
         if (!empty($this->request->params['prefix'])) {
             $currentAuthPrefix = $this->request->params['prefix'];
         } else {
             $currentAuthPrefix = 'front';
         }
         $authPrefixSettings = Configure::read('BcAuthPrefix');
         foreach ($authPrefixSettings as $key => $authPrefixSetting) {
             if (isset($authPrefixSetting['alias']) && $authPrefixSetting['alias'] == $currentAuthPrefix) {
                 $authConfig = $authPrefixSetting;
                 $authConfig['auth_prefix'] = $authPrefixSetting['alias'];
                 break;
             }
             if ($key == $currentAuthPrefix) {
                 $authConfig = $authPrefixSetting;
                 $authConfig['auth_prefix'] = $key;
                 break;
             }
         }
         if ($authConfig) {
             $this->BcAuthConfigure->setting($authConfig);
         } else {
             $this->BcAuth->setSessionKey('Auth.' . Configure::read('BcAuthPrefix.admin.sessionKey'));
         }
         // =================================================================
         // ユーザーの存在チェック
         // ログイン中のユーザーを管理側で削除した場合、ログイン状態を削除する必要がある為
         // =================================================================
         $user = $this->BcAuth->user();
         if ($user && $authConfig) {
             $userModel = $authConfig['userModel'];
             $User = ClassRegistry::init($userModel);
             if (strpos($userModel, '.') !== false) {
                 list($plugin, $userModel) = explode('.', $userModel);
             }
             if ($userModel && !empty($this->{$userModel})) {
                 $conditions = array($userModel . '.id' => $user['id'], $userModel . '.name' => $user['name']);
                 if (isset($User->belongsTo['UserGroup'])) {
                     $UserGroup = ClassRegistry::init('UserGroup');
                     $userGroups = $UserGroup->find('all', array('conditions' => array('UserGroup.auth_prefix LIKE' => '%' . $authConfig['auth_prefix'] . '%'), 'recursive' => -1));
                     $userGroupIds = Hash::extract($userGroups, '{n}.UserGroup.id');
                     $conditions[$userModel . '.user_group_id'] = $userGroupIds;
                 }
                 if (!$User->find('count', array('conditions' => $conditions, 'recursive' => -1))) {
                     $this->Session->delete(BcAuthComponent::$sessionKey);
                 }
             }
         }
     }
     if ($isRequestView) {
         // テーマ、レイアウトとビュー用サブディレクトリの設定
         $this->setTheme();
         if (isset($this->request->params['prefix'])) {
             $this->layoutPath = str_replace('_', '/', $this->request->params['prefix']);
             $this->subDir = str_replace('_', '/', $this->request->params['prefix']);
         }
         if (!$isAdmin && !empty($this->request->params['Site']['name'])) {
             $agentSetting = Configure::read('BcAgent.' . $this->request->params['Site']['device']);
             if ($agentSetting && !empty($agentSetting['helper'])) {
                 $this->helpers[] = $agentSetting['helper'];
             }
             if (isset($this->request->params['Site'])) {
                 $this->layoutPath = $this->request->params['Site']['name'];
                 $this->subDir = $this->request->params['Site']['name'];
             }
         }
         // 権限チェック
         if (isset($User->belongsTo['UserGroup']) && isset($this->BcAuth) && isset($this->request->params['prefix']) && empty($this->request->params['Site']['name']) && isset($this->request->params['action']) && empty($this->request->params['requested'])) {
             if (!$this->BcAuth->allowedActions || !in_array($this->request->params['action'], $this->BcAuth->allowedActions)) {
                 $user = $this->BcAuth->user();
                 $Permission = ClassRegistry::init('Permission');
                 if ($user) {
                     if (!$Permission->check($this->request->url, $user['user_group_id'])) {
                         $this->setMessage('指定されたページへのアクセスは許可されていません。', true);
                         $this->redirect($this->BcAuth->loginRedirect);
                     }
                 }
             }
         }
     }
 }
 /**
  * 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()
  *
  * #### Passing POST and GET data
  *
  * POST and GET data can be simulated in requestAction.  Use `$extra['url']` for
  * GET data.  The `$extra['data']` parameter allows POST data simulation.
  *
  * @param mixed $url String or array-based url.  Unlike other url arrays in CakePHP, this
  *    url will not automatically handle passed and named 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 named/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, $extra = array())
 {
     if (empty($url)) {
         return false;
     }
     App::uses('Dispatcher', 'Routing');
     if (($index = array_search('return', $extra)) !== false) {
         $extra['return'] = 0;
         $extra['autoRender'] = 1;
         unset($extra[$index]);
     }
     if (is_array($url) && !isset($extra['url'])) {
         $extra['url'] = array();
     }
     $extra = array_merge(array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra);
     $data = isset($extra['data']) ? $extra['data'] : null;
     unset($extra['data']);
     if (is_string($url)) {
         $request = new CakeRequest($url);
     } elseif (is_array($url)) {
         $params = $url + array('pass' => array(), 'named' => array(), 'base' => false);
         $params = array_merge($params, $extra);
         $request = new CakeRequest(Router::reverse($params), false);
     }
     if (isset($data)) {
         $request->data = $data;
     }
     $dispatcher = new Dispatcher();
     $result = $dispatcher->dispatch($request, new CakeResponse(), $extra);
     Router::popRequest();
     return $result;
 }
Example #13
0
 /**
  * test reversing parameter arrays back into strings.
  *
  * @return void
  */
 public function testRouterReverse()
 {
     $params = array('controller' => 'posts', 'action' => 'view', 'pass' => array(1), 'named' => array(), 'url' => array(), 'autoRender' => 1, 'bare' => 1, 'return' => 1, 'requested' => 1, '_Token' => array('key' => 'sekret'));
     $result = Router::reverse($params);
     $this->assertEqual($result, '/posts/view/1');
     $params = array('controller' => 'posts', 'action' => 'index', 'pass' => array(1), 'named' => array('page' => 1, 'sort' => 'Article.title', 'direction' => 'desc'), 'url' => array());
     $result = Router::reverse($params);
     $this->assertEqual($result, '/posts/index/1/page:1/sort:Article.title/direction:desc');
     Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{3}'));
     $params = array('lang' => 'eng', 'controller' => 'posts', 'action' => 'view', 'pass' => array(1), 'named' => array(), 'url' => array('url' => 'eng/posts/view/1'));
     $result = Router::reverse($params);
     $this->assertEqual($result, '/eng/posts/view/1');
     $params = array('lang' => 'eng', 'controller' => 'posts', 'action' => 'view', 'pass' => array(1), 'named' => array(), 'url' => array('url' => 'eng/posts/view/1', 'foo' => 'bar', 'baz' => 'quu'), 'paging' => array(), 'models' => array());
     $result = Router::reverse($params);
     $this->assertEqual($result, '/eng/posts/view/1?foo=bar&baz=quu');
     $request = new CakeRequest('/eng/posts/view/1');
     $request->addParams(array('lang' => 'eng', 'controller' => 'posts', 'action' => 'view', 'pass' => array(1), 'named' => array()));
     $request->query = array('url' => 'eng/posts/view/1', 'test' => 'value');
     $result = Router::reverse($request);
     $expected = '/eng/posts/view/1?test=value';
     $this->assertEquals($expected, $result);
     $params = array('lang' => 'eng', 'controller' => 'posts', 'action' => 'view', 'pass' => array(1), 'named' => array(), 'url' => array('url' => 'eng/posts/view/1'));
     $result = Router::reverse($params, true);
     $this->assertPattern('/^http(s)?:\\/\\//', $result);
 }
 /**
  * turn framework-style url (/home/view/4) to routed url (/product/4)
  * @param type $url
  * @param type $params
  * @return type
  */
 function urlReverse($url, $params)
 {
     return $this->url(Router::reverse($url, $params));
 }
Example #15
0
 function admin_destroy($id)
 {
     if (!empty($id) || $this->Xpagin->isExecuter) {
         if (empty($id) && !empty($this->data['Xpagin']['record'])) {
             $id = $this->data['Xpagin']['record'];
         } else {
             if (empty($id)) {
                 $this->Notifier->error($this->Interpreter->process("[:no_items_selected:]"));
                 $this->redirect($this->referer());
             }
         }
         if ($this->Location->deleteAll(array('id' => $id))) {
             $this->Notifier->success($this->Interpreter->process("[:Location_deleted_successfully:]"));
         } else {
             $this->Notifier->success($this->Interpreter->process("[:an_error_ocurred_on_the_server:]"));
         }
         $this->redirect(Router::reverse(Router::parse($this->referer())));
     } else {
         $this->Notifier->error($this->Interpreter->process("[:specify_a_Location_id_add:]"));
     }
     if (!$this->Xpagin->isExecuter) {
         $referer = Router::parse($this->referer());
         if ($referer['action'] == 'view') {
             $this->redirect(array('action' => 'trash'));
         }
         $this->redirect($this->referer());
     }
 }
Example #16
0
 /**
  * Clean url from rating parameters
  *
  * @return array
  */
 public function removeRatingParamsFromUrl()
 {
     if ($this->named === true) {
         $queryParams = $this->Controller->request->params['named'];
     } else {
         $queryParams = $this->Controller->request->query;
     }
     foreach ($queryParams as $name => $value) {
         if (isset($this->parameters[$name])) {
             unset($queryParams[$name]);
         }
     }
     if ($this->named === true) {
         $this->Controller->request->params['named'] = $queryParams;
     } else {
         $this->Controller->request->query = $queryParams;
     }
     return Router::reverse($this->Controller->request);
 }
Example #17
0
 /**
  * test reversing parameter arrays back into strings.
  *
  * @return void
  */
 function testRouterReverse()
 {
     $params = array('controller' => 'posts', 'action' => 'view', 'pass' => array(1), 'named' => array(), 'url' => array(), 'autoRender' => 1, 'bare' => 1, 'return' => 1, 'requested' => 1);
     $result = Router::reverse($params);
     $this->assertEqual($result, '/posts/view/1');
     $params = array('controller' => 'posts', 'action' => 'index', 'pass' => array(1), 'named' => array('page' => 1, 'sort' => 'Article.title', 'direction' => 'desc'), 'url' => array());
     $result = Router::reverse($params);
     $this->assertEqual($result, '/posts/index/1/page:1/sort:Article.title/direction:desc');
     Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{3}'));
     $params = array('lang' => 'eng', 'controller' => 'posts', 'action' => 'view', 'pass' => array(1), 'named' => array(), 'url' => array('url' => 'eng/posts/view/1'));
     $result = Router::reverse($params);
     $this->assertEqual($result, '/eng/posts/view/1');
     $params = array('lang' => 'eng', 'controller' => 'posts', 'action' => 'view', 'pass' => array(1), 'named' => array(), 'url' => array('url' => 'eng/posts/view/1', 'foo' => 'bar', 'baz' => 'quu'), 'paging' => array(), 'models' => array());
     $result = Router::reverse($params);
     $this->assertEqual($result, '/eng/posts/view/1?foo=bar&baz=quu');
 }
Example #18
0
 public function initialize(Controller $controller)
 {
     $controller->loggedUser = $controller->Session->read('loggedUser');
     if (is_null($controller->loggedUser)) {
         $controller->Cookie->domain = env('HTTP_BASE');
         $controller->Cookie->name = 'remember_me';
         $cookie = $controller->Cookie->read('User');
         if (!empty($cookie)) {
             if ($cookie['model_class'] == 'UserModel') {
                 $user_model = ClassRegistry::init('User.UserModel');
                 $user = $user_model->find('first', array('conditions' => array('UserModel.user_email' => $cookie['email'], 'UserModel.password' => $cookie['password'], 'UserModel.user_status' => USER_ACTIVE), 'multiLanguageIsUsed' => false));
                 if ($user) {
                     $controller->loggedUser = new stdClass();
                     $controller->loggedUser->Admin = new stdClass();
                     $controller->loggedUser->Admin->id = 0;
                     unset($user['UserAccount']['password']);
                     $controller->loggedUser->User = arrayToObject($user['UserModel']);
                     $access_model = ClassRegistry::init('User.UserRoleAccess');
                     $controller->loggedUser->Role = Hash::combine($access_model->findByUserId($user['UserModel']['id']), 'UserRoleAccess.role_id', 'UserRoleAccess.role_id');
                     $controller->Session->write('loggedUser', $this->loggedUser);
                 }
             } elseif ($cookie['model_class'] == 'UserAdmin') {
                 $admin_model = ClassRegistry::init('User.UserAdmin');
                 $admin = $admin_model->find('first', array('conditions' => array('UserAdmin.email' => $cookie['email'], 'UserAdmin.password' => $cookie['password'], 'UserAdmin.status' => USER_ADMIN_ACTIVE), 'multiLanguageIsUsed' => false));
                 if ($admin) {
                     $controller->loggedUser = new stdClass();
                     $controller->loggedUser->User = new stdClass();
                     $controller->loggedUser->User->id = 0;
                     unset($admin['UserAdmin']['password']);
                     $controller->loggedUser->Admin = arrayToObject($admin['UserAdmin']);
                     $controller->Session->write('loggedUser', $this->loggedUser);
                 }
             }
         }
     }
     if (empty($controller->loggedUser)) {
         $controller->loggedUser = new stdClass();
         $controller->loggedUser->Admin = new stdClass();
         $controller->loggedUser->User = new stdClass();
         $controller->loggedUser->Admin->id = 0;
         $controller->loggedUser->User->id = 0;
     }
     /* Admin has all access */
     if ($controller->loggedUser->Admin->id > 0) {
         return true;
     }
     $classController = get_class($controller);
     $parentController = get_parent_class($controller);
     /* System CakeHandler controller */
     if (in_array($classController, array('CakeErrorController'))) {
         return true;
     }
     /* Verify exclude parent controller */
     $userParentExcludeController = Configure::read('USER_EXCLUDE_PARENT_CONTROLLER');
     if (!empty($controller->plugin) && isset($userParentExcludeController['plugin'][$controller->plugin][$parentController])) {
         return true;
     } elseif (empty($controller->plugin) && isset($userParentExcludeController['controller'][$parentController])) {
         return true;
     }
     /* End of verify exclude parent controller */
     /* Verify exclude controller */
     $accController = null;
     $userExcludeController = Configure::read('USER_EXCLUDE_CONTROLLER');
     if (!empty($controller->plugin)) {
         if (isset($userExcludeController['plugin'][$controller->plugin])) {
             $accPlugin = $userExcludeController['plugin'][$controller->plugin];
             if (count($accPlugin) == 0) {
                 return true;
             }
             if (isset($accPlugin[$classController])) {
                 $accController = $accPlugin[$classController];
             }
         }
     } else {
         if (isset($userExcludeController['controller'][$classController])) {
             $accController = $userExcludeController['controller'][$classController];
         }
     }
     if (!is_null($accController)) {
         if (count($accController) == 0) {
             return true;
         }
         if (isset($accController[$controller->action])) {
             return true;
         }
     }
     /* End of Verify exclude controller */
     /* Exclude exact URL */
     if (in_array(Router::reverse($controller->request), Configure::read('USER_EXCLUDE_URL'))) {
         return true;
     }
     /* Exclude exact URL Pattern */
     foreach (Configure::read('USER_EXCLUDE_URL_REGEX') as $exculePattern) {
         if (@preg_match($exculePattern, Router::reverse($controller->request))) {
             return true;
         }
     }
     $access = true;
     $roleRight = ClassRegistry::init('User.UserRoleRight');
     if ($controller->loggedUser->User->id == 0) {
         list($rolesP, $rolesC) = $roleRight->getRightByRole(USER_ROLE_ANONYM);
     } else {
         list($rolesP, $rolesC) = $roleRight->getRightByRole($controller->loggedUser->Role);
     }
     if (!empty($controller->plugin)) {
         if (!(isset($rolesP[$controller->plugin][$classController][$controller->action]['id']) || isset($rolesP[$controller->plugin][$classController]['id']) || isset($rolesP[$controller->plugin]['id']))) {
             $access = false;
         }
     } elseif (!(isset($rolesC[$classController][$controller->action]['id']) || isset($rolesC[$classController]['id']))) {
         $access = false;
     }
     if (!$access) {
         if ($controller->loggedUser->User->id == 0) {
             $controller->Session->setFlash(__('You are not authorized to access this page. Please login'), 'flash/error');
             $controller->redirect(Router::url(array('plugin' => 'User', 'controller' => 'User', 'action' => 'login')));
         } else {
             $controller->Session->setFlash(__('You are not authorized to access this page'), 'flash/error');
             $controller->redirect('/');
         }
     }
 }