Router.php 40 KB

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