Router.php 34 KB

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