PageRenderTime 1059ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Routing/Router.php

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