Base for a static organization website

Router.php 38KB

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