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