PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Routing/Router.php

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