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 to set as default
211: * @return mixed void|string
212: * @throws RouterException
213: */
214: public static function defaultRouteClass($routeClass = null) {
215: if ($routeClass === null) {
216: return self::$_routeClass;
217: }
218:
219: self::$_routeClass = self::_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: self::$_prefixes = array_merge(self::$_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 self::$_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 self::$_resourceMap;
270: }
271: self::$_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: self::$initialized = true;
346:
347: foreach (self::$_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'])) {
358: self::$_prefixes[] = $defaults['prefix'];
359: self::$_prefixes = array_keys(array_flip(self::$_prefixes));
360: }
361: $defaults += array('plugin' => null);
362: if (empty($options['action'])) {
363: $defaults += array('action' => 'index');
364: }
365: $routeClass = self::$_routeClass;
366: if (isset($options['routeClass'])) {
367: if (strpos($options['routeClass'], '.') === false) {
368: $routeClass = $options['routeClass'];
369: } else {
370: list(, $routeClass) = pluginSplit($options['routeClass'], true);
371: }
372: $routeClass = self::_validateRouteClass($routeClass);
373: unset($options['routeClass']);
374: }
375: if ($routeClass === 'RedirectRoute' && isset($defaults['redirect'])) {
376: $defaults = $defaults['redirect'];
377: }
378: self::$routes[] = new $routeClass($route, $defaults, $options);
379: return self::$routes;
380: }
381:
382: /**
383: * Connects a new redirection Route in the router.
384: *
385: * Redirection routes are different from normal routes as they perform an actual
386: * header redirection if a match is found. The redirection can occur within your
387: * application or redirect to an outside location.
388: *
389: * Examples:
390: *
391: * `Router::redirect('/home/*', array('controller' => 'posts', 'action' => 'view'), array('persist' => true));`
392: *
393: * Redirects /home/* to /posts/view and passes the parameters to /posts/view. Using an array as the
394: * redirect destination allows you to use other routes to define where a URL string should be redirected to.
395: *
396: * `Router::redirect('/posts/*', 'http://google.com', array('status' => 302));`
397: *
398: * Redirects /posts/* to http://google.com with a HTTP status of 302
399: *
400: * ### Options:
401: *
402: * - `status` Sets the HTTP status (default 301)
403: * - `persist` Passes the params to the redirected route, if it can. This is useful with greedy routes,
404: * routes that end in `*` are greedy. As you can remap URLs and not loose any passed/named args.
405: *
406: * @param string $route A string describing the template of the route
407: * @param array $url A URL to redirect to. Can be a string or a CakePHP array-based URL
408: * @param array $options An array matching the named elements in the route to regular expressions which that
409: * element should match. Also contains additional parameters such as which routed parameters should be
410: * shifted into the passed arguments. As well as supplying patterns for routing parameters.
411: * @see routes
412: * @return array Array of routes
413: */
414: public static function redirect($route, $url, $options = array()) {
415: App::uses('RedirectRoute', 'Routing/Route');
416: $options['routeClass'] = 'RedirectRoute';
417: if (is_string($url)) {
418: $url = array('redirect' => $url);
419: }
420: return self::connect($route, $url, $options);
421: }
422:
423: /**
424: * Specifies what named parameters CakePHP should be parsing out of incoming URLs. By default
425: * CakePHP will parse every named parameter out of incoming URLs. However, if you want to take more
426: * control over how named parameters are parsed you can use one of the following setups:
427: *
428: * Do not parse any named parameters:
429: *
430: * {{{ Router::connectNamed(false); }}}
431: *
432: * Parse only default parameters used for CakePHP's pagination:
433: *
434: * {{{ Router::connectNamed(false, array('default' => true)); }}}
435: *
436: * Parse only the page parameter if its value is a number:
437: *
438: * {{{ Router::connectNamed(array('page' => '[\d]+'), array('default' => false, 'greedy' => false)); }}}
439: *
440: * Parse only the page parameter no matter what.
441: *
442: * {{{ Router::connectNamed(array('page'), array('default' => false, 'greedy' => false)); }}}
443: *
444: * Parse only the page parameter if the current action is 'index'.
445: *
446: * {{{
447: * Router::connectNamed(
448: * array('page' => array('action' => 'index')),
449: * array('default' => false, 'greedy' => false)
450: * );
451: * }}}
452: *
453: * Parse only the page parameter if the current action is 'index' and the controller is 'pages'.
454: *
455: * {{{
456: * Router::connectNamed(
457: * array('page' => array('action' => 'index', 'controller' => 'pages')),
458: * array('default' => false, 'greedy' => false)
459: * );
460: * }}}
461: *
462: * ### Options
463: *
464: * - `greedy` Setting this to true will make Router parse all named params. Setting it to false will
465: * parse only the connected named params.
466: * - `default` Set this to true to merge in the default set of named parameters.
467: * - `reset` Set to true to clear existing rules and start fresh.
468: * - `separator` Change the string used to separate the key & value in a named parameter. Defaults to `:`
469: *
470: * @param array $named A list of named parameters. Key value pairs are accepted where values are
471: * either regex strings to match, or arrays as seen above.
472: * @param array $options Allows to control all settings: separator, greedy, reset, default
473: * @return array
474: */
475: public static function connectNamed($named, $options = array()) {
476: if (isset($options['separator'])) {
477: self::$_namedConfig['separator'] = $options['separator'];
478: unset($options['separator']);
479: }
480:
481: if ($named === true || $named === false) {
482: $options += array('default' => $named, 'reset' => true, 'greedy' => $named);
483: $named = array();
484: } else {
485: $options += array('default' => false, 'reset' => false, 'greedy' => true);
486: }
487:
488: if ($options['reset'] || self::$_namedConfig['rules'] === false) {
489: self::$_namedConfig['rules'] = array();
490: }
491:
492: if ($options['default']) {
493: $named = array_merge($named, self::$_namedConfig['default']);
494: }
495:
496: foreach ($named as $key => $val) {
497: if (is_numeric($key)) {
498: self::$_namedConfig['rules'][$val] = true;
499: } else {
500: self::$_namedConfig['rules'][$key] = $val;
501: }
502: }
503: self::$_namedConfig['greedyNamed'] = $options['greedy'];
504: return self::$_namedConfig;
505: }
506:
507: /**
508: * Gets the current named parameter configuration values.
509: *
510: * @return array
511: * @see Router::$_namedConfig
512: */
513: public static function namedConfig() {
514: return self::$_namedConfig;
515: }
516:
517: /**
518: * Creates REST resource routes for the given controller(s). When creating resource routes
519: * for a plugin, by default the prefix will be changed to the lower_underscore version of the plugin
520: * name. By providing a prefix you can override this behavior.
521: *
522: * ### Options:
523: *
524: * - 'id' - The regular expression fragment to use when matching IDs. By default, matches
525: * integer values and UUIDs.
526: * - 'prefix' - URL prefix to use for the generated routes. Defaults to '/'.
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' => self::ID . '|' . self::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 (self::$_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: self::$_resourceMapped[] = $urlName;
575: }
576: return self::$_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 self::$_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 (!self::$initialized) {
596: self::_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(self::_parseExtension($url));
611:
612: for ($i = 0, $len = count(self::$routes); $i < $len; $i++) {
613: $route =& self::$routes[$i];
614:
615: if (($r = $route->parse($url)) !== false) {
616: self::$_currentRoute[] =& $route;
617: $out = $r;
618: break;
619: }
620: }
621: if (isset($out['prefix'])) {
622: $out['action'] = $out['prefix'] . '_' . $out['action'];
623: }
624:
625: if (!empty($ext) && !isset($out['ext'])) {
626: $out['ext'] = $ext;
627: }
628:
629: if (!empty($queryParameters) && !isset($out['?'])) {
630: $out['?'] = $queryParameters;
631: }
632: return $out;
633: }
634:
635: /**
636: * Parses a file extension out of a URL, if Router::parseExtensions() is enabled.
637: *
638: * @param string $url URL.
639: * @return array Returns an array containing the altered URL and the parsed extension.
640: */
641: protected static function _parseExtension($url) {
642: $ext = null;
643:
644: if (self::$_parseExtensions) {
645: if (preg_match('/\.[0-9a-zA-Z]*$/', $url, $match) === 1) {
646: $match = substr($match[0], 1);
647: if (empty(self::$_validExtensions)) {
648: $url = substr($url, 0, strpos($url, '.' . $match));
649: $ext = $match;
650: } else {
651: foreach (self::$_validExtensions as $name) {
652: if (strcasecmp($name, $match) === 0) {
653: $url = substr($url, 0, strpos($url, '.' . $name));
654: $ext = $match;
655: break;
656: }
657: }
658: }
659: }
660: }
661: return compact('ext', 'url');
662: }
663:
664: /**
665: * Takes parameter and path information back from the Dispatcher, sets these
666: * parameters as the current request parameters that are merged with URL arrays
667: * created later in the request.
668: *
669: * Nested requests will create a stack of requests. You can remove requests using
670: * Router::popRequest(). This is done automatically when using Object::requestAction().
671: *
672: * Will accept either a CakeRequest object or an array of arrays. Support for
673: * accepting arrays may be removed in the future.
674: *
675: * @param CakeRequest|array $request Parameters and path information or a CakeRequest object.
676: * @return void
677: */
678: public static function setRequestInfo($request) {
679: if ($request instanceof CakeRequest) {
680: self::$_requests[] = $request;
681: } else {
682: $requestObj = new CakeRequest();
683: $request += array(array(), array());
684: $request[0] += array('controller' => false, 'action' => false, 'plugin' => null);
685: $requestObj->addParams($request[0])->addPaths($request[1]);
686: self::$_requests[] = $requestObj;
687: }
688: }
689:
690: /**
691: * Pops a request off of the request stack. Used when doing requestAction
692: *
693: * @return CakeRequest The request removed from the stack.
694: * @see Router::setRequestInfo()
695: * @see Object::requestAction()
696: */
697: public static function popRequest() {
698: return array_pop(self::$_requests);
699: }
700:
701: /**
702: * Gets the current request object, or the first one.
703: *
704: * @param bool $current True to get the current request object, or false to get the first one.
705: * @return CakeRequest|null Null if stack is empty.
706: */
707: public static function getRequest($current = false) {
708: if ($current) {
709: $i = count(self::$_requests) - 1;
710: return isset(self::$_requests[$i]) ? self::$_requests[$i] : null;
711: }
712: return isset(self::$_requests[0]) ? self::$_requests[0] : null;
713: }
714:
715: /**
716: * Gets parameter information
717: *
718: * @param bool $current Get current request parameter, useful when using requestAction
719: * @return array Parameter information
720: */
721: public static function getParams($current = false) {
722: if ($current && self::$_requests) {
723: return self::$_requests[count(self::$_requests) - 1]->params;
724: }
725: if (isset(self::$_requests[0])) {
726: return self::$_requests[0]->params;
727: }
728: return array();
729: }
730:
731: /**
732: * Gets URL parameter by name
733: *
734: * @param string $name Parameter name
735: * @param bool $current Current parameter, useful when using requestAction
736: * @return string Parameter value
737: */
738: public static function getParam($name = 'controller', $current = false) {
739: $params = Router::getParams($current);
740: if (isset($params[$name])) {
741: return $params[$name];
742: }
743: return null;
744: }
745:
746: /**
747: * Gets path information
748: *
749: * @param bool $current Current parameter, useful when using requestAction
750: * @return array
751: */
752: public static function getPaths($current = false) {
753: if ($current) {
754: return self::$_requests[count(self::$_requests) - 1];
755: }
756: if (!isset(self::$_requests[0])) {
757: return array('base' => null);
758: }
759: return array('base' => self::$_requests[0]->base);
760: }
761:
762: /**
763: * Reloads default Router settings. Resets all class variables and
764: * removes all connected routes.
765: *
766: * @return void
767: */
768: public static function reload() {
769: if (empty(self::$_initialState)) {
770: self::$_initialState = get_class_vars('Router');
771: self::_setPrefixes();
772: return;
773: }
774: foreach (self::$_initialState as $key => $val) {
775: if ($key !== '_initialState') {
776: self::${$key} = $val;
777: }
778: }
779: self::_setPrefixes();
780: }
781:
782: /**
783: * Promote a route (by default, the last one added) to the beginning of the list
784: *
785: * @param int $which A zero-based array index representing the route to move. For example,
786: * if 3 routes have been added, the last route would be 2.
787: * @return bool Returns false if no route exists at the position specified by $which.
788: */
789: public static function promote($which = null) {
790: if ($which === null) {
791: $which = count(self::$routes) - 1;
792: }
793: if (!isset(self::$routes[$which])) {
794: return false;
795: }
796: $route =& self::$routes[$which];
797: unset(self::$routes[$which]);
798: array_unshift(self::$routes, $route);
799: return true;
800: }
801:
802: /**
803: * Finds URL for specified action.
804: *
805: * Returns a URL pointing to a combination of controller and action. Param
806: * $url can be:
807: *
808: * - Empty - the method will find address to actual controller/action.
809: * - '/' - the method will find base URL of application.
810: * - A combination of controller/action - the method will find URL for it.
811: *
812: * There are a few 'special' parameters that can change the final URL string that is generated
813: *
814: * - `base` - Set to false to remove the base path from the generated URL. If your application
815: * is not in the root directory, this can be used to generate URLs that are 'cake relative'.
816: * cake relative URLs are required when using requestAction.
817: * - `?` - Takes an array of query string parameters
818: * - `#` - Allows you to set URL hash fragments.
819: * - `full_base` - If true the `Router::fullBaseUrl()` value will be prepended to generated URLs.
820: *
821: * @param string|array $url Cake-relative URL, like "/products/edit/92" or "/presidents/elect/4"
822: * or an array specifying any of the following: 'controller', 'action',
823: * and/or 'plugin', in addition to named arguments (keyed array elements),
824: * and standard URL arguments (indexed array elements)
825: * @param bool|array $full If (bool) true, the full base URL will be prepended to the result.
826: * If an array accepts the following keys
827: * - escape - used when making URLs embedded in html escapes query string '&'
828: * - full - if true the full base URL will be prepended.
829: * @return string Full translated URL with base path.
830: */
831: public static function url($url = null, $full = false) {
832: if (!self::$initialized) {
833: self::_loadRoutes();
834: }
835:
836: $params = array('plugin' => null, 'controller' => null, 'action' => 'index');
837:
838: if (is_bool($full)) {
839: $escape = false;
840: } else {
841: extract($full + array('escape' => false, 'full' => false));
842: }
843:
844: $path = array('base' => null);
845: if (!empty(self::$_requests)) {
846: $request = self::$_requests[count(self::$_requests) - 1];
847: $params = $request->params;
848: $path = array('base' => $request->base, 'here' => $request->here);
849: }
850: if (empty($path['base'])) {
851: $path['base'] = Configure::read('App.base');
852: }
853:
854: $base = $path['base'];
855: $extension = $output = $q = $frag = null;
856:
857: if (empty($url)) {
858: $output = isset($path['here']) ? $path['here'] : '/';
859: if ($full) {
860: $output = self::fullBaseUrl() . $output;
861: }
862: return $output;
863: } elseif (is_array($url)) {
864: if (isset($url['base']) && $url['base'] === false) {
865: $base = null;
866: unset($url['base']);
867: }
868: if (isset($url['full_base']) && $url['full_base'] === true) {
869: $full = true;
870: unset($url['full_base']);
871: }
872: if (isset($url['?'])) {
873: $q = $url['?'];
874: unset($url['?']);
875: }
876: if (isset($url['#'])) {
877: $frag = '#' . $url['#'];
878: unset($url['#']);
879: }
880: if (isset($url['ext'])) {
881: $extension = '.' . $url['ext'];
882: unset($url['ext']);
883: }
884: if (empty($url['action'])) {
885: if (empty($url['controller']) || $params['controller'] === $url['controller']) {
886: $url['action'] = $params['action'];
887: } else {
888: $url['action'] = 'index';
889: }
890: }
891:
892: $prefixExists = (array_intersect_key($url, array_flip(self::$_prefixes)));
893: foreach (self::$_prefixes as $prefix) {
894: if (!empty($params[$prefix]) && !$prefixExists) {
895: $url[$prefix] = true;
896: } elseif (isset($url[$prefix]) && !$url[$prefix]) {
897: unset($url[$prefix]);
898: }
899: if (isset($url[$prefix]) && strpos($url['action'], $prefix . '_') === 0) {
900: $url['action'] = substr($url['action'], strlen($prefix) + 1);
901: }
902: }
903:
904: $url += array('controller' => $params['controller'], 'plugin' => $params['plugin']);
905:
906: $match = false;
907:
908: for ($i = 0, $len = count(self::$routes); $i < $len; $i++) {
909: $originalUrl = $url;
910:
911: $url = self::$routes[$i]->persistParams($url, $params);
912:
913: if ($match = self::$routes[$i]->match($url)) {
914: $output = trim($match, '/');
915: break;
916: }
917: $url = $originalUrl;
918: }
919: if ($match === false) {
920: $output = self::_handleNoRoute($url);
921: }
922: } else {
923: if (preg_match('/^([a-z][a-z0-9.+\-]+:|:?\/\/|[#?])/i', $url)) {
924: return $url;
925: }
926: if (substr($url, 0, 1) === '/') {
927: $output = substr($url, 1);
928: } else {
929: foreach (self::$_prefixes as $prefix) {
930: if (isset($params[$prefix])) {
931: $output .= $prefix . '/';
932: break;
933: }
934: }
935: if (!empty($params['plugin']) && $params['plugin'] !== $params['controller']) {
936: $output .= Inflector::underscore($params['plugin']) . '/';
937: }
938: $output .= Inflector::underscore($params['controller']) . '/' . $url;
939: }
940: }
941: $protocol = preg_match('#^[a-z][a-z0-9+\-.]*\://#i', $output);
942: if ($protocol === 0) {
943: $output = str_replace('//', '/', $base . '/' . $output);
944:
945: if ($full) {
946: $output = self::fullBaseUrl() . $output;
947: }
948: if (!empty($extension)) {
949: $output = rtrim($output, '/');
950: }
951: }
952: return $output . $extension . self::queryString($q, array(), $escape) . $frag;
953: }
954:
955: /**
956: * Sets the full base URL that will be used as a prefix for generating
957: * fully qualified URLs for this application. If no parameters are passed,
958: * the currently configured value is returned.
959: *
960: * ## Note:
961: *
962: * If you change the configuration value ``App.fullBaseUrl`` during runtime
963: * and expect the router to produce links using the new setting, you are
964: * required to call this method passing such value again.
965: *
966: * @param string $base the prefix for URLs generated containing the domain.
967: * For example: ``http://example.com``
968: * @return string
969: */
970: public static function fullBaseUrl($base = null) {
971: if ($base !== null) {
972: self::$_fullBaseUrl = $base;
973: Configure::write('App.fullBaseUrl', $base);
974: }
975: if (empty(self::$_fullBaseUrl)) {
976: self::$_fullBaseUrl = Configure::read('App.fullBaseUrl');
977: }
978: return self::$_fullBaseUrl;
979: }
980:
981: /**
982: * A special fallback method that handles URL arrays that cannot match
983: * any defined routes.
984: *
985: * @param array $url A URL that didn't match any routes
986: * @return string A generated URL for the array
987: * @see Router::url()
988: */
989: protected static function _handleNoRoute($url) {
990: $named = $args = array();
991: $skip = array_merge(
992: array('bare', 'action', 'controller', 'plugin', 'prefix'),
993: self::$_prefixes
994: );
995:
996: $keys = array_values(array_diff(array_keys($url), $skip));
997: $count = count($keys);
998:
999: // Remove this once parsed URL parameters can be inserted into 'pass'
1000: for ($i = 0; $i < $count; $i++) {
1001: $key = $keys[$i];
1002: if (is_numeric($keys[$i])) {
1003: $args[] = $url[$key];
1004: } else {
1005: $named[$key] = $url[$key];
1006: }
1007: }
1008:
1009: list($args, $named) = array(Hash::filter($args), Hash::filter($named));
1010: foreach (self::$_prefixes as $prefix) {
1011: $prefixed = $prefix . '_';
1012: if (!empty($url[$prefix]) && strpos($url['action'], $prefixed) === 0) {
1013: $url['action'] = substr($url['action'], strlen($prefixed) * -1);
1014: break;
1015: }
1016: }
1017:
1018: if (empty($named) && empty($args) && (!isset($url['action']) || $url['action'] === 'index')) {
1019: $url['action'] = null;
1020: }
1021:
1022: $urlOut = array_filter(array($url['controller'], $url['action']));
1023:
1024: if (isset($url['plugin'])) {
1025: array_unshift($urlOut, $url['plugin']);
1026: }
1027:
1028: foreach (self::$_prefixes as $prefix) {
1029: if (isset($url[$prefix])) {
1030: array_unshift($urlOut, $prefix);
1031: break;
1032: }
1033: }
1034: $output = implode('/', $urlOut);
1035:
1036: if (!empty($args)) {
1037: $output .= '/' . implode('/', array_map('rawurlencode', $args));
1038: }
1039:
1040: if (!empty($named)) {
1041: foreach ($named as $name => $value) {
1042: if (is_array($value)) {
1043: $flattend = Hash::flatten($value, '%5D%5B');
1044: foreach ($flattend as $namedKey => $namedValue) {
1045: $output .= '/' . $name . "%5B{$namedKey}%5D" . self::$_namedConfig['separator'] . rawurlencode($namedValue);
1046: }
1047: } else {
1048: $output .= '/' . $name . self::$_namedConfig['separator'] . rawurlencode($value);
1049: }
1050: }
1051: }
1052: return $output;
1053: }
1054:
1055: /**
1056: * Generates a well-formed querystring from $q
1057: *
1058: * @param string|array $q Query string Either a string of already compiled query string arguments or
1059: * an array of arguments to convert into a query string.
1060: * @param array $extra Extra querystring parameters.
1061: * @param bool $escape Whether or not to use escaped &
1062: * @return array
1063: */
1064: public static function queryString($q, $extra = array(), $escape = false) {
1065: if (empty($q) && empty($extra)) {
1066: return null;
1067: }
1068: $join = '&';
1069: if ($escape === true) {
1070: $join = '&';
1071: }
1072: $out = '';
1073:
1074: if (is_array($q)) {
1075: $q = array_merge($q, $extra);
1076: } else {
1077: $out = $q;
1078: $q = $extra;
1079: }
1080: $addition = http_build_query($q, null, $join);
1081:
1082: if ($out && $addition && substr($out, strlen($join) * -1, strlen($join)) !== $join) {
1083: $out .= $join;
1084: }
1085:
1086: $out .= $addition;
1087:
1088: if (isset($out[0]) && $out[0] !== '?') {
1089: $out = '?' . $out;
1090: }
1091: return $out;
1092: }
1093:
1094: /**
1095: * Reverses a parsed parameter array into a string.
1096: *
1097: * Works similarly to Router::url(), but since parsed URL's contain additional
1098: * 'pass' and 'named' as well as 'url.url' keys. Those keys need to be specially
1099: * handled in order to reverse a params array into a string URL.
1100: *
1101: * This will strip out 'autoRender', 'bare', 'requested', and 'return' param names as those
1102: * are used for CakePHP internals and should not normally be part of an output URL.
1103: *
1104: * @param CakeRequest|array $params The params array or CakeRequest object that needs to be reversed.
1105: * @param bool $full Set to true to include the full URL including the protocol when reversing
1106: * the URL.
1107: * @return string The string that is the reversed result of the array
1108: */
1109: public static function reverse($params, $full = false) {
1110: if ($params instanceof CakeRequest) {
1111: $url = $params->query;
1112: $params = $params->params;
1113: } else {
1114: $url = $params['url'];
1115: }
1116: $pass = isset($params['pass']) ? $params['pass'] : array();
1117: $named = isset($params['named']) ? $params['named'] : array();
1118:
1119: unset(
1120: $params['pass'], $params['named'], $params['paging'], $params['models'], $params['url'], $url['url'],
1121: $params['autoRender'], $params['bare'], $params['requested'], $params['return'],
1122: $params['_Token']
1123: );
1124: $params = array_merge($params, $pass, $named);
1125: if (!empty($url)) {
1126: $params['?'] = $url;
1127: }
1128: return Router::url($params, $full);
1129: }
1130:
1131: /**
1132: * Normalizes a URL for purposes of comparison.
1133: *
1134: * Will strip the base path off and replace any double /'s.
1135: * It will not unify the casing and underscoring of the input value.
1136: *
1137: * @param array|string $url URL to normalize Either an array or a string URL.
1138: * @return string Normalized URL
1139: */
1140: public static function normalize($url = '/') {
1141: if (is_array($url)) {
1142: $url = Router::url($url);
1143: }
1144: if (preg_match('/^[a-z\-]+:\/\//', $url)) {
1145: return $url;
1146: }
1147: $request = Router::getRequest();
1148:
1149: if (!empty($request->base) && stristr($url, $request->base)) {
1150: $url = preg_replace('/^' . preg_quote($request->base, '/') . '/', '', $url, 1);
1151: }
1152: $url = '/' . $url;
1153:
1154: while (strpos($url, '//') !== false) {
1155: $url = str_replace('//', '/', $url);
1156: }
1157: $url = preg_replace('/(?:(\/$))/', '', $url);
1158:
1159: if (empty($url)) {
1160: return '/';
1161: }
1162: return $url;
1163: }
1164:
1165: /**
1166: * Returns the route matching the current request URL.
1167: *
1168: * @return CakeRoute Matching route object.
1169: */
1170: public static function requestRoute() {
1171: return self::$_currentRoute[0];
1172: }
1173:
1174: /**
1175: * Returns the route matching the current request (useful for requestAction traces)
1176: *
1177: * @return CakeRoute Matching route object.
1178: */
1179: public static function currentRoute() {
1180: $count = count(self::$_currentRoute) - 1;
1181: return ($count >= 0) ? self::$_currentRoute[$count] : false;
1182: }
1183:
1184: /**
1185: * Removes the plugin name from the base URL.
1186: *
1187: * @param string $base Base URL
1188: * @param string $plugin Plugin name
1189: * @return string base URL with plugin name removed if present
1190: */
1191: public static function stripPlugin($base, $plugin = null) {
1192: if ($plugin) {
1193: $base = preg_replace('/(?:' . $plugin . ')/', '', $base);
1194: $base = str_replace('//', '', $base);
1195: $pos1 = strrpos($base, '/');
1196: $char = strlen($base) - 1;
1197:
1198: if ($pos1 === $char) {
1199: $base = substr($base, 0, $char);
1200: }
1201: }
1202: return $base;
1203: }
1204:
1205: /**
1206: * Instructs the router to parse out file extensions from the URL.
1207: *
1208: * For example, http://example.com/posts.rss would yield a file extension of "rss".
1209: * The file extension itself is made available in the controller as
1210: * `$this->params['ext']`, and is used by the RequestHandler component to
1211: * automatically switch to alternate layouts and templates, and load helpers
1212: * corresponding to the given content, i.e. RssHelper. Switching layouts and helpers
1213: * requires that the chosen extension has a defined mime type in `CakeResponse`
1214: *
1215: * A list of valid extension can be passed to this method, i.e. Router::parseExtensions('rss', 'xml');
1216: * If no parameters are given, anything after the first . (dot) after the last / in the URL will be
1217: * parsed, excluding querystring parameters (i.e. ?q=...).
1218: *
1219: * @return void
1220: * @see RequestHandler::startup()
1221: */
1222: public static function parseExtensions() {
1223: self::$_parseExtensions = true;
1224: if (func_num_args() > 0) {
1225: self::setExtensions(func_get_args(), false);
1226: }
1227: }
1228:
1229: /**
1230: * Get the list of extensions that can be parsed by Router.
1231: *
1232: * To initially set extensions use `Router::parseExtensions()`
1233: * To add more see `setExtensions()`
1234: *
1235: * @return array Array of extensions Router is configured to parse.
1236: */
1237: public static function extensions() {
1238: if (!self::$initialized) {
1239: self::_loadRoutes();
1240: }
1241:
1242: return self::$_validExtensions;
1243: }
1244:
1245: /**
1246: * Set/add valid extensions.
1247: *
1248: * To have the extensions parsed you still need to call `Router::parseExtensions()`
1249: *
1250: * @param array $extensions List of extensions to be added as valid extension
1251: * @param bool $merge Default true will merge extensions. Set to false to override current extensions
1252: * @return array
1253: */
1254: public static function setExtensions($extensions, $merge = true) {
1255: if (!is_array($extensions)) {
1256: return self::$_validExtensions;
1257: }
1258: if (!$merge) {
1259: return self::$_validExtensions = $extensions;
1260: }
1261: return self::$_validExtensions = array_merge(self::$_validExtensions, $extensions);
1262: }
1263:
1264: /**
1265: * Loads route configuration
1266: *
1267: * @return void
1268: */
1269: protected static function _loadRoutes() {
1270: self::$initialized = true;
1271: include APP . 'Config' . DS . 'routes.php';
1272: }
1273:
1274: }
1275:
1276: //Save the initial state
1277: Router::reload();
1278: