Router.php 38 KB

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