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