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