PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/code/ryzom/tools/server/www/webtt/cake/libs/router.php

https://bitbucket.org/SirCotare/ryzom
PHP | 1648 lines | 844 code | 131 blank | 673 comment | 203 complexity | 7fbef4840ec229ac8281e3dbceb56abb MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Parses the request URL into controller, action, and parameters.
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake
  16. * @subpackage cake.cake.libs
  17. * @since CakePHP(tm) v 0.2.9
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. /**
  21. * Parses the request URL into controller, action, and parameters.
  22. *
  23. * @package cake
  24. * @subpackage cake.cake.libs
  25. */
  26. class Router {
  27. /**
  28. * Array of routes connected with Router::connect()
  29. *
  30. * @var array
  31. * @access public
  32. */
  33. var $routes = array();
  34. /**
  35. * List of action prefixes used in connected routes.
  36. * Includes admin prefix
  37. *
  38. * @var array
  39. * @access private
  40. */
  41. var $__prefixes = array();
  42. /**
  43. * Directive for Router to parse out file extensions for mapping to Content-types.
  44. *
  45. * @var boolean
  46. * @access private
  47. */
  48. var $__parseExtensions = false;
  49. /**
  50. * List of valid extensions to parse from a URL. If null, any extension is allowed.
  51. *
  52. * @var array
  53. * @access private
  54. */
  55. var $__validExtensions = null;
  56. /**
  57. * 'Constant' regular expression definitions for named route elements
  58. *
  59. * @var array
  60. * @access private
  61. */
  62. var $__named = array(
  63. 'Action' => 'index|show|add|create|edit|update|remove|del|delete|view|item',
  64. 'Year' => '[12][0-9]{3}',
  65. 'Month' => '0[1-9]|1[012]',
  66. 'Day' => '0[1-9]|[12][0-9]|3[01]',
  67. 'ID' => '[0-9]+',
  68. '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}'
  69. );
  70. /**
  71. * Stores all information necessary to decide what named arguments are parsed under what conditions.
  72. *
  73. * @var string
  74. * @access public
  75. */
  76. var $named = array(
  77. 'default' => array('page', 'fields', 'order', 'limit', 'recursive', 'sort', 'direction', 'step'),
  78. 'greedy' => true,
  79. 'separator' => ':',
  80. 'rules' => false,
  81. );
  82. /**
  83. * The route matching the URL of the current request
  84. *
  85. * @var array
  86. * @access private
  87. */
  88. var $__currentRoute = array();
  89. /**
  90. * Default HTTP request method => controller action map.
  91. *
  92. * @var array
  93. * @access private
  94. */
  95. var $__resourceMap = array(
  96. array('action' => 'index', 'method' => 'GET', 'id' => false),
  97. array('action' => 'view', 'method' => 'GET', 'id' => true),
  98. array('action' => 'add', 'method' => 'POST', 'id' => false),
  99. array('action' => 'edit', 'method' => 'PUT', 'id' => true),
  100. array('action' => 'delete', 'method' => 'DELETE', 'id' => true),
  101. array('action' => 'edit', 'method' => 'POST', 'id' => true)
  102. );
  103. /**
  104. * List of resource-mapped controllers
  105. *
  106. * @var array
  107. * @access private
  108. */
  109. var $__resourceMapped = array();
  110. /**
  111. * Maintains the parameter stack for the current request
  112. *
  113. * @var array
  114. * @access private
  115. */
  116. var $__params = array();
  117. /**
  118. * Maintains the path stack for the current request
  119. *
  120. * @var array
  121. * @access private
  122. */
  123. var $__paths = array();
  124. /**
  125. * Keeps Router state to determine if default routes have already been connected
  126. *
  127. * @var boolean
  128. * @access private
  129. */
  130. var $__defaultsMapped = false;
  131. /**
  132. * Keeps track of whether the connection of default routes is enabled or disabled.
  133. *
  134. * @var boolean
  135. * @access private
  136. */
  137. var $__connectDefaults = true;
  138. /**
  139. * Constructor for Router.
  140. * Builds __prefixes
  141. *
  142. * @return void
  143. */
  144. function Router() {
  145. $this->__setPrefixes();
  146. }
  147. /**
  148. * Sets the Routing prefixes. Includes compatibility for existing Routing.admin
  149. * configurations.
  150. *
  151. * @return void
  152. * @access private
  153. * @todo Remove support for Routing.admin in future versions.
  154. */
  155. function __setPrefixes() {
  156. $routing = Configure::read('Routing');
  157. if (!empty($routing['admin'])) {
  158. $this->__prefixes[] = $routing['admin'];
  159. }
  160. if (!empty($routing['prefixes'])) {
  161. $this->__prefixes = array_merge($this->__prefixes, (array)$routing['prefixes']);
  162. }
  163. }
  164. /**
  165. * Gets a reference to the Router object instance
  166. *
  167. * @return Router Instance of the Router.
  168. * @access public
  169. * @static
  170. */
  171. function &getInstance() {
  172. static $instance = array();
  173. if (!$instance) {
  174. $instance[0] =& new Router();
  175. }
  176. return $instance[0];
  177. }
  178. /**
  179. * Gets the named route elements for use in app/config/routes.php
  180. *
  181. * @return array Named route elements
  182. * @access public
  183. * @see Router::$__named
  184. * @static
  185. */
  186. function getNamedExpressions() {
  187. $self =& Router::getInstance();
  188. return $self->__named;
  189. }
  190. /**
  191. * Connects a new Route in the router.
  192. *
  193. * Routes are a way of connecting request urls to objects in your application. At their core routes
  194. * are a set or regular expressions that are used to match requests to destinations.
  195. *
  196. * Examples:
  197. *
  198. * `Router::connect('/:controller/:action/*');`
  199. *
  200. * The first parameter will be used as a controller name while the second is used as the action name.
  201. * the '/*' syntax makes this route greedy in that it will match requests like `/posts/index` as well as requests
  202. * like `/posts/edit/1/foo/bar`.
  203. *
  204. * `Router::connect('/home-page', array('controller' => 'pages', 'action' => 'display', 'home'));`
  205. *
  206. * The above shows the use of route parameter defaults. And providing routing parameters for a static route.
  207. *
  208. * {{{
  209. * Router::connect(
  210. * '/:lang/:controller/:action/:id',
  211. * array(),
  212. * array('id' => '[0-9]+', 'lang' => '[a-z]{3}')
  213. * );
  214. * }}}
  215. *
  216. * Shows connecting a route with custom route parameters as well as providing patterns for those parameters.
  217. * Patterns for routing parameters do not need capturing groups, as one will be added for each route params.
  218. *
  219. * $options offers three 'special' keys. `pass`, `persist` and `routeClass` have special meaning in the $options array.
  220. *
  221. * `pass` is used to define which of the routed parameters should be shifted into the pass array. Adding a
  222. * parameter to pass will remove it from the regular route array. Ex. `'pass' => array('slug')`
  223. *
  224. * `persist` is used to define which route parameters should be automatically included when generating
  225. * new urls. You can override persistent parameters by redefining them in a url or remove them by
  226. * setting the parameter to `false`. Ex. `'persist' => array('lang')`
  227. *
  228. * `routeClass` is used to extend and change how individual routes parse requests and handle reverse routing,
  229. * via a custom routing class. Ex. `'routeClass' => 'SlugRoute'`
  230. *
  231. * @param string $route A string describing the template of the route
  232. * @param array $defaults An array describing the default route parameters. These parameters will be used by default
  233. * and can supply routing parameters that are not dynamic. See above.
  234. * @param array $options An array matching the named elements in the route to regular expressions which that
  235. * element should match. Also contains additional parameters such as which routed parameters should be
  236. * shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a
  237. * custom routing class.
  238. * @see routes
  239. * @return array Array of routes
  240. * @access public
  241. * @static
  242. */
  243. function connect($route, $defaults = array(), $options = array()) {
  244. $self =& Router::getInstance();
  245. foreach ($self->__prefixes as $prefix) {
  246. if (isset($defaults[$prefix])) {
  247. $defaults['prefix'] = $prefix;
  248. break;
  249. }
  250. }
  251. if (isset($defaults['prefix'])) {
  252. $self->__prefixes[] = $defaults['prefix'];
  253. $self->__prefixes = array_keys(array_flip($self->__prefixes));
  254. }
  255. $defaults += array('plugin' => null);
  256. if (empty($options['action'])) {
  257. $defaults += array('action' => 'index');
  258. }
  259. $routeClass = 'CakeRoute';
  260. if (isset($options['routeClass'])) {
  261. $routeClass = $options['routeClass'];
  262. unset($options['routeClass']);
  263. }
  264. //TODO 2.0 refactor this to use a string class name, throw exception, and then construct.
  265. $Route =& new $routeClass($route, $defaults, $options);
  266. if ($routeClass !== 'CakeRoute' && !is_subclass_of($Route, 'CakeRoute')) {
  267. trigger_error(__('Route classes must extend CakeRoute', true), E_USER_WARNING);
  268. return false;
  269. }
  270. $self->routes[] =& $Route;
  271. return $self->routes;
  272. }
  273. /**
  274. * Specifies what named parameters CakePHP should be parsing. The most common setups are:
  275. *
  276. * Do not parse any named parameters:
  277. *
  278. * {{{ Router::connectNamed(false); }}}
  279. *
  280. * Parse only default parameters used for CakePHP's pagination:
  281. *
  282. * {{{ Router::connectNamed(false, array('default' => true)); }}}
  283. *
  284. * Parse only the page parameter if its value is a number:
  285. *
  286. * {{{ Router::connectNamed(array('page' => '[\d]+'), array('default' => false, 'greedy' => false)); }}}
  287. *
  288. * Parse only the page parameter no mater what.
  289. *
  290. * {{{ Router::connectNamed(array('page'), array('default' => false, 'greedy' => false)); }}}
  291. *
  292. * Parse only the page parameter if the current action is 'index'.
  293. *
  294. * {{{
  295. * Router::connectNamed(
  296. * array('page' => array('action' => 'index')),
  297. * array('default' => false, 'greedy' => false)
  298. * );
  299. * }}}
  300. *
  301. * Parse only the page parameter if the current action is 'index' and the controller is 'pages'.
  302. *
  303. * {{{
  304. * Router::connectNamed(
  305. * array('page' => array('action' => 'index', 'controller' => 'pages')),
  306. * array('default' => false, 'greedy' => false)
  307. * );
  308. * }}}
  309. *
  310. * @param array $named A list of named parameters. Key value pairs are accepted where values are
  311. * either regex strings to match, or arrays as seen above.
  312. * @param array $options Allows to control all settings: separator, greedy, reset, default
  313. * @return array
  314. * @access public
  315. * @static
  316. */
  317. function connectNamed($named, $options = array()) {
  318. $self =& Router::getInstance();
  319. if (isset($options['argSeparator'])) {
  320. $self->named['separator'] = $options['argSeparator'];
  321. unset($options['argSeparator']);
  322. }
  323. if ($named === true || $named === false) {
  324. $options = array_merge(array('default' => $named, 'reset' => true, 'greedy' => $named), $options);
  325. $named = array();
  326. } else {
  327. $options = array_merge(array('default' => false, 'reset' => false, 'greedy' => true), $options);
  328. }
  329. if ($options['reset'] == true || $self->named['rules'] === false) {
  330. $self->named['rules'] = array();
  331. }
  332. if ($options['default']) {
  333. $named = array_merge($named, $self->named['default']);
  334. }
  335. foreach ($named as $key => $val) {
  336. if (is_numeric($key)) {
  337. $self->named['rules'][$val] = true;
  338. } else {
  339. $self->named['rules'][$key] = $val;
  340. }
  341. }
  342. $self->named['greedy'] = $options['greedy'];
  343. return $self->named;
  344. }
  345. /**
  346. * Tell router to connect or not connect the default routes.
  347. *
  348. * If default routes are disabled all automatic route generation will be disabled
  349. * and you will need to manually configure all the routes you want.
  350. *
  351. * @param boolean $connect Set to true or false depending on whether you want or don't want default routes.
  352. * @return void
  353. * @access public
  354. * @static
  355. */
  356. function defaults($connect = true) {
  357. $self =& Router::getInstance();
  358. $self->__connectDefaults = $connect;
  359. }
  360. /**
  361. * Creates REST resource routes for the given controller(s)
  362. *
  363. * ### Options:
  364. *
  365. * - 'id' - The regular expression fragment to use when matching IDs. By default, matches
  366. * integer values and UUIDs.
  367. * - 'prefix' - URL prefix to use for the generated routes. Defaults to '/'.
  368. *
  369. * @param mixed $controller A controller name or array of controller names (i.e. "Posts" or "ListItems")
  370. * @param array $options Options to use when generating REST routes
  371. * @return void
  372. * @access public
  373. * @static
  374. */
  375. function mapResources($controller, $options = array()) {
  376. $self =& Router::getInstance();
  377. $options = array_merge(array('prefix' => '/', 'id' => $self->__named['ID'] . '|' . $self->__named['UUID']), $options);
  378. $prefix = $options['prefix'];
  379. foreach ((array)$controller as $ctlName) {
  380. $urlName = Inflector::underscore($ctlName);
  381. foreach ($self->__resourceMap as $params) {
  382. extract($params);
  383. $url = $prefix . $urlName . (($id) ? '/:id' : '');
  384. Router::connect($url,
  385. array('controller' => $urlName, 'action' => $action, '[method]' => $params['method']),
  386. array('id' => $options['id'], 'pass' => array('id'))
  387. );
  388. }
  389. $self->__resourceMapped[] = $urlName;
  390. }
  391. }
  392. /**
  393. * Returns the list of prefixes used in connected routes
  394. *
  395. * @return array A list of prefixes used in connected routes
  396. * @access public
  397. * @static
  398. */
  399. function prefixes() {
  400. $self =& Router::getInstance();
  401. return $self->__prefixes;
  402. }
  403. /**
  404. * Parses given URL and returns an array of controller, action and parameters
  405. * taken from that URL.
  406. *
  407. * @param string $url URL to be parsed
  408. * @return array Parsed elements from URL
  409. * @access public
  410. * @static
  411. */
  412. function parse($url) {
  413. $self =& Router::getInstance();
  414. if (!$self->__defaultsMapped && $self->__connectDefaults) {
  415. $self->__connectDefaultRoutes();
  416. }
  417. $out = array(
  418. 'pass' => array(),
  419. 'named' => array(),
  420. );
  421. $r = $ext = null;
  422. if (ini_get('magic_quotes_gpc') === '1') {
  423. $url = stripslashes_deep($url);
  424. }
  425. if ($url && strpos($url, '/') !== 0) {
  426. $url = '/' . $url;
  427. }
  428. if (strpos($url, '?') !== false) {
  429. $url = substr($url, 0, strpos($url, '?'));
  430. }
  431. extract($self->__parseExtension($url));
  432. for ($i = 0, $len = count($self->routes); $i < $len; $i++) {
  433. $route =& $self->routes[$i];
  434. if (($r = $route->parse($url)) !== false) {
  435. $self->__currentRoute[] =& $route;
  436. $params = $route->options;
  437. $argOptions = array();
  438. if (array_key_exists('named', $params)) {
  439. $argOptions['named'] = $params['named'];
  440. unset($params['named']);
  441. }
  442. if (array_key_exists('greedy', $params)) {
  443. $argOptions['greedy'] = $params['greedy'];
  444. unset($params['greedy']);
  445. }
  446. $out = $r;
  447. if (isset($out['_args_'])) {
  448. $argOptions['context'] = array('action' => $out['action'], 'controller' => $out['controller']);
  449. $parsedArgs = $self->getArgs($out['_args_'], $argOptions);
  450. $out['pass'] = array_merge($out['pass'], $parsedArgs['pass']);
  451. $out['named'] = $parsedArgs['named'];
  452. unset($out['_args_']);
  453. }
  454. if (isset($params['pass'])) {
  455. $j = count($params['pass']);
  456. while($j--) {
  457. if (isset($out[$params['pass'][$j]])) {
  458. array_unshift($out['pass'], $out[$params['pass'][$j]]);
  459. }
  460. }
  461. }
  462. break;
  463. }
  464. }
  465. if (!empty($ext) && !isset($out['url']['ext'])) {
  466. $out['url']['ext'] = $ext;
  467. }
  468. return $out;
  469. }
  470. /**
  471. * Parses a file extension out of a URL, if Router::parseExtensions() is enabled.
  472. *
  473. * @param string $url
  474. * @return array Returns an array containing the altered URL and the parsed extension.
  475. * @access private
  476. */
  477. function __parseExtension($url) {
  478. $ext = null;
  479. if ($this->__parseExtensions) {
  480. if (preg_match('/\.[0-9a-zA-Z]*$/', $url, $match) === 1) {
  481. $match = substr($match[0], 1);
  482. if (empty($this->__validExtensions)) {
  483. $url = substr($url, 0, strpos($url, '.' . $match));
  484. $ext = $match;
  485. } else {
  486. foreach ($this->__validExtensions as $name) {
  487. if (strcasecmp($name, $match) === 0) {
  488. $url = substr($url, 0, strpos($url, '.' . $name));
  489. $ext = $match;
  490. break;
  491. }
  492. }
  493. }
  494. }
  495. if (empty($ext)) {
  496. $ext = 'html';
  497. }
  498. }
  499. return compact('ext', 'url');
  500. }
  501. /**
  502. * Connects the default, built-in routes, including prefix and plugin routes. The following routes are created
  503. * in the order below:
  504. *
  505. * For each of the Routing.prefixes the following routes are created. Routes containing `:plugin` are only
  506. * created when your application has one or more plugins.
  507. *
  508. * - `/:prefix/:plugin` a plugin shortcut route.
  509. * - `/:prefix/:plugin/:action/*` a plugin shortcut route.
  510. * - `/:prefix/:plugin/:controller`
  511. * - `/:prefix/:plugin/:controller/:action/*`
  512. * - `/:prefix/:controller`
  513. * - `/:prefix/:controller/:action/*`
  514. *
  515. * If plugins are found in your application the following routes are created:
  516. *
  517. * - `/:plugin` a plugin shortcut route.
  518. * - `/:plugin/:action/*` a plugin shortcut route.
  519. * - `/:plugin/:controller`
  520. * - `/:plugin/:controller/:action/*`
  521. *
  522. * And lastly the following catch-all routes are connected.
  523. *
  524. * - `/:controller'
  525. * - `/:controller/:action/*'
  526. *
  527. * You can disable the connection of default routes with Router::defaults().
  528. *
  529. * @return void
  530. * @access private
  531. */
  532. function __connectDefaultRoutes() {
  533. if ($plugins = App::objects('plugin')) {
  534. foreach ($plugins as $key => $value) {
  535. $plugins[$key] = Inflector::underscore($value);
  536. }
  537. $pluginPattern = implode('|', $plugins);
  538. $match = array('plugin' => $pluginPattern);
  539. $shortParams = array('routeClass' => 'PluginShortRoute', 'plugin' => $pluginPattern);
  540. foreach ($this->__prefixes as $prefix) {
  541. $params = array('prefix' => $prefix, $prefix => true);
  542. $indexParams = $params + array('action' => 'index');
  543. $this->connect("/{$prefix}/:plugin", $indexParams, $shortParams);
  544. $this->connect("/{$prefix}/:plugin/:controller", $indexParams, $match);
  545. $this->connect("/{$prefix}/:plugin/:controller/:action/*", $params, $match);
  546. }
  547. $this->connect('/:plugin', array('action' => 'index'), $shortParams);
  548. $this->connect('/:plugin/:controller', array('action' => 'index'), $match);
  549. $this->connect('/:plugin/:controller/:action/*', array(), $match);
  550. }
  551. foreach ($this->__prefixes as $prefix) {
  552. $params = array('prefix' => $prefix, $prefix => true);
  553. $indexParams = $params + array('action' => 'index');
  554. $this->connect("/{$prefix}/:controller", $indexParams);
  555. $this->connect("/{$prefix}/:controller/:action/*", $params);
  556. }
  557. $this->connect('/:controller', array('action' => 'index'));
  558. $this->connect('/:controller/:action/*');
  559. if ($this->named['rules'] === false) {
  560. $this->connectNamed(true);
  561. }
  562. $this->__defaultsMapped = true;
  563. }
  564. /**
  565. * Takes parameter and path information back from the Dispatcher, sets these
  566. * parameters as the current request parameters that are merged with url arrays
  567. * created later in the request.
  568. *
  569. * @param array $params Parameters and path information
  570. * @return void
  571. * @access public
  572. * @static
  573. */
  574. function setRequestInfo($params) {
  575. $self =& Router::getInstance();
  576. $defaults = array('plugin' => null, 'controller' => null, 'action' => null);
  577. $params[0] = array_merge($defaults, (array)$params[0]);
  578. $params[1] = array_merge($defaults, (array)$params[1]);
  579. list($self->__params[], $self->__paths[]) = $params;
  580. if (count($self->__paths)) {
  581. if (isset($self->__paths[0]['namedArgs'])) {
  582. foreach ($self->__paths[0]['namedArgs'] as $arg => $value) {
  583. $self->named['rules'][$arg] = true;
  584. }
  585. }
  586. }
  587. }
  588. /**
  589. * Gets parameter information
  590. *
  591. * @param boolean $current Get current request parameter, useful when using requestAction
  592. * @return array Parameter information
  593. * @access public
  594. * @static
  595. */
  596. function getParams($current = false) {
  597. $self =& Router::getInstance();
  598. if ($current) {
  599. return $self->__params[count($self->__params) - 1];
  600. }
  601. if (isset($self->__params[0])) {
  602. return $self->__params[0];
  603. }
  604. return array();
  605. }
  606. /**
  607. * Gets URL parameter by name
  608. *
  609. * @param string $name Parameter name
  610. * @param boolean $current Current parameter, useful when using requestAction
  611. * @return string Parameter value
  612. * @access public
  613. * @static
  614. */
  615. function getParam($name = 'controller', $current = false) {
  616. $params = Router::getParams($current);
  617. if (isset($params[$name])) {
  618. return $params[$name];
  619. }
  620. return null;
  621. }
  622. /**
  623. * Gets path information
  624. *
  625. * @param boolean $current Current parameter, useful when using requestAction
  626. * @return array
  627. * @access public
  628. * @static
  629. */
  630. function getPaths($current = false) {
  631. $self =& Router::getInstance();
  632. if ($current) {
  633. return $self->__paths[count($self->__paths) - 1];
  634. }
  635. if (!isset($self->__paths[0])) {
  636. return array('base' => null);
  637. }
  638. return $self->__paths[0];
  639. }
  640. /**
  641. * Reloads default Router settings. Resets all class variables and
  642. * removes all connected routes.
  643. *
  644. * @access public
  645. * @return void
  646. * @static
  647. */
  648. function reload() {
  649. $self =& Router::getInstance();
  650. foreach (get_class_vars('Router') as $key => $val) {
  651. $self->{$key} = $val;
  652. }
  653. $self->__setPrefixes();
  654. }
  655. /**
  656. * Promote a route (by default, the last one added) to the beginning of the list
  657. *
  658. * @param $which A zero-based array index representing the route to move. For example,
  659. * if 3 routes have been added, the last route would be 2.
  660. * @return boolean Returns false if no route exists at the position specified by $which.
  661. * @access public
  662. * @static
  663. */
  664. function promote($which = null) {
  665. $self =& Router::getInstance();
  666. if ($which === null) {
  667. $which = count($self->routes) - 1;
  668. }
  669. if (!isset($self->routes[$which])) {
  670. return false;
  671. }
  672. $route =& $self->routes[$which];
  673. unset($self->routes[$which]);
  674. array_unshift($self->routes, $route);
  675. return true;
  676. }
  677. /**
  678. * Finds URL for specified action.
  679. *
  680. * Returns an URL pointing to a combination of controller and action. Param
  681. * $url can be:
  682. *
  683. * - Empty - the method will find address to actual controller/action.
  684. * - '/' - the method will find base URL of application.
  685. * - A combination of controller/action - the method will find url for it.
  686. *
  687. * There are a few 'special' parameters that can change the final URL string that is generated
  688. *
  689. * - `base` - Set to false to remove the base path from the generated url. If your application
  690. * is not in the root directory, this can be used to generate urls that are 'cake relative'.
  691. * cake relative urls are required when using requestAction.
  692. * - `?` - Takes an array of query string parameters
  693. * - `#` - Allows you to set url hash fragments.
  694. * - `full_base` - If true the `FULL_BASE_URL` constant will be prepended to generated urls.
  695. *
  696. * @param mixed $url Cake-relative URL, like "/products/edit/92" or "/presidents/elect/4"
  697. * or an array specifying any of the following: 'controller', 'action',
  698. * and/or 'plugin', in addition to named arguments (keyed array elements),
  699. * and standard URL arguments (indexed array elements)
  700. * @param mixed $full If (bool) true, the full base URL will be prepended to the result.
  701. * If an array accepts the following keys
  702. * - escape - used when making urls embedded in html escapes query string '&'
  703. * - full - if true the full base URL will be prepended.
  704. * @return string Full translated URL with base path.
  705. * @access public
  706. * @static
  707. */
  708. function url($url = null, $full = false) {
  709. $self =& Router::getInstance();
  710. $defaults = $params = array('plugin' => null, 'controller' => null, 'action' => 'index');
  711. if (is_bool($full)) {
  712. $escape = false;
  713. } else {
  714. extract($full + array('escape' => false, 'full' => false));
  715. }
  716. if (!empty($self->__params)) {
  717. if (isset($this) && !isset($this->params['requested'])) {
  718. $params = $self->__params[0];
  719. } else {
  720. $params = end($self->__params);
  721. }
  722. }
  723. $path = array('base' => null);
  724. if (!empty($self->__paths)) {
  725. if (isset($this) && !isset($this->params['requested'])) {
  726. $path = $self->__paths[0];
  727. } else {
  728. $path = end($self->__paths);
  729. }
  730. }
  731. $base = $path['base'];
  732. $extension = $output = $mapped = $q = $frag = null;
  733. if (is_array($url)) {
  734. if (isset($url['base']) && $url['base'] === false) {
  735. $base = null;
  736. unset($url['base']);
  737. }
  738. if (isset($url['full_base']) && $url['full_base'] === true) {
  739. $full = true;
  740. unset($url['full_base']);
  741. }
  742. if (isset($url['?'])) {
  743. $q = $url['?'];
  744. unset($url['?']);
  745. }
  746. if (isset($url['#'])) {
  747. $frag = '#' . urlencode($url['#']);
  748. unset($url['#']);
  749. }
  750. if (empty($url['action'])) {
  751. if (empty($url['controller']) || $params['controller'] === $url['controller']) {
  752. $url['action'] = $params['action'];
  753. } else {
  754. $url['action'] = 'index';
  755. }
  756. }
  757. $prefixExists = (array_intersect_key($url, array_flip($self->__prefixes)));
  758. foreach ($self->__prefixes as $prefix) {
  759. if (!empty($params[$prefix]) && !$prefixExists) {
  760. $url[$prefix] = true;
  761. } elseif (isset($url[$prefix]) && !$url[$prefix]) {
  762. unset($url[$prefix]);
  763. }
  764. if (isset($url[$prefix]) && strpos($url['action'], $prefix . '_') === 0) {
  765. $url['action'] = substr($url['action'], strlen($prefix) + 1);
  766. }
  767. }
  768. $url += array('controller' => $params['controller'], 'plugin' => $params['plugin']);
  769. if (isset($url['ext'])) {
  770. $extension = '.' . $url['ext'];
  771. unset($url['ext']);
  772. }
  773. $match = false;
  774. for ($i = 0, $len = count($self->routes); $i < $len; $i++) {
  775. $originalUrl = $url;
  776. if (isset($self->routes[$i]->options['persist'], $params)) {
  777. $url = $self->routes[$i]->persistParams($url, $params);
  778. }
  779. if ($match = $self->routes[$i]->match($url)) {
  780. $output = trim($match, '/');
  781. break;
  782. }
  783. $url = $originalUrl;
  784. }
  785. if ($match === false) {
  786. $output = $self->_handleNoRoute($url);
  787. }
  788. $output = str_replace('//', '/', $base . '/' . $output);
  789. } else {
  790. if (((strpos($url, '://')) || (strpos($url, 'javascript:') === 0) || (strpos($url, 'mailto:') === 0)) || (!strncmp($url, '#', 1))) {
  791. return $url;
  792. }
  793. if (empty($url)) {
  794. if (!isset($path['here'])) {
  795. $path['here'] = '/';
  796. }
  797. $output = $path['here'];
  798. } elseif (substr($url, 0, 1) === '/') {
  799. $output = $base . $url;
  800. } else {
  801. $output = $base . '/';
  802. foreach ($self->__prefixes as $prefix) {
  803. if (isset($params[$prefix])) {
  804. $output .= $prefix . '/';
  805. break;
  806. }
  807. }
  808. if (!empty($params['plugin']) && $params['plugin'] !== $params['controller']) {
  809. $output .= Inflector::underscore($params['plugin']) . '/';
  810. }
  811. $output .= Inflector::underscore($params['controller']) . '/' . $url;
  812. }
  813. $output = str_replace('//', '/', $output);
  814. }
  815. if ($full && defined('FULL_BASE_URL')) {
  816. $output = FULL_BASE_URL . $output;
  817. }
  818. if (!empty($extension) && substr($output, -1) === '/') {
  819. $output = substr($output, 0, -1);
  820. }
  821. return $output . $extension . $self->queryString($q, array(), $escape) . $frag;
  822. }
  823. /**
  824. * A special fallback method that handles url arrays that cannot match
  825. * any defined routes.
  826. *
  827. * @param array $url A url that didn't match any routes
  828. * @return string A generated url for the array
  829. * @access protected
  830. * @see Router::url()
  831. */
  832. function _handleNoRoute($url) {
  833. $named = $args = array();
  834. $skip = array_merge(
  835. array('bare', 'action', 'controller', 'plugin', 'prefix'),
  836. $this->__prefixes
  837. );
  838. $keys = array_values(array_diff(array_keys($url), $skip));
  839. $count = count($keys);
  840. // Remove this once parsed URL parameters can be inserted into 'pass'
  841. for ($i = 0; $i < $count; $i++) {
  842. if (is_numeric($keys[$i])) {
  843. $args[] = $url[$keys[$i]];
  844. } else {
  845. $named[$keys[$i]] = $url[$keys[$i]];
  846. }
  847. }
  848. list($args, $named) = array(Set::filter($args, true), Set::filter($named, true));
  849. foreach ($this->__prefixes as $prefix) {
  850. if (!empty($url[$prefix])) {
  851. $url['action'] = str_replace($prefix . '_', '', $url['action']);
  852. break;
  853. }
  854. }
  855. if (empty($named) && empty($args) && (!isset($url['action']) || $url['action'] === 'index')) {
  856. $url['action'] = null;
  857. }
  858. $urlOut = array_filter(array($url['controller'], $url['action']));
  859. if (isset($url['plugin'])) {
  860. array_unshift($urlOut, $url['plugin']);
  861. }
  862. foreach ($this->__prefixes as $prefix) {
  863. if (isset($url[$prefix])) {
  864. array_unshift($urlOut, $prefix);
  865. break;
  866. }
  867. }
  868. $output = implode('/', $urlOut);
  869. if (!empty($args)) {
  870. $output .= '/' . implode('/', $args);
  871. }
  872. if (!empty($named)) {
  873. foreach ($named as $name => $value) {
  874. $output .= '/' . $name . $this->named['separator'] . $value;
  875. }
  876. }
  877. return $output;
  878. }
  879. /**
  880. * Takes an array of URL parameters and separates the ones that can be used as named arguments
  881. *
  882. * @param array $params Associative array of URL parameters.
  883. * @param string $controller Name of controller being routed. Used in scoping.
  884. * @param string $action Name of action being routed. Used in scoping.
  885. * @return array
  886. * @access public
  887. * @static
  888. */
  889. function getNamedElements($params, $controller = null, $action = null) {
  890. $self =& Router::getInstance();
  891. $named = array();
  892. foreach ($params as $param => $val) {
  893. if (isset($self->named['rules'][$param])) {
  894. $rule = $self->named['rules'][$param];
  895. if (Router::matchNamed($param, $val, $rule, compact('controller', 'action'))) {
  896. $named[$param] = $val;
  897. unset($params[$param]);
  898. }
  899. }
  900. }
  901. return array($named, $params);
  902. }
  903. /**
  904. * Return true if a given named $param's $val matches a given $rule depending on $context. Currently implemented
  905. * rule types are controller, action and match that can be combined with each other.
  906. *
  907. * @param string $param The name of the named parameter
  908. * @param string $val The value of the named parameter
  909. * @param array $rule The rule(s) to apply, can also be a match string
  910. * @param string $context An array with additional context information (controller / action)
  911. * @return boolean
  912. * @access public
  913. * @static
  914. */
  915. function matchNamed($param, $val, $rule, $context = array()) {
  916. if ($rule === true || $rule === false) {
  917. return $rule;
  918. }
  919. if (is_string($rule)) {
  920. $rule = array('match' => $rule);
  921. }
  922. if (!is_array($rule)) {
  923. return false;
  924. }
  925. $controllerMatches = !isset($rule['controller'], $context['controller']) || in_array($context['controller'], (array)$rule['controller']);
  926. if (!$controllerMatches) {
  927. return false;
  928. }
  929. $actionMatches = !isset($rule['action'], $context['action']) || in_array($context['action'], (array)$rule['action']);
  930. if (!$actionMatches) {
  931. return false;
  932. }
  933. return (!isset($rule['match']) || preg_match('/' . $rule['match'] . '/', $val));
  934. }
  935. /**
  936. * Generates a well-formed querystring from $q
  937. *
  938. * @param mixed $q Query string
  939. * @param array $extra Extra querystring parameters.
  940. * @param bool $escape Whether or not to use escaped &
  941. * @return array
  942. * @access public
  943. * @static
  944. */
  945. function queryString($q, $extra = array(), $escape = false) {
  946. if (empty($q) && empty($extra)) {
  947. return null;
  948. }
  949. $join = '&';
  950. if ($escape === true) {
  951. $join = '&amp;';
  952. }
  953. $out = '';
  954. if (is_array($q)) {
  955. $q = array_merge($extra, $q);
  956. } else {
  957. $out = $q;
  958. $q = $extra;
  959. }
  960. $out .= http_build_query($q, null, $join);
  961. if (isset($out[0]) && $out[0] != '?') {
  962. $out = '?' . $out;
  963. }
  964. return $out;
  965. }
  966. /**
  967. * Reverses a parsed parameter array into a string. Works similarly to Router::url(), but
  968. * Since parsed URL's contain additional 'pass' and 'named' as well as 'url.url' keys.
  969. * Those keys need to be specially handled in order to reverse a params array into a string url.
  970. *
  971. * This will strip out 'autoRender', 'bare', 'requested', and 'return' param names as those
  972. * are used for CakePHP internals and should not normally be part of an output url.
  973. *
  974. * @param array $param The params array that needs to be reversed.
  975. * @return string The string that is the reversed result of the array
  976. * @access public
  977. * @static
  978. */
  979. function reverse($params) {
  980. $pass = $params['pass'];
  981. $named = $params['named'];
  982. $url = $params['url'];
  983. unset(
  984. $params['pass'], $params['named'], $params['paging'], $params['models'], $params['url'], $url['url'],
  985. $params['autoRender'], $params['bare'], $params['requested'], $params['return']
  986. );
  987. $params = array_merge($params, $pass, $named);
  988. if (!empty($url)) {
  989. $params['?'] = $url;
  990. }
  991. return Router::url($params);
  992. }
  993. /**
  994. * Normalizes a URL for purposes of comparison. Will strip the base path off
  995. * and replace any double /'s. It will not unify the casing and underscoring
  996. * of the input value.
  997. *
  998. * @param mixed $url URL to normalize Either an array or a string url.
  999. * @return string Normalized URL
  1000. * @access public
  1001. * @static
  1002. */
  1003. function normalize($url = '/') {
  1004. if (is_array($url)) {
  1005. $url = Router::url($url);
  1006. } elseif (preg_match('/^[a-z\-]+:\/\//', $url)) {
  1007. return $url;
  1008. }
  1009. $paths = Router::getPaths();
  1010. if (!empty($paths['base']) && stristr($url, $paths['base'])) {
  1011. $url = preg_replace('/^' . preg_quote($paths['base'], '/') . '/', '', $url, 1);
  1012. }
  1013. $url = '/' . $url;
  1014. while (strpos($url, '//') !== false) {
  1015. $url = str_replace('//', '/', $url);
  1016. }
  1017. $url = preg_replace('/(?:(\/$))/', '', $url);
  1018. if (empty($url)) {
  1019. return '/';
  1020. }
  1021. return $url;
  1022. }
  1023. /**
  1024. * Returns the route matching the current request URL.
  1025. *
  1026. * @return CakeRoute Matching route object.
  1027. * @access public
  1028. * @static
  1029. */
  1030. function &requestRoute() {
  1031. $self =& Router::getInstance();
  1032. return $self->__currentRoute[0];
  1033. }
  1034. /**
  1035. * Returns the route matching the current request (useful for requestAction traces)
  1036. *
  1037. * @return CakeRoute Matching route object.
  1038. * @access public
  1039. * @static
  1040. */
  1041. function &currentRoute() {
  1042. $self =& Router::getInstance();
  1043. return $self->__currentRoute[count($self->__currentRoute) - 1];
  1044. }
  1045. /**
  1046. * Removes the plugin name from the base URL.
  1047. *
  1048. * @param string $base Base URL
  1049. * @param string $plugin Plugin name
  1050. * @return base url with plugin name removed if present
  1051. * @access public
  1052. * @static
  1053. */
  1054. function stripPlugin($base, $plugin = null) {
  1055. if ($plugin != null) {
  1056. $base = preg_replace('/(?:' . $plugin . ')/', '', $base);
  1057. $base = str_replace('//', '', $base);
  1058. $pos1 = strrpos($base, '/');
  1059. $char = strlen($base) - 1;
  1060. if ($pos1 === $char) {
  1061. $base = substr($base, 0, $char);
  1062. }
  1063. }
  1064. return $base;
  1065. }
  1066. /**
  1067. * Instructs the router to parse out file extensions from the URL. For example,
  1068. * http://example.com/posts.rss would yield an file extension of "rss".
  1069. * The file extension itself is made available in the controller as
  1070. * $this->params['url']['ext'], and is used by the RequestHandler component to
  1071. * automatically switch to alternate layouts and templates, and load helpers
  1072. * corresponding to the given content, i.e. RssHelper.
  1073. *
  1074. * A list of valid extension can be passed to this method, i.e. Router::parseExtensions('rss', 'xml');
  1075. * If no parameters are given, anything after the first . (dot) after the last / in the URL will be
  1076. * parsed, excluding querystring parameters (i.e. ?q=...).
  1077. *
  1078. * @access public
  1079. * @return void
  1080. * @static
  1081. */
  1082. function parseExtensions() {
  1083. $self =& Router::getInstance();
  1084. $self->__parseExtensions = true;
  1085. if (func_num_args() > 0) {
  1086. $self->__validExtensions = func_get_args();
  1087. }
  1088. }
  1089. /**
  1090. * Takes a passed params and converts it to args
  1091. *
  1092. * @param array $params
  1093. * @return array Array containing passed and named parameters
  1094. * @access public
  1095. * @static
  1096. */
  1097. function getArgs($args, $options = array()) {
  1098. $self =& Router::getInstance();
  1099. $pass = $named = array();
  1100. $args = explode('/', $args);
  1101. $greedy = isset($options['greedy']) ? $options['greedy'] : $self->named['greedy'];
  1102. $context = array();
  1103. if (isset($options['context'])) {
  1104. $context = $options['context'];
  1105. }
  1106. $rules = $self->named['rules'];
  1107. if (isset($options['named'])) {
  1108. $greedy = isset($options['greedy']) && $options['greedy'] === true;
  1109. foreach ((array)$options['named'] as $key => $val) {
  1110. if (is_numeric($key)) {
  1111. $rules[$val] = true;
  1112. continue;
  1113. }
  1114. $rules[$key] = $val;
  1115. }
  1116. }
  1117. foreach ($args as $param) {
  1118. if (empty($param) && $param !== '0' && $param !== 0) {
  1119. continue;
  1120. }
  1121. $separatorIsPresent = strpos($param, $self->named['separator']) !== false;
  1122. if ((!isset($options['named']) || !empty($options['named'])) && $separatorIsPresent) {
  1123. list($key, $val) = explode($self->named['separator'], $param, 2);
  1124. $hasRule = isset($rules[$key]);
  1125. $passIt = (!$hasRule && !$greedy) || ($hasRule && !$self->matchNamed($key, $val, $rules[$key], $context));
  1126. if ($passIt) {
  1127. $pass[] = $param;
  1128. } else {
  1129. $named[$key] = $val;
  1130. }
  1131. } else {
  1132. $pass[] = $param;
  1133. }
  1134. }
  1135. return compact('pass', 'named');
  1136. }
  1137. }
  1138. /**
  1139. * A single Route used by the Router to connect requests to
  1140. * parameter maps.
  1141. *
  1142. * Not normally created as a standalone. Use Router::connect() to create
  1143. * Routes for your application.
  1144. *
  1145. * @package cake.libs
  1146. * @since 1.3.0
  1147. * @see Router::connect()
  1148. */
  1149. class CakeRoute {
  1150. /**
  1151. * An array of named segments in a Route.
  1152. * `/:controller/:action/:id` has 3 key elements
  1153. *
  1154. * @var array
  1155. * @access public
  1156. */
  1157. var $keys = array();
  1158. /**
  1159. * An array of additional parameters for the Route.
  1160. *
  1161. * @var array
  1162. * @access public
  1163. */
  1164. var $options = array();
  1165. /**
  1166. * Default parameters for a Route
  1167. *
  1168. * @var array
  1169. * @access public
  1170. */
  1171. var $defaults = array();
  1172. /**
  1173. * The routes template string.
  1174. *
  1175. * @var string
  1176. * @access public
  1177. */
  1178. var $template = null;
  1179. /**
  1180. * Is this route a greedy route? Greedy routes have a `/*` in their
  1181. * template
  1182. *
  1183. * @var string
  1184. * @access protected
  1185. */
  1186. var $_greedy = false;
  1187. /**
  1188. * The compiled route regular expresssion
  1189. *
  1190. * @var string
  1191. * @access protected
  1192. */
  1193. var $_compiledRoute = null;
  1194. /**
  1195. * HTTP header shortcut map. Used for evaluating header-based route expressions.
  1196. *
  1197. * @var array
  1198. * @access private
  1199. */
  1200. var $__headerMap = array(
  1201. 'type' => 'content_type',
  1202. 'method' => 'request_method',
  1203. 'server' => 'server_name'
  1204. );
  1205. /**
  1206. * Constructor for a Route
  1207. *
  1208. * @param string $template Template string with parameter placeholders
  1209. * @param array $defaults Array of defaults for the route.
  1210. * @param string $params Array of parameters and additional options for the Route
  1211. * @return void
  1212. * @access public
  1213. */
  1214. function CakeRoute($template, $defaults = array(), $options = array()) {
  1215. $this->template = $template;
  1216. $this->defaults = (array)$defaults;
  1217. $this->options = (array)$options;
  1218. }
  1219. /**
  1220. * Check if a Route has been compiled into a regular expression.
  1221. *
  1222. * @return boolean
  1223. * @access public
  1224. */
  1225. function compiled() {
  1226. return !empty($this->_compiledRoute);
  1227. }
  1228. /**
  1229. * Compiles the route's regular expression. Modifies defaults property so all necessary keys are set
  1230. * and populates $this->names with the named routing elements.
  1231. *
  1232. * @return array Returns a string regular expression of the compiled route.
  1233. * @access public
  1234. */
  1235. function compile() {
  1236. if ($this->compiled()) {
  1237. return $this->_compiledRoute;
  1238. }
  1239. $this->_writeRoute();
  1240. return $this->_compiledRoute;
  1241. }
  1242. /**
  1243. * Builds a route regular expression. Uses the template, defaults and options
  1244. * properties to compile a regular expression that can be used to parse request strings.
  1245. *
  1246. * @return void
  1247. * @access protected
  1248. */
  1249. function _writeRoute() {
  1250. if (empty($this->template) || ($this->template === '/')) {
  1251. $this->_compiledRoute = '#^/*$#';
  1252. $this->keys = array();
  1253. return;
  1254. }
  1255. $route = $this->template;
  1256. $names = $routeParams = array();
  1257. $parsed = preg_quote($this->template, '#');
  1258. $parsed = str_replace('\\-', '-', $parsed);
  1259. preg_match_all('#:([A-Za-z0-9_-]+[A-Z0-9a-z])#', $parsed, $namedElements);
  1260. foreach ($namedElements[1] as $i => $name) {
  1261. $search = '\\' . $namedElements[0][$i];
  1262. if (isset($this->options[$name])) {
  1263. $option = null;
  1264. if ($name !== 'plugin' && array_key_exists($name, $this->defaults)) {
  1265. $option = '?';
  1266. }
  1267. $slashParam = '/\\' . $namedElements[0][$i];
  1268. if (strpos($parsed, $slashParam) !== false) {
  1269. $routeParams[$slashParam] = '(?:/(' . $this->options[$name] . ')' . $option . ')' . $option;
  1270. } else {
  1271. $routeParams[$search] = '(?:(' . $this->options[$name] . ')' . $option . ')' . $option;
  1272. }
  1273. } else {
  1274. $routeParams[$search] = '(?:([^/]+))';
  1275. }
  1276. $names[] = $name;
  1277. }
  1278. if (preg_match('#\/\*$#', $route, $m)) {
  1279. $parsed = preg_replace('#/\\\\\*$#', '(?:/(?P<_args_>.*))?', $parsed);
  1280. $this->_greedy = true;
  1281. }
  1282. krsort($routeParams);
  1283. $parsed = str_replace(array_keys($routeParams), array_values($routeParams), $parsed);
  1284. $this->_compiledRoute = '#^' . $parsed . '[/]*$#';
  1285. $this->keys = $names;
  1286. }
  1287. /**
  1288. * Checks to see if the given URL can be parsed by this route.
  1289. * If the route can be parsed an array of parameters will be returned; if not,
  1290. * false will be returned. String urls are parsed if they match a routes regular expression.
  1291. *
  1292. * @param string $url The url to attempt to parse.
  1293. * @return mixed Boolean false on failure, otherwise an array or parameters
  1294. * @access public
  1295. */
  1296. function parse($url) {
  1297. if (!$this->compiled()) {
  1298. $this->compile();
  1299. }
  1300. if (!preg_match($this->_compiledRoute, $url, $parsed)) {
  1301. return false;
  1302. } else {
  1303. foreach ($this->defaults as $key => $val) {
  1304. if ($key[0] === '[' && preg_match('/^\[(\w+)\]$/', $key, $header)) {
  1305. if (isset($this->__headerMap[$header[1]])) {
  1306. $header = $this->__headerMap[$header[1]];
  1307. } else {
  1308. $header = 'http_' . $header[1];
  1309. }
  1310. $val = (array)$val;
  1311. $h = false;
  1312. foreach ($val as $v) {
  1313. if (env(strtoupper($header)) === $v) {
  1314. $h = true;
  1315. }
  1316. }
  1317. if (!$h) {
  1318. return false;
  1319. }
  1320. }
  1321. }
  1322. array_shift($parsed);
  1323. $route = array();
  1324. foreach ($this->keys as $i => $key) {
  1325. if (isset($parsed[$i])) {
  1326. $route[$key] = $parsed[$i];
  1327. }
  1328. }
  1329. $route['pass'] = $route['named'] = array();
  1330. $route += $this->defaults;
  1331. if (isset($parsed['_args_'])) {
  1332. $route['_args_'] = $parsed['_args_'];
  1333. }
  1334. foreach ($route as $key => $value) {
  1335. if (is_integer($key)) {
  1336. $route['pass'][] = $value;
  1337. unset($route[$key]);
  1338. }
  1339. }
  1340. return $route;
  1341. }
  1342. }
  1343. /**
  1344. * Apply persistent parameters to a url array. Persistant parameters are a special
  1345. * key used during route creation to force route parameters to persist when omitted from
  1346. * a url array.
  1347. *
  1348. * @param array $url The array to apply persistent parameters to.
  1349. * @param array $params An array of persistent values to replace persistent ones.
  1350. * @return array An array with persistent parameters applied.
  1351. * @access public
  1352. */
  1353. function persistParams($url, $params) {
  1354. foreach ($this->options['persist'] as $persistKey) {
  1355. if (array_key_exists($persistKey, $params) && !isset($url[$persistKey])) {
  1356. $url[$persistKey] = $params[$persistKey];
  1357. }
  1358. }
  1359. return $url;
  1360. }
  1361. /**
  1362. * Attempt to match a url array. If the url matches the route parameters and settings, then
  1363. * return a generated string url. If the url doesn't match the route parameters, false will be returned.
  1364. * This method handles the reverse routing or conversion of url arrays into string urls.
  1365. *
  1366. * @param array $url An array of parameters to check matching with.
  1367. * @return mixed Either a string url for the parameters if they match or false.
  1368. * @access public
  1369. */
  1370. function match($url) {
  1371. if (!$this->compiled()) {
  1372. $this->compile();
  1373. }
  1374. $defaults = $this->defaults;
  1375. if (isset($defaults['prefix'])) {
  1376. $url['prefix'] = $defaults['prefix'];
  1377. }
  1378. //check that all the key names are in the url
  1379. $keyNames = array_flip($this->keys);
  1380. if (array_intersect_key($keyNames, $url) != $keyNames) {
  1381. return false;
  1382. }
  1383. $diffUnfiltered = Set::diff($url, $defaults);
  1384. $diff = array();
  1385. foreach ($diffUnfiltered as $key => $var) {
  1386. if ($var === 0 || $var === '0' || !empty($var)) {
  1387. $diff[$key] = $var;
  1388. }
  1389. }
  1390. //if a not a greedy route, no extra params are allowed.
  1391. if (!$this->_greedy && array_diff_key($diff, $keyNames) != array()) {
  1392. return false;
  1393. }
  1394. //remove defaults that are also keys. They can cause match failures
  1395. foreach ($this->keys as $key) {
  1396. unset($defaults[$key]);
  1397. }
  1398. $filteredDefaults = array_filter($defaults);
  1399. //if the difference between the url diff and defaults contains keys from defaults its not a match
  1400. if (array_intersect_key($filteredDefaults, $diffUnfiltered) !== array()) {
  1401. return false;
  1402. }
  1403. $passedArgsAndParams = array_diff_key($diff, $filteredDefaults, $keyNames);
  1404. list($named, $params) = Router::getNamedElements($passedArgsAndParams, $url['controller'], $url['action']);
  1405. //remove any pass params, they have numeric indexes, skip any params that are in the defaults
  1406. $pass = array();
  1407. $i = 0;
  1408. while (isset($url[$i])) {
  1409. if (!isset($diff[$i])) {
  1410. $i++;
  1411. continue;
  1412. }
  1413. $pass[] = $url[$i];
  1414. unset($url[$i], $params[$i]);
  1415. $i++;
  1416. }
  1417. //still some left over parameters that weren't named or passed args, bail.
  1418. if (!empty($params)) {
  1419. return false;
  1420. }
  1421. //check patterns for routed params
  1422. if (!empty($this->options)) {
  1423. foreach ($this->options as $key => $pattern) {
  1424. if (array_key_exists($key, $url) && !preg_match('#^' . $pattern . '$#', $url[$key])) {
  1425. return false;
  1426. }
  1427. }
  1428. }
  1429. return $this->_writeUrl(array_merge($url, compact('pass', 'named')));
  1430. }
  1431. /**
  1432. * Converts a matching route array into a url string. Composes the string url using the template
  1433. * used to create the route.
  1434. *
  1435. * @param array $params The params to convert to a string url.
  1436. * @return string Composed route string.
  1437. * @access protected
  1438. */
  1439. function _writeUrl($params) {
  1440. if (isset($params['prefix'], $params['action'])) {
  1441. $params['action'] = str_replace($params['prefix'] . '_', '', $params['action']);
  1442. unset($params['prefix']);
  1443. }
  1444. if (is_array($params['pass'])) {
  1445. $params['pass'] = implode('/', $params['pass']);
  1446. }
  1447. $instance =& Router::getInstance();
  1448. $separator = $instance->named['separator'];
  1449. if (!empty($params['named']) && is_array($params['named'])) {
  1450. $named = array();
  1451. foreach ($params['named'] as $key => $value) {
  1452. $named[] = $key . $separator . $value;
  1453. }
  1454. $params['pass'] = $params['pass'] . '/' . implode('/', $named);
  1455. }
  1456. $out = $this->template;
  1457. $search = $replace = array();
  1458. foreach ($this->keys as $key) {
  1459. $string = null;
  1460. if (isset($params[$key])) {
  1461. $string = $params[$key];
  1462. } elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
  1463. $key .= '/';
  1464. }
  1465. $search[] = ':' . $key;
  1466. $replace[] = $string;
  1467. }
  1468. $out = str_replace($search, $replace, $out);
  1469. if (strpos($this->template, '*')) {
  1470. $out = str_replace('*', $params['pass'], $out);
  1471. }
  1472. $out = str_replace('//', '/', $out);
  1473. return $out;
  1474. }
  1475. }
  1476. /**
  1477. * Plugin short route, that copies the plugin param to the controller parameters
  1478. * It is used for supporting /:plugin routes.
  1479. *
  1480. * @package cake.libs
  1481. */
  1482. class PluginShortRoute extends CakeRoute {
  1483. /**
  1484. * Parses a string url into an array. If a plugin key is found, it will be copied to the
  1485. * controller parameter
  1486. *
  1487. * @param string $url The url to parse
  1488. * @return mixed false on failure, or an array of request parameters
  1489. */
  1490. function parse($url) {
  1491. $params = parent::parse($url);
  1492. if (!$params) {
  1493. return false;
  1494. }
  1495. $params['controller'] = $params['plugin'];
  1496. return $params;
  1497. }
  1498. /**
  1499. * Reverse route plugin shortcut urls. If the plugin and controller
  1500. * are not the same the match is an auto fail.
  1501. *
  1502. * @param array $url Array of parameters to convert to a string.
  1503. * @return mixed either false or a string url.
  1504. */
  1505. function match($url) {
  1506. if (isset($url['controller']) && isset($url['plugin']) && $url['plugin'] != $url['controller']) {
  1507. return false;
  1508. }
  1509. $this->defaults['controller'] = $url['controller'];
  1510. $result = parent::match($url);
  1511. unset($this->defaults['controller']);
  1512. return $result;
  1513. }
  1514. }