Router.php 36 KB

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