PageRenderTime 60ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Routing/Router.php

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