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