1: <?php
  2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13: 
 14: 
 15: App::uses('Set', 'Utility');
 16: 
 17:  18:  19:  20:  21:  22:  23:  24:  25: 
 26: class CakeRoute {
 27: 
 28:  29:  30:  31:  32:  33: 
 34:     public $keys = array();
 35: 
 36:  37:  38:  39:  40: 
 41:     public $options = array();
 42: 
 43:  44:  45:  46:  47: 
 48:     public $defaults = array();
 49: 
 50:  51:  52:  53:  54: 
 55:     public $template = null;
 56: 
 57:  58:  59:  60:  61:  62: 
 63:     protected $_greedy = false;
 64: 
 65:  66:  67:  68:  69: 
 70:     protected $_compiledRoute = null;
 71: 
 72:  73:  74:  75:  76: 
 77:     protected $_headerMap = array(
 78:         'type' => 'content_type',
 79:         'method' => 'request_method',
 80:         'server' => 'server_name'
 81:     );
 82: 
 83:  84:  85:  86:  87:  88:  89: 
 90:     public function __construct($template, $defaults = array(), $options = array()) {
 91:         $this->template = $template;
 92:         $this->defaults = (array)$defaults;
 93:         $this->options = (array)$options;
 94:     }
 95: 
 96:  97:  98:  99: 100: 
101:     public function compiled() {
102:         return !empty($this->_compiledRoute);
103:     }
104: 
105: 106: 107: 108: 109: 110: 
111:     public function compile() {
112:         if ($this->compiled()) {
113:             return $this->_compiledRoute;
114:         }
115:         $this->_writeRoute();
116:         return $this->_compiledRoute;
117:     }
118: 
119: 120: 121: 122: 123: 124: 
125:     protected function _writeRoute() {
126:         if (empty($this->template) || ($this->template === '/')) {
127:             $this->_compiledRoute = '#^/*$#';
128:             $this->keys = array();
129:             return;
130:         }
131:         $route = $this->template;
132:         $names = $routeParams = array();
133:         $parsed = preg_quote($this->template, '#');
134: 
135:         preg_match_all('#:([A-Za-z0-9_-]+[A-Z0-9a-z])#', $route, $namedElements);
136:         foreach ($namedElements[1] as $i => $name) {
137:             $search = '\\' . $namedElements[0][$i];
138:             if (isset($this->options[$name])) {
139:                 $option = null;
140:                 if ($name !== 'plugin' && array_key_exists($name, $this->defaults)) {
141:                     $option = '?';
142:                 }
143:                 $slashParam = '/\\' . $namedElements[0][$i];
144:                 if (strpos($parsed, $slashParam) !== false) {
145:                     $routeParams[$slashParam] = '(?:/(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option;
146:                 } else {
147:                     $routeParams[$search] = '(?:(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option;
148:                 }
149:             } else {
150:                 $routeParams[$search] = '(?:(?P<' . $name . '>[^/]+))';
151:             }
152:             $names[] = $name;
153:         }
154:         if (preg_match('#\/\*\*$#', $route)) {
155:             $parsed = preg_replace('#/\\\\\*\\\\\*$#', '(?:/(?P<_trailing_>.*))?', $parsed);
156:             $this->_greedy = true;
157:         } elseif (preg_match('#\/\*$#', $route)) {
158:             $parsed = preg_replace('#/\\\\\*$#', '(?:/(?P<_args_>.*))?', $parsed);
159:             $this->_greedy = true;
160:         }
161:         krsort($routeParams);
162:         $parsed = str_replace(array_keys($routeParams), array_values($routeParams), $parsed);
163:         $this->_compiledRoute = '#^' . $parsed . '[/]*$#';
164:         $this->keys = $names;
165: 
166:         
167:         foreach ($this->keys as $key) {
168:             unset($this->defaults[$key]);
169:         }
170:     }
171: 
172: 173: 174: 175: 176: 177: 178: 179: 
180:     public function parse($url) {
181:         if (!$this->compiled()) {
182:             $this->compile();
183:         }
184:         if (!preg_match($this->_compiledRoute, $url, $route)) {
185:             return false;
186:         }
187:         foreach ($this->defaults as $key => $val) {
188:             $key = (string)$key;
189:             if ($key[0] === '[' && preg_match('/^\[(\w+)\]$/', $key, $header)) {
190:                 if (isset($this->_headerMap[$header[1]])) {
191:                     $header = $this->_headerMap[$header[1]];
192:                 } else {
193:                     $header = 'http_' . $header[1];
194:                 }
195:                 $header = strtoupper($header);
196: 
197:                 $val = (array)$val;
198:                 $h = false;
199: 
200:                 foreach ($val as $v) {
201:                     if (env($header) === $v) {
202:                         $h = true;
203:                     }
204:                 }
205:                 if (!$h) {
206:                     return false;
207:                 }
208:             }
209:         }
210:         array_shift($route);
211:         $count = count($this->keys);
212:         for ($i = 0; $i <= $count; $i++) {
213:             unset($route[$i]);
214:         }
215:         $route['pass'] = $route['named'] = array();
216: 
217:         
218:         foreach ($this->defaults as $key => $value) {
219:             if (isset($route[$key])) {
220:                 continue;
221:             }
222:             if (is_integer($key)) {
223:                 $route['pass'][] = $value;
224:                 continue;
225:             }
226:             $route[$key] = $value;
227:         }
228: 
229:         foreach ($this->keys as $key) {
230:             if (isset($route[$key])) {
231:                 $route[$key] = rawurldecode($route[$key]);
232:             }
233:         }
234: 
235:         if (isset($route['_args_'])) {
236:             list($pass, $named) = $this->_parseArgs($route['_args_'], $route);
237:             $route['pass'] = array_merge($route['pass'], $pass);
238:             $route['named'] = $named;
239:             unset($route['_args_']);
240:         }
241: 
242:         if (isset($route['_trailing_'])) {
243:             $route['pass'][] = rawurldecode($route['_trailing_']);
244:             unset($route['_trailing_']);
245:         }
246: 
247:         
248:         if (isset($this->options['pass'])) {
249:             $j = count($this->options['pass']);
250:             while ($j--) {
251:                 if (isset($route[$this->options['pass'][$j]])) {
252:                     array_unshift($route['pass'], $route[$this->options['pass'][$j]]);
253:                 }
254:             }
255:         }
256:         return $route;
257:     }
258: 
259: 260: 261: 262: 263: 264: 265: 266: 
267:     protected function _parseArgs($args, $context) {
268:         $pass = $named = array();
269:         $args = explode('/', $args);
270: 
271:         $namedConfig = Router::namedConfig();
272:         $greedy = $namedConfig['greedyNamed'];
273:         $rules = $namedConfig['rules'];
274:         if (!empty($this->options['named'])) {
275:             $greedy = isset($this->options['greedyNamed']) && $this->options['greedyNamed'] === true;
276:             foreach ((array)$this->options['named'] as $key => $val) {
277:                 if (is_numeric($key)) {
278:                     $rules[$val] = true;
279:                     continue;
280:                 }
281:                 $rules[$key] = $val;
282:             }
283:         }
284: 
285:         foreach ($args as $param) {
286:             if (empty($param) && $param !== '0' && $param !== 0) {
287:                 continue;
288:             }
289: 
290:             $separatorIsPresent = strpos($param, $namedConfig['separator']) !== false;
291:             if ((!isset($this->options['named']) || !empty($this->options['named'])) && $separatorIsPresent) {
292:                 list($key, $val) = explode($namedConfig['separator'], $param, 2);
293:                 $key = rawurldecode($key);
294:                 $val = rawurldecode($val);
295:                 $hasRule = isset($rules[$key]);
296:                 $passIt = (!$hasRule && !$greedy) || ($hasRule && !$this->_matchNamed($val, $rules[$key], $context));
297:                 if ($passIt) {
298:                     $pass[] = rawurldecode($param);
299:                 } else {
300:                     if (preg_match_all('/\[([A-Za-z0-9_-]+)?\]/', $key, $matches, PREG_SET_ORDER)) {
301:                         $matches = array_reverse($matches);
302:                         $parts = explode('[', $key);
303:                         $key = array_shift($parts);
304:                         $arr = $val;
305:                         foreach ($matches as $match) {
306:                             if (empty($match[1])) {
307:                                 $arr = array($arr);
308:                             } else {
309:                                 $arr = array(
310:                                     $match[1] => $arr
311:                                 );
312:                             }
313:                         }
314:                         $val = $arr;
315:                     }
316:                     $named = array_merge_recursive($named, array($key => $val));
317:                 }
318:             } else {
319:                 $pass[] = rawurldecode($param);
320:             }
321:         }
322:         return array($pass, $named);
323:     }
324: 
325: 326: 327: 328: 329: 330: 331: 332: 333: 
334:     protected function _matchNamed($val, $rule, $context) {
335:         if ($rule === true || $rule === false) {
336:             return $rule;
337:         }
338:         if (is_string($rule)) {
339:             $rule = array('match' => $rule);
340:         }
341:         if (!is_array($rule)) {
342:             return false;
343:         }
344: 
345:         $controllerMatches = (
346:             !isset($rule['controller'], $context['controller']) ||
347:             in_array($context['controller'], (array)$rule['controller'])
348:         );
349:         if (!$controllerMatches) {
350:             return false;
351:         }
352:         $actionMatches = (
353:             !isset($rule['action'], $context['action']) ||
354:             in_array($context['action'], (array)$rule['action'])
355:         );
356:         if (!$actionMatches) {
357:             return false;
358:         }
359:         return (!isset($rule['match']) || preg_match('/' . $rule['match'] . '/', $val));
360:     }
361: 
362: 363: 364: 365: 366: 367: 368: 369: 370: 
371:     public function persistParams($url, $params) {
372:         foreach ($this->options['persist'] as $persistKey) {
373:             if (array_key_exists($persistKey, $params) && !isset($url[$persistKey])) {
374:                 $url[$persistKey] = $params[$persistKey];
375:             }
376:         }
377:         return $url;
378:     }
379: 
380: 381: 382: 383: 384: 385: 386: 387: 
388:     public function match($url) {
389:         if (!$this->compiled()) {
390:             $this->compile();
391:         }
392:         $defaults = $this->defaults;
393: 
394:         if (isset($defaults['prefix'])) {
395:             $url['prefix'] = $defaults['prefix'];
396:         }
397: 
398:         
399:         $keyNames = array_flip($this->keys);
400:         if (array_intersect_key($keyNames, $url) !== $keyNames) {
401:             return false;
402:         }
403: 
404:         
405:         if (array_diff_key($defaults, $url) !== array()) {
406:             return false;
407:         }
408: 
409:         $namedConfig = Router::namedConfig();
410:         $prefixes = Router::prefixes();
411:         $greedyNamed = $namedConfig['greedyNamed'];
412:         $allowedNamedParams = $namedConfig['rules'];
413: 
414:         $named = $pass = array();
415: 
416:         foreach ($url as $key => $value) {
417: 
418:             
419:             $defaultExists = array_key_exists($key, $defaults);
420:             if ($defaultExists && $defaults[$key] != $value) {
421:                 return false;
422:             } elseif ($defaultExists) {
423:                 continue;
424:             }
425: 
426:             
427:             if (array_key_exists($key, $keyNames)) {
428:                 continue;
429:             }
430: 
431:             
432:             $numeric = is_numeric($key);
433:             if ($numeric && isset($defaults[$key]) && $defaults[$key] == $value) {
434:                 continue;
435:             } elseif ($numeric) {
436:                 $pass[] = $value;
437:                 unset($url[$key]);
438:                 continue;
439:             }
440: 
441:             
442:             if (
443:                 ($greedyNamed || isset($allowedNamedParams[$key])) &&
444:                 ($value !== false && $value !== null) &&
445:                 (!in_array($key, $prefixes))
446:             ) {
447:                 $named[$key] = $value;
448:                 continue;
449:             }
450: 
451:             
452:             if (!$defaultExists && !empty($value)) {
453:                 return false;
454:             }
455:         }
456: 
457:         
458:         if (!$this->_greedy && (!empty($pass) || !empty($named))) {
459:             return false;
460:         }
461: 
462:         
463:         if (!empty($this->options)) {
464:             foreach ($this->options as $key => $pattern) {
465:                 if (array_key_exists($key, $url) && !preg_match('#^' . $pattern . '$#', $url[$key])) {
466:                     return false;
467:                 }
468:             }
469:         }
470:         return $this->_writeUrl(array_merge($url, compact('pass', 'named')));
471:     }
472: 
473: 474: 475: 476: 477: 478: 479: 
480:     protected function _writeUrl($params) {
481:         if (isset($params['prefix'])) {
482:             $prefixed = $params['prefix'] . '_';
483:         }
484:         if (isset($prefixed, $params['action']) && strpos($params['action'], $prefixed) === 0) {
485:             $params['action'] = substr($params['action'], strlen($prefixed) * -1);
486:             unset($params['prefix']);
487:         }
488: 
489:         if (is_array($params['pass'])) {
490:             $params['pass'] = implode('/', array_map('rawurlencode', $params['pass']));
491:         }
492: 
493:         $namedConfig = Router::namedConfig();
494:         $separator = $namedConfig['separator'];
495: 
496:         if (!empty($params['named']) && is_array($params['named'])) {
497:             $named = array();
498:             foreach ($params['named'] as $key => $value) {
499:                 if (is_array($value)) {
500:                     $flat = Set::flatten($value, '][');
501:                     foreach ($flat as $namedKey => $namedValue) {
502:                         $named[] = $key . "[$namedKey]" . $separator . rawurlencode($namedValue);
503:                     }
504:                 } else {
505:                     $named[] = $key . $separator . rawurlencode($value);
506:                 }
507:             }
508:             $params['pass'] = $params['pass'] . '/' . implode('/', $named);
509:         }
510:         $out = $this->template;
511: 
512:         $search = $replace = array();
513:         foreach ($this->keys as $key) {
514:             $string = null;
515:             if (isset($params[$key])) {
516:                 $string = $params[$key];
517:             } elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
518:                 $key .= '/';
519:             }
520:             $search[] = ':' . $key;
521:             $replace[] = $string;
522:         }
523:         $out = str_replace($search, $replace, $out);
524: 
525:         if (strpos($this->template, '*')) {
526:             $out = str_replace('*', $params['pass'], $out);
527:         }
528:         $out = str_replace('//', '/', $out);
529:         return $out;
530:     }
531: 
532: }
533: