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