PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Routing/Router.php

https://bitbucket.org/ds10/agent-j
PHP | 1122 lines | 549 code | 92 blank | 481 comment | 130 complexity | 09cfcbaf8c7cbf08b19165929f23c286 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, LGPL-3.0, GPL-2.0, LGPL-2.1, MIT
  1. <?php
  2. /**
  3. * Parses the request URL into controller, action, and parameters.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Routing
  16. * @since CakePHP(tm) v 0.2.9
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('CakeRequest', 'Network');
  20. App::uses('CakeRoute', 'Routing/Route');
  21. /**
  22. * Parses the request URL into controller, action, and parameters. Uses the connected routes
  23. * to match the incoming url string to parameters that will allow the request to be dispatched. Also
  24. * handles converting parameter lists into url strings, using the connected routes. Routing allows you to decouple
  25. * the way the world interacts with your application (urls) and the implementation (controllers and actions).
  26. *
  27. * ### Connecting routes
  28. *
  29. * Connecting routes is done using Router::connect(). When parsing incoming requests or reverse matching
  30. * parameters, routes are enumerated in the order they were connected. You can modify the order of connected
  31. * routes using Router::promote(). For more information on routes and how to connect them see Router::connect().
  32. *
  33. * ### Named parameters
  34. *
  35. * Named parameters allow you to embed key:value pairs into path segments. This allows you create hash
  36. * structures using urls. You can define how named parameters work in your application using Router::connectNamed()
  37. *
  38. * @package Cake.Routing
  39. */
  40. class Router {
  41. /**
  42. * Array of routes connected with Router::connect()
  43. *
  44. * @var array
  45. */
  46. public static $routes = array();
  47. /**
  48. * List of action prefixes used in connected routes.
  49. * Includes admin prefix
  50. *
  51. * @var array
  52. */
  53. protected static $_prefixes = array();
  54. /**
  55. * Directive for Router to parse out file extensions for mapping to Content-types.
  56. *
  57. * @var boolean
  58. */
  59. protected static $_parseExtensions = false;
  60. /**
  61. * List of valid extensions to parse from a URL. If null, any extension is allowed.
  62. *
  63. * @var array
  64. */
  65. protected static $_validExtensions = array();
  66. /**
  67. * 'Constant' regular expression definitions for named route elements
  68. *
  69. */
  70. const ACTION = 'index|show|add|create|edit|update|remove|del|delete|view|item';
  71. const YEAR = '[12][0-9]{3}';
  72. const MONTH = '0[1-9]|1[012]';
  73. const DAY = '0[1-9]|[12][0-9]|3[01]';
  74. const ID = '[0-9]+';
  75. const UUID = '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}';
  76. /**
  77. * Named expressions
  78. *
  79. * @var array
  80. */
  81. protected static $_namedExpressions = array(
  82. 'Action' => Router::ACTION,
  83. 'Year' => Router::YEAR,
  84. 'Month' => Router::MONTH,
  85. 'Day' => Router::DAY,
  86. 'ID' => Router::ID,
  87. 'UUID' => Router::UUID
  88. );
  89. /**
  90. * Stores all information necessary to decide what named arguments are parsed under what conditions.
  91. *
  92. * @var string
  93. */
  94. protected static $_namedConfig = array(
  95. 'default' => array('page', 'fields', 'order', 'limit', 'recursive', 'sort', 'direction', 'step'),
  96. 'greedyNamed' => true,
  97. 'separator' => ':',
  98. 'rules' => false,
  99. );
  100. /**
  101. * The route matching the URL of the current request
  102. *
  103. * @var array
  104. */
  105. protected static $_currentRoute = array();
  106. /**
  107. * Default HTTP request method => controller action map.
  108. *
  109. * @var array
  110. */
  111. protected static $_resourceMap = array(
  112. array('action' => 'index', 'method' => 'GET', 'id' => false),
  113. array('action' => 'view', 'method' => 'GET', 'id' => true),
  114. array('action' => 'add', 'method' => 'POST', 'id' => false),
  115. array('action' => 'edit', 'method' => 'PUT', 'id' => true),
  116. array('action' => 'delete', 'method' => 'DELETE', 'id' => true),
  117. array('action' => 'edit', 'method' => 'POST', 'id' => true)
  118. );
  119. /**
  120. * List of resource-mapped controllers
  121. *
  122. * @var array
  123. */
  124. protected static $_resourceMapped = array();
  125. /**
  126. * Maintains the request object stack for the current request.
  127. * This will contain more than one request object when requestAction is used.
  128. *
  129. * @var array
  130. */
  131. protected static $_requests = array();
  132. /**
  133. * Initial state is populated the first time reload() is called which is at the bottom
  134. * of this file. This is a cheat as get_class_vars() returns the value of static vars even if they
  135. * have changed.
  136. *
  137. * @var array
  138. */
  139. protected static $_initialState = array();
  140. /**
  141. * Default route class to use
  142. *
  143. * @var string
  144. */
  145. protected static $_routeClass = 'CakeRoute';
  146. /**
  147. * Set the default route class to use or return the current one
  148. *
  149. * @param string $routeClass to set as default
  150. * @return mixed void|string
  151. * @throws RouterException
  152. */
  153. public static function defaultRouteClass($routeClass = null) {
  154. if (is_null($routeClass)) {
  155. return self::$_routeClass;
  156. }
  157. self::$_routeClass = self::_validateRouteClass($routeClass);
  158. }
  159. /**
  160. * Validates that the passed route class exists and is a subclass of CakeRoute
  161. *
  162. * @param $routeClass
  163. * @return string
  164. * @throws RouterException
  165. */
  166. protected static function _validateRouteClass($routeClass) {
  167. if (!class_exists($routeClass) || !is_subclass_of($routeClass, 'CakeRoute')) {
  168. throw new RouterException(__d('cake_dev', 'Route classes must extend CakeRoute'));
  169. }
  170. return $routeClass;
  171. }
  172. /**
  173. * Sets the Routing prefixes.
  174. *
  175. * @return void
  176. */
  177. protected static function _setPrefixes() {
  178. $routing = Configure::read('Routing');
  179. if (!empty($routing['prefixes'])) {
  180. self::$_prefixes = array_merge(self::$_prefixes, (array)$routing['prefixes']);
  181. }
  182. }
  183. /**
  184. * Gets the named route elements for use in app/Config/routes.php
  185. *
  186. * @return array Named route elements
  187. * @see Router::$_namedExpressions
  188. */
  189. public static function getNamedExpressions() {
  190. return self::$_namedExpressions;
  191. }
  192. /**
  193. * Resource map getter & setter.
  194. *
  195. * @param array $resourceMap Resource map
  196. * @return mixed
  197. * @see Router::$_resourceMap
  198. */
  199. public static function resourceMap($resourceMap = null) {
  200. if ($resourceMap === null) {
  201. return self::$_resourceMap;
  202. }
  203. self::$_resourceMap = $resourceMap;
  204. }
  205. /**
  206. * Connects a new Route in the router.
  207. *
  208. * Routes are a way of connecting request urls to objects in your application. At their core routes
  209. * are a set or regular expressions that are used to match requests to destinations.
  210. *
  211. * Examples:
  212. *
  213. * `Router::connect('/:controller/:action/*');`
  214. *
  215. * The first parameter will be used as a controller name while the second is used as the action name.
  216. * the '/*' syntax makes this route greedy in that it will match requests like `/posts/index` as well as requests
  217. * like `/posts/edit/1/foo/bar`.
  218. *
  219. * `Router::connect('/home-page', array('controller' => 'pages', 'action' => 'display', 'home'));`
  220. *
  221. * The above shows the use of route parameter defaults. And providing routing parameters for a static route.
  222. *
  223. * {{{
  224. * Router::connect(
  225. * '/:lang/:controller/:action/:id',
  226. * array(),
  227. * array('id' => '[0-9]+', 'lang' => '[a-z]{3}')
  228. * );
  229. * }}}
  230. *
  231. * Shows connecting a route with custom route parameters as well as providing patterns for those parameters.
  232. * Patterns for routing parameters do not need capturing groups, as one will be added for each route params.
  233. *
  234. * $options offers four 'special' keys. `pass`, `named`, `persist` and `routeClass`
  235. * have special meaning in the $options array.
  236. *
  237. * `pass` is used to define which of the routed parameters should be shifted into the pass array. Adding a
  238. * parameter to pass will remove it from the regular route array. Ex. `'pass' => array('slug')`
  239. *
  240. * `persist` is used to define which route parameters should be automatically included when generating
  241. * new urls. You can override persistent parameters by redefining them in a url or remove them by
  242. * setting the parameter to `false`. Ex. `'persist' => array('lang')`
  243. *
  244. * `routeClass` is used to extend and change how individual routes parse requests and handle reverse routing,
  245. * via a custom routing class. Ex. `'routeClass' => 'SlugRoute'`
  246. *
  247. * `named` is used to configure named parameters at the route level. This key uses the same options
  248. * as Router::connectNamed()
  249. *
  250. * @param string $route A string describing the template of the route
  251. * @param array $defaults An array describing the default route parameters. These parameters will be used by default
  252. * and can supply routing parameters that are not dynamic. See above.
  253. * @param array $options An array matching the named elements in the route to regular expressions which that
  254. * element should match. Also contains additional parameters such as which routed parameters should be
  255. * shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a
  256. * custom routing class.
  257. * @see routes
  258. * @return array Array of routes
  259. * @throws RouterException
  260. */
  261. public static function connect($route, $defaults = array(), $options = array()) {
  262. foreach (self::$_prefixes as $prefix) {
  263. if (isset($defaults[$prefix])) {
  264. if ($defaults[$prefix]) {
  265. $defaults['prefix'] = $prefix;
  266. } else {
  267. unset($defaults[$prefix]);
  268. }
  269. break;
  270. }
  271. }
  272. if (isset($defaults['prefix'])) {
  273. self::$_prefixes[] = $defaults['prefix'];
  274. self::$_prefixes = array_keys(array_flip(self::$_prefixes));
  275. }
  276. $defaults += array('plugin' => null);
  277. if (empty($options['action'])) {
  278. $defaults += array('action' => 'index');
  279. }
  280. $routeClass = self::$_routeClass;
  281. if (isset($options['routeClass'])) {
  282. $routeClass = self::_validateRouteClass($options['routeClass']);
  283. unset($options['routeClass']);
  284. }
  285. if ($routeClass == 'RedirectRoute' && isset($defaults['redirect'])) {
  286. $defaults = $defaults['redirect'];
  287. }
  288. self::$routes[] = new $routeClass($route, $defaults, $options);
  289. return self::$routes;
  290. }
  291. /**
  292. * Connects a new redirection Route in the router.
  293. *
  294. * Redirection routes are different from normal routes as they perform an actual
  295. * header redirection if a match is found. The redirection can occur within your
  296. * application or redirect to an outside location.
  297. *
  298. * Examples:
  299. *
  300. * `Router::redirect('/home/*', array('controller' => 'posts', 'action' => 'view', array('persist' => true)));`
  301. *
  302. * Redirects /home/* to /posts/view and passes the parameters to /posts/view. Using an array as the
  303. * redirect destination allows you to use other routes to define where a url string should be redirected to.
  304. *
  305. * `Router::redirect('/posts/*', 'http://google.com', array('status' => 302));`
  306. *
  307. * Redirects /posts/* to http://google.com with a HTTP status of 302
  308. *
  309. * ### Options:
  310. *
  311. * - `status` Sets the HTTP status (default 301)
  312. * - `persist` Passes the params to the redirected route, if it can. This is useful with greedy routes,
  313. * routes that end in `*` are greedy. As you can remap urls and not loose any passed/named args.
  314. *
  315. * @param string $route A string describing the template of the route
  316. * @param array $url A url to redirect to. Can be a string or a Cake array-based url
  317. * @param array $options An array matching the named elements in the route to regular expressions which that
  318. * element should match. Also contains additional parameters such as which routed parameters should be
  319. * shifted into the passed arguments. As well as supplying patterns for routing parameters.
  320. * @see routes
  321. * @return array Array of routes
  322. */
  323. public static function redirect($route, $url, $options = array()) {
  324. App::uses('RedirectRoute', 'Routing/Route');
  325. $options['routeClass'] = 'RedirectRoute';
  326. if (is_string($url)) {
  327. $url = array('redirect' => $url);
  328. }
  329. return self::connect($route, $url, $options);
  330. }
  331. /**
  332. * Specifies what named parameters CakePHP should be parsing out of incoming urls. By default
  333. * CakePHP will parse every named parameter out of incoming URLs. However, if you want to take more
  334. * control over how named parameters are parsed you can use one of the following setups:
  335. *
  336. * Do not parse any named parameters:
  337. *
  338. * {{{ Router::connectNamed(false); }}}
  339. *
  340. * Parse only default parameters used for CakePHP's pagination:
  341. *
  342. * {{{ Router::connectNamed(false, array('default' => true)); }}}
  343. *
  344. * Parse only the page parameter if its value is a number:
  345. *
  346. * {{{ Router::connectNamed(array('page' => '[\d]+'), array('default' => false, 'greedy' => false)); }}}
  347. *
  348. * Parse only the page parameter no matter what.
  349. *
  350. * {{{ Router::connectNamed(array('page'), array('default' => false, 'greedy' => false)); }}}
  351. *
  352. * Parse only the page parameter if the current action is 'index'.
  353. *
  354. * {{{
  355. * Router::connectNamed(
  356. * array('page' => array('action' => 'index')),
  357. * array('default' => false, 'greedy' => false)
  358. * );
  359. * }}}
  360. *
  361. * Parse only the page parameter if the current action is 'index' and the controller is 'pages'.
  362. *
  363. * {{{
  364. * Router::connectNamed(
  365. * array('page' => array('action' => 'index', 'controller' => 'pages')),
  366. * array('default' => false, 'greedy' => false)
  367. * );
  368. * }}}
  369. *
  370. * ### Options
  371. *
  372. * - `greedy` Setting this to true will make Router parse all named params. Setting it to false will
  373. * parse only the connected named params.
  374. * - `default` Set this to true to merge in the default set of named parameters.
  375. * - `reset` Set to true to clear existing rules and start fresh.
  376. * - `separator` Change the string used to separate the key & value in a named parameter. Defaults to `:`
  377. *
  378. * @param array $named A list of named parameters. Key value pairs are accepted where values are
  379. * either regex strings to match, or arrays as seen above.
  380. * @param array $options Allows to control all settings: separator, greedy, reset, default
  381. * @return array
  382. */
  383. public static function connectNamed($named, $options = array()) {
  384. if (isset($options['separator'])) {
  385. self::$_namedConfig['separator'] = $options['separator'];
  386. unset($options['separator']);
  387. }
  388. if ($named === true || $named === false) {
  389. $options = array_merge(array('default' => $named, 'reset' => true, 'greedy' => $named), $options);
  390. $named = array();
  391. } else {
  392. $options = array_merge(array('default' => false, 'reset' => false, 'greedy' => true), $options);
  393. }
  394. if ($options['reset'] == true || self::$_namedConfig['rules'] === false) {
  395. self::$_namedConfig['rules'] = array();
  396. }
  397. if ($options['default']) {
  398. $named = array_merge($named, self::$_namedConfig['default']);
  399. }
  400. foreach ($named as $key => $val) {
  401. if (is_numeric($key)) {
  402. self::$_namedConfig['rules'][$val] = true;
  403. } else {
  404. self::$_namedConfig['rules'][$key] = $val;
  405. }
  406. }
  407. self::$_namedConfig['greedyNamed'] = $options['greedy'];
  408. return self::$_namedConfig;
  409. }
  410. /**
  411. * Gets the current named parameter configuration values.
  412. *
  413. * @return array
  414. * @see Router::$_namedConfig
  415. */
  416. public static function namedConfig() {
  417. return self::$_namedConfig;
  418. }
  419. /**
  420. * Creates REST resource routes for the given controller(s). When creating resource routes
  421. * for a plugin, by default the prefix will be changed to the lower_underscore version of the plugin
  422. * name. By providing a prefix you can override this behavior.
  423. *
  424. * ### Options:
  425. *
  426. * - 'id' - The regular expression fragment to use when matching IDs. By default, matches
  427. * integer values and UUIDs.
  428. * - 'prefix' - URL prefix to use for the generated routes. Defaults to '/'.
  429. *
  430. * @param mixed $controller A controller name or array of controller names (i.e. "Posts" or "ListItems")
  431. * @param array $options Options to use when generating REST routes
  432. * @return array Array of mapped resources
  433. */
  434. public static function mapResources($controller, $options = array()) {
  435. $hasPrefix = isset($options['prefix']);
  436. $options = array_merge(array(
  437. 'prefix' => '/',
  438. 'id' => self::ID . '|' . self::UUID
  439. ), $options);
  440. $prefix = $options['prefix'];
  441. foreach ((array)$controller as $name) {
  442. list($plugin, $name) = pluginSplit($name);
  443. $urlName = Inflector::underscore($name);
  444. $plugin = Inflector::underscore($plugin);
  445. if ($plugin && !$hasPrefix) {
  446. $prefix = '/' . $plugin . '/';
  447. }
  448. foreach (self::$_resourceMap as $params) {
  449. $url = $prefix . $urlName . (($params['id']) ? '/:id' : '');
  450. Router::connect($url,
  451. array(
  452. 'plugin' => $plugin,
  453. 'controller' => $urlName,
  454. 'action' => $params['action'],
  455. '[method]' => $params['method']
  456. ),
  457. array('id' => $options['id'], 'pass' => array('id'))
  458. );
  459. }
  460. self::$_resourceMapped[] = $urlName;
  461. }
  462. return self::$_resourceMapped;
  463. }
  464. /**
  465. * Returns the list of prefixes used in connected routes
  466. *
  467. * @return array A list of prefixes used in connected routes
  468. */
  469. public static function prefixes() {
  470. return self::$_prefixes;
  471. }
  472. /**
  473. * Parses given URL string. Returns 'routing' parameters for that url.
  474. *
  475. * @param string $url URL to be parsed
  476. * @return array Parsed elements from URL
  477. */
  478. public static function parse($url) {
  479. $ext = null;
  480. $out = array();
  481. if ($url && strpos($url, '/') !== 0) {
  482. $url = '/' . $url;
  483. }
  484. if (strpos($url, '?') !== false) {
  485. $url = substr($url, 0, strpos($url, '?'));
  486. }
  487. extract(self::_parseExtension($url));
  488. for ($i = 0, $len = count(self::$routes); $i < $len; $i++) {
  489. $route =& self::$routes[$i];
  490. if (($r = $route->parse($url)) !== false) {
  491. self::$_currentRoute[] =& $route;
  492. $out = $r;
  493. break;
  494. }
  495. }
  496. if (isset($out['prefix'])) {
  497. $out['action'] = $out['prefix'] . '_' . $out['action'];
  498. }
  499. if (!empty($ext) && !isset($out['ext'])) {
  500. $out['ext'] = $ext;
  501. }
  502. return $out;
  503. }
  504. /**
  505. * Parses a file extension out of a URL, if Router::parseExtensions() is enabled.
  506. *
  507. * @param string $url
  508. * @return array Returns an array containing the altered URL and the parsed extension.
  509. */
  510. protected static function _parseExtension($url) {
  511. $ext = null;
  512. if (self::$_parseExtensions) {
  513. if (preg_match('/\.[0-9a-zA-Z]*$/', $url, $match) === 1) {
  514. $match = substr($match[0], 1);
  515. if (empty(self::$_validExtensions)) {
  516. $url = substr($url, 0, strpos($url, '.' . $match));
  517. $ext = $match;
  518. } else {
  519. foreach (self::$_validExtensions as $name) {
  520. if (strcasecmp($name, $match) === 0) {
  521. $url = substr($url, 0, strpos($url, '.' . $name));
  522. $ext = $match;
  523. break;
  524. }
  525. }
  526. }
  527. }
  528. }
  529. return compact('ext', 'url');
  530. }
  531. /**
  532. * Takes parameter and path information back from the Dispatcher, sets these
  533. * parameters as the current request parameters that are merged with url arrays
  534. * created later in the request.
  535. *
  536. * Nested requests will create a stack of requests. You can remove requests using
  537. * Router::popRequest(). This is done automatically when using Object::requestAction().
  538. *
  539. * Will accept either a CakeRequest object or an array of arrays. Support for
  540. * accepting arrays may be removed in the future.
  541. *
  542. * @param CakeRequest|array $request Parameters and path information or a CakeRequest object.
  543. * @return void
  544. */
  545. public static function setRequestInfo($request) {
  546. if ($request instanceof CakeRequest) {
  547. self::$_requests[] = $request;
  548. } else {
  549. $requestObj = new CakeRequest();
  550. $request += array(array(), array());
  551. $request[0] += array('controller' => false, 'action' => false, 'plugin' => null);
  552. $requestObj->addParams($request[0])->addPaths($request[1]);
  553. self::$_requests[] = $requestObj;
  554. }
  555. }
  556. /**
  557. * Pops a request off of the request stack. Used when doing requestAction
  558. *
  559. * @return CakeRequest The request removed from the stack.
  560. * @see Router::setRequestInfo()
  561. * @see Object::requestAction()
  562. */
  563. public static function popRequest() {
  564. return array_pop(self::$_requests);
  565. }
  566. /**
  567. * Get the either the current request object, or the first one.
  568. *
  569. * @param boolean $current Whether you want the request from the top of the stack or the first one.
  570. * @return CakeRequest or null.
  571. */
  572. public static function getRequest($current = false) {
  573. if ($current) {
  574. $i = count(self::$_requests) - 1;
  575. return isset(self::$_requests[$i]) ? self::$_requests[$i] : null;
  576. }
  577. return isset(self::$_requests[0]) ? self::$_requests[0] : null;
  578. }
  579. /**
  580. * Gets parameter information
  581. *
  582. * @param boolean $current Get current request parameter, useful when using requestAction
  583. * @return array Parameter information
  584. */
  585. public static function getParams($current = false) {
  586. if ($current) {
  587. return self::$_requests[count(self::$_requests) - 1]->params;
  588. }
  589. if (isset(self::$_requests[0])) {
  590. return self::$_requests[0]->params;
  591. }
  592. return array();
  593. }
  594. /**
  595. * Gets URL parameter by name
  596. *
  597. * @param string $name Parameter name
  598. * @param boolean $current Current parameter, useful when using requestAction
  599. * @return string Parameter value
  600. */
  601. public static function getParam($name = 'controller', $current = false) {
  602. $params = Router::getParams($current);
  603. if (isset($params[$name])) {
  604. return $params[$name];
  605. }
  606. return null;
  607. }
  608. /**
  609. * Gets path information
  610. *
  611. * @param boolean $current Current parameter, useful when using requestAction
  612. * @return array
  613. */
  614. public static function getPaths($current = false) {
  615. if ($current) {
  616. return self::$_requests[count(self::$_requests) - 1];
  617. }
  618. if (!isset(self::$_requests[0])) {
  619. return array('base' => null);
  620. }
  621. return array('base' => self::$_requests[0]->base);
  622. }
  623. /**
  624. * Reloads default Router settings. Resets all class variables and
  625. * removes all connected routes.
  626. *
  627. * @return void
  628. */
  629. public static function reload() {
  630. if (empty(self::$_initialState)) {
  631. self::$_initialState = get_class_vars('Router');
  632. self::_setPrefixes();
  633. return;
  634. }
  635. foreach (self::$_initialState as $key => $val) {
  636. if ($key != '_initialState') {
  637. self::${$key} = $val;
  638. }
  639. }
  640. self::_setPrefixes();
  641. }
  642. /**
  643. * Promote a route (by default, the last one added) to the beginning of the list
  644. *
  645. * @param integer $which A zero-based array index representing the route to move. For example,
  646. * if 3 routes have been added, the last route would be 2.
  647. * @return boolean Returns false if no route exists at the position specified by $which.
  648. */
  649. public static function promote($which = null) {
  650. if ($which === null) {
  651. $which = count(self::$routes) - 1;
  652. }
  653. if (!isset(self::$routes[$which])) {
  654. return false;
  655. }
  656. $route =& self::$routes[$which];
  657. unset(self::$routes[$which]);
  658. array_unshift(self::$routes, $route);
  659. return true;
  660. }
  661. /**
  662. * Finds URL for specified action.
  663. *
  664. * Returns an URL pointing to a combination of controller and action. Param
  665. * $url can be:
  666. *
  667. * - Empty - the method will find address to actual controller/action.
  668. * - '/' - the method will find base URL of application.
  669. * - A combination of controller/action - the method will find url for it.
  670. *
  671. * There are a few 'special' parameters that can change the final URL string that is generated
  672. *
  673. * - `base` - Set to false to remove the base path from the generated url. If your application
  674. * is not in the root directory, this can be used to generate urls that are 'cake relative'.
  675. * cake relative urls are required when using requestAction.
  676. * - `?` - Takes an array of query string parameters
  677. * - `#` - Allows you to set url hash fragments.
  678. * - `full_base` - If true the `FULL_BASE_URL` constant will be prepended to generated urls.
  679. *
  680. * @param mixed $url Cake-relative URL, like "/products/edit/92" or "/presidents/elect/4"
  681. * or an array specifying any of the following: 'controller', 'action',
  682. * and/or 'plugin', in addition to named arguments (keyed array elements),
  683. * and standard URL arguments (indexed array elements)
  684. * @param mixed $full If (bool) true, the full base URL will be prepended to the result.
  685. * If an array accepts the following keys
  686. * - escape - used when making urls embedded in html escapes query string '&'
  687. * - full - if true the full base URL will be prepended.
  688. * @return string Full translated URL with base path.
  689. */
  690. public static function url($url = null, $full = false) {
  691. $params = array('plugin' => null, 'controller' => null, 'action' => 'index');
  692. if (is_bool($full)) {
  693. $escape = false;
  694. } else {
  695. extract($full + array('escape' => false, 'full' => false));
  696. }
  697. $path = array('base' => null);
  698. if (!empty(self::$_requests)) {
  699. $request = self::$_requests[count(self::$_requests) - 1];
  700. $params = $request->params;
  701. $path = array('base' => $request->base, 'here' => $request->here);
  702. }
  703. $base = $path['base'];
  704. $extension = $output = $q = $frag = null;
  705. if (empty($url)) {
  706. $output = isset($path['here']) ? $path['here'] : '/';
  707. if ($full && defined('FULL_BASE_URL')) {
  708. $output = FULL_BASE_URL . $output;
  709. }
  710. return $output;
  711. } elseif (is_array($url)) {
  712. if (isset($url['base']) && $url['base'] === false) {
  713. $base = null;
  714. unset($url['base']);
  715. }
  716. if (isset($url['full_base']) && $url['full_base'] === true) {
  717. $full = true;
  718. unset($url['full_base']);
  719. }
  720. if (isset($url['?'])) {
  721. $q = $url['?'];
  722. unset($url['?']);
  723. }
  724. if (isset($url['#'])) {
  725. $frag = '#' . $url['#'];
  726. unset($url['#']);
  727. }
  728. if (isset($url['ext'])) {
  729. $extension = '.' . $url['ext'];
  730. unset($url['ext']);
  731. }
  732. if (empty($url['action'])) {
  733. if (empty($url['controller']) || $params['controller'] === $url['controller']) {
  734. $url['action'] = $params['action'];
  735. } else {
  736. $url['action'] = 'index';
  737. }
  738. }
  739. $prefixExists = (array_intersect_key($url, array_flip(self::$_prefixes)));
  740. foreach (self::$_prefixes as $prefix) {
  741. if (!empty($params[$prefix]) && !$prefixExists) {
  742. $url[$prefix] = true;
  743. } elseif (isset($url[$prefix]) && !$url[$prefix]) {
  744. unset($url[$prefix]);
  745. }
  746. if (isset($url[$prefix]) && strpos($url['action'], $prefix . '_') === 0) {
  747. $url['action'] = substr($url['action'], strlen($prefix) + 1);
  748. }
  749. }
  750. $url += array('controller' => $params['controller'], 'plugin' => $params['plugin']);
  751. $match = false;
  752. for ($i = 0, $len = count(self::$routes); $i < $len; $i++) {
  753. $originalUrl = $url;
  754. if (isset(self::$routes[$i]->options['persist'], $params)) {
  755. $url = self::$routes[$i]->persistParams($url, $params);
  756. }
  757. if ($match = self::$routes[$i]->match($url)) {
  758. $output = trim($match, '/');
  759. break;
  760. }
  761. $url = $originalUrl;
  762. }
  763. if ($match === false) {
  764. $output = self::_handleNoRoute($url);
  765. }
  766. } else {
  767. if (
  768. (strpos($url, '://') !== false ||
  769. (strpos($url, 'javascript:') === 0) ||
  770. (strpos($url, 'mailto:') === 0)) ||
  771. (!strncmp($url, '#', 1))
  772. ) {
  773. return $url;
  774. }
  775. if (substr($url, 0, 1) === '/') {
  776. $output = substr($url, 1);
  777. } else {
  778. foreach (self::$_prefixes as $prefix) {
  779. if (isset($params[$prefix])) {
  780. $output .= $prefix . '/';
  781. break;
  782. }
  783. }
  784. if (!empty($params['plugin']) && $params['plugin'] !== $params['controller']) {
  785. $output .= Inflector::underscore($params['plugin']) . '/';
  786. }
  787. $output .= Inflector::underscore($params['controller']) . '/' . $url;
  788. }
  789. }
  790. $protocol = preg_match('#^[a-z][a-z0-9+-.]*\://#i', $output);
  791. if ($protocol === 0) {
  792. $output = str_replace('//', '/', $base . '/' . $output);
  793. if ($full && defined('FULL_BASE_URL')) {
  794. $output = FULL_BASE_URL . $output;
  795. }
  796. if (!empty($extension)) {
  797. $output = rtrim($output, '/');
  798. }
  799. }
  800. return $output . $extension . self::queryString($q, array(), $escape) . $frag;
  801. }
  802. /**
  803. * A special fallback method that handles url arrays that cannot match
  804. * any defined routes.
  805. *
  806. * @param array $url A url that didn't match any routes
  807. * @return string A generated url for the array
  808. * @see Router::url()
  809. */
  810. protected static function _handleNoRoute($url) {
  811. $named = $args = array();
  812. $skip = array_merge(
  813. array('bare', 'action', 'controller', 'plugin', 'prefix'),
  814. self::$_prefixes
  815. );
  816. $keys = array_values(array_diff(array_keys($url), $skip));
  817. $count = count($keys);
  818. // Remove this once parsed URL parameters can be inserted into 'pass'
  819. for ($i = 0; $i < $count; $i++) {
  820. $key = $keys[$i];
  821. if (is_numeric($keys[$i])) {
  822. $args[] = $url[$key];
  823. } else {
  824. $named[$key] = $url[$key];
  825. }
  826. }
  827. list($args, $named) = array(Set::filter($args, true), Set::filter($named, true));
  828. foreach (self::$_prefixes as $prefix) {
  829. $prefixed = $prefix . '_';
  830. if (!empty($url[$prefix]) && strpos($url['action'], $prefixed) === 0) {
  831. $url['action'] = substr($url['action'], strlen($prefixed) * -1);
  832. break;
  833. }
  834. }
  835. if (empty($named) && empty($args) && (!isset($url['action']) || $url['action'] === 'index')) {
  836. $url['action'] = null;
  837. }
  838. $urlOut = array_filter(array($url['controller'], $url['action']));
  839. if (isset($url['plugin'])) {
  840. array_unshift($urlOut, $url['plugin']);
  841. }
  842. foreach (self::$_prefixes as $prefix) {
  843. if (isset($url[$prefix])) {
  844. array_unshift($urlOut, $prefix);
  845. break;
  846. }
  847. }
  848. $output = implode('/', $urlOut);
  849. if (!empty($args)) {
  850. $output .= '/' . implode('/', array_map('rawurlencode', $args));
  851. }
  852. if (!empty($named)) {
  853. foreach ($named as $name => $value) {
  854. if (is_array($value)) {
  855. $flattend = Set::flatten($value, '][');
  856. foreach ($flattend as $namedKey => $namedValue) {
  857. $output .= '/' . $name . "[$namedKey]" . self::$_namedConfig['separator'] . rawurlencode($namedValue);
  858. }
  859. } else {
  860. $output .= '/' . $name . self::$_namedConfig['separator'] . rawurlencode($value);
  861. }
  862. }
  863. }
  864. return $output;
  865. }
  866. /**
  867. * Generates a well-formed querystring from $q
  868. *
  869. * @param string|array $q Query string Either a string of already compiled query string arguments or
  870. * an array of arguments to convert into a query string.
  871. * @param array $extra Extra querystring parameters.
  872. * @param boolean $escape Whether or not to use escaped &
  873. * @return array
  874. */
  875. public static function queryString($q, $extra = array(), $escape = false) {
  876. if (empty($q) && empty($extra)) {
  877. return null;
  878. }
  879. $join = '&';
  880. if ($escape === true) {
  881. $join = '&amp;';
  882. }
  883. $out = '';
  884. if (is_array($q)) {
  885. $q = array_merge($q, $extra);
  886. } else {
  887. $out = $q;
  888. $q = $extra;
  889. }
  890. $addition = http_build_query($q, null, $join);
  891. if ($out && $addition && substr($out, strlen($join) * -1, strlen($join)) != $join) {
  892. $out .= $join;
  893. }
  894. $out .= $addition;
  895. if (isset($out[0]) && $out[0] != '?') {
  896. $out = '?' . $out;
  897. }
  898. return $out;
  899. }
  900. /**
  901. * Reverses a parsed parameter array into a string. Works similarly to Router::url(), but
  902. * Since parsed URL's contain additional 'pass' and 'named' as well as 'url.url' keys.
  903. * Those keys need to be specially handled in order to reverse a params array into a string url.
  904. *
  905. * This will strip out 'autoRender', 'bare', 'requested', and 'return' param names as those
  906. * are used for CakePHP internals and should not normally be part of an output url.
  907. *
  908. * @param CakeRequest|array $params The params array or CakeRequest object that needs to be reversed.
  909. * @param boolean $full Set to true to include the full url including the protocol when reversing
  910. * the url.
  911. * @return string The string that is the reversed result of the array
  912. */
  913. public static function reverse($params, $full = false) {
  914. if ($params instanceof CakeRequest) {
  915. $url = $params->query;
  916. $params = $params->params;
  917. } else {
  918. $url = $params['url'];
  919. }
  920. $pass = isset($params['pass']) ? $params['pass'] : array();
  921. $named = isset($params['named']) ? $params['named'] : array();
  922. unset(
  923. $params['pass'], $params['named'], $params['paging'], $params['models'], $params['url'], $url['url'],
  924. $params['autoRender'], $params['bare'], $params['requested'], $params['return'],
  925. $params['_Token']
  926. );
  927. $params = array_merge($params, $pass, $named);
  928. if (!empty($url)) {
  929. $params['?'] = $url;
  930. }
  931. return Router::url($params, $full);
  932. }
  933. /**
  934. * Normalizes a URL for purposes of comparison. Will strip the base path off
  935. * and replace any double /'s. It will not unify the casing and underscoring
  936. * of the input value.
  937. *
  938. * @param mixed $url URL to normalize Either an array or a string url.
  939. * @return string Normalized URL
  940. */
  941. public static function normalize($url = '/') {
  942. if (is_array($url)) {
  943. $url = Router::url($url);
  944. }
  945. if (preg_match('/^[a-z\-]+:\/\//', $url)) {
  946. return $url;
  947. }
  948. $request = Router::getRequest();
  949. if (!empty($request->base) && stristr($url, $request->base)) {
  950. $url = preg_replace('/^' . preg_quote($request->base, '/') . '/', '', $url, 1);
  951. }
  952. $url = '/' . $url;
  953. while (strpos($url, '//') !== false) {
  954. $url = str_replace('//', '/', $url);
  955. }
  956. $url = preg_replace('/(?:(\/$))/', '', $url);
  957. if (empty($url)) {
  958. return '/';
  959. }
  960. return $url;
  961. }
  962. /**
  963. * Returns the route matching the current request URL.
  964. *
  965. * @return CakeRoute Matching route object.
  966. */
  967. public static function &requestRoute() {
  968. return self::$_currentRoute[0];
  969. }
  970. /**
  971. * Returns the route matching the current request (useful for requestAction traces)
  972. *
  973. * @return CakeRoute Matching route object.
  974. */
  975. public static function &currentRoute() {
  976. return self::$_currentRoute[count(self::$_currentRoute) - 1];
  977. }
  978. /**
  979. * Removes the plugin name from the base URL.
  980. *
  981. * @param string $base Base URL
  982. * @param string $plugin Plugin name
  983. * @return string base url with plugin name removed if present
  984. */
  985. public static function stripPlugin($base, $plugin = null) {
  986. if ($plugin != null) {
  987. $base = preg_replace('/(?:' . $plugin . ')/', '', $base);
  988. $base = str_replace('//', '', $base);
  989. $pos1 = strrpos($base, '/');
  990. $char = strlen($base) - 1;
  991. if ($pos1 === $char) {
  992. $base = substr($base, 0, $char);
  993. }
  994. }
  995. return $base;
  996. }
  997. /**
  998. * Instructs the router to parse out file extensions from the URL. For example,
  999. * http://example.com/posts.rss would yield an file extension of "rss".
  1000. * The file extension itself is made available in the controller as
  1001. * `$this->params['ext']`, and is used by the RequestHandler component to
  1002. * automatically switch to alternate layouts and templates, and load helpers
  1003. * corresponding to the given content, i.e. RssHelper. Switching layouts and helpers
  1004. * requires that the chosen extension has a defined mime type in `CakeResponse`
  1005. *
  1006. * A list of valid extension can be passed to this method, i.e. Router::parseExtensions('rss', 'xml');
  1007. * If no parameters are given, anything after the first . (dot) after the last / in the URL will be
  1008. * parsed, excluding querystring parameters (i.e. ?q=...).
  1009. *
  1010. * @return void
  1011. * @see RequestHandler::startup()
  1012. */
  1013. public static function parseExtensions() {
  1014. self::$_parseExtensions = true;
  1015. if (func_num_args() > 0) {
  1016. self::$_validExtensions = func_get_args();
  1017. }
  1018. }
  1019. /**
  1020. * Get the list of extensions that can be parsed by Router. To add more
  1021. * extensions use Router::parseExtensions()
  1022. *
  1023. * @return array Array of extensions Router is configured to parse.
  1024. */
  1025. public static function extensions() {
  1026. return self::$_validExtensions;
  1027. }
  1028. }
  1029. //Save the initial state
  1030. Router::reload();