1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Application\Routers;
9:
10: use Nette;
11: use Nette\Application;
12: use Nette\Utils\Strings;
13:
14:
15: 16: 17: 18: 19: 20:
21: class Route extends Nette\Object implements Application\IRouter
22: {
23: const PRESENTER_KEY = 'presenter';
24: const MODULE_KEY = 'module';
25:
26:
27: const CASE_SENSITIVE = 256;
28:
29:
30: const HOST = 1,
31: PATH = 2,
32: RELATIVE = 3;
33:
34:
35: const VALUE = 'value';
36: const PATTERN = 'pattern';
37: const FILTER_IN = 'filterIn';
38: const FILTER_OUT = 'filterOut';
39: const FILTER_TABLE = 'filterTable';
40: const FILTER_STRICT = 'filterStrict';
41:
42:
43: const OPTIONAL = 0,
44: PATH_OPTIONAL = 1,
45: CONSTANT = 2;
46:
47:
48: public static $defaultFlags = 0;
49:
50:
51: public static $styles = array(
52: '#' => array(
53: self::PATTERN => '[^/]+',
54: self::FILTER_OUT => array(__CLASS__, 'param2path'),
55: ),
56: '?#' => array(
57: ),
58: 'module' => array(
59: self::PATTERN => '[a-z][a-z0-9.-]*',
60: self::FILTER_IN => array(__CLASS__, 'path2presenter'),
61: self::FILTER_OUT => array(__CLASS__, 'presenter2path'),
62: ),
63: 'presenter' => array(
64: self::PATTERN => '[a-z][a-z0-9.-]*',
65: self::FILTER_IN => array(__CLASS__, 'path2presenter'),
66: self::FILTER_OUT => array(__CLASS__, 'presenter2path'),
67: ),
68: 'action' => array(
69: self::PATTERN => '[a-z][a-z0-9-]*',
70: self::FILTER_IN => array(__CLASS__, 'path2action'),
71: self::FILTER_OUT => array(__CLASS__, 'action2path'),
72: ),
73: '?module' => array(
74: ),
75: '?presenter' => array(
76: ),
77: '?action' => array(
78: ),
79: );
80:
81:
82: private $mask;
83:
84:
85: private $sequence;
86:
87:
88: private $re;
89:
90:
91: private $aliases;
92:
93:
94: private $metadata = array();
95:
96:
97: private $xlat;
98:
99:
100: private $type;
101:
102:
103: private $flags;
104:
105:
106: private $lastRefUrl;
107:
108:
109: private $lastBaseUrl;
110:
111:
112: 113: 114: 115: 116:
117: public function __construct($mask, $metadata = array(), $flags = 0)
118: {
119: if (is_string($metadata)) {
120: $a = strrpos($tmp = $metadata, ':');
121: if (!$a) {
122: throw new Nette\InvalidArgumentException("Second argument must be array or string in format Presenter:action, '$metadata' given.");
123: }
124: $metadata = array(self::PRESENTER_KEY => substr($tmp, 0, $a));
125: if ($a < strlen($tmp) - 1) {
126: $metadata['action'] = substr($tmp, $a + 1);
127: }
128: } elseif ($metadata instanceof \Closure || $metadata instanceof Nette\Callback) {
129: $metadata = array(
130: self::PRESENTER_KEY => 'Nette:Micro',
131: 'callback' => $metadata,
132: );
133: }
134:
135: $this->flags = $flags | static::$defaultFlags;
136: $this->setMask($mask, $metadata);
137: }
138:
139:
140: 141: 142: 143:
144: public function match(Nette\Http\IRequest $httpRequest)
145: {
146:
147:
148:
149: $url = $httpRequest->getUrl();
150: $re = $this->re;
151:
152: if ($this->type === self::HOST) {
153: $host = $url->getHost();
154: $path = '//' . $host . $url->getPath();
155: $host = ip2long($host) ? array($host) : array_reverse(explode('.', $host));
156: $re = strtr($re, array(
157: '/%basePath%/' => preg_quote($url->getBasePath(), '#'),
158: '%tld%' => preg_quote($host[0], '#'),
159: '%domain%' => preg_quote(isset($host[1]) ? "$host[1].$host[0]" : $host[0], '#'),
160: ));
161:
162: } elseif ($this->type === self::RELATIVE) {
163: $basePath = $url->getBasePath();
164: if (strncmp($url->getPath(), $basePath, strlen($basePath)) !== 0) {
165: return NULL;
166: }
167: $path = (string) substr($url->getPath(), strlen($basePath));
168:
169: } else {
170: $path = $url->getPath();
171: }
172:
173: if ($path !== '') {
174: $path = rtrim(rawurldecode($path), '/') . '/';
175: }
176:
177: if (!$matches = Strings::match($path, $re)) {
178:
179: return NULL;
180: }
181:
182:
183: $params = array();
184: foreach ($matches as $k => $v) {
185: if (is_string($k) && $v !== '') {
186: $params[$this->aliases[$k]] = $v;
187: }
188: }
189:
190:
191:
192: foreach ($this->metadata as $name => $meta) {
193: if (isset($params[$name])) {
194:
195:
196: } elseif (isset($meta['fixity']) && $meta['fixity'] !== self::OPTIONAL) {
197: $params[$name] = NULL;
198: }
199: }
200:
201:
202:
203: if ($this->xlat) {
204: $params += self::renameKeys($httpRequest->getQuery(), array_flip($this->xlat));
205: } else {
206: $params += $httpRequest->getQuery();
207: }
208:
209:
210:
211: foreach ($this->metadata as $name => $meta) {
212: if (isset($params[$name])) {
213: if (!is_scalar($params[$name])) {
214:
215: } elseif (isset($meta[self::FILTER_TABLE][$params[$name]])) {
216: $params[$name] = $meta[self::FILTER_TABLE][$params[$name]];
217:
218: } elseif (isset($meta[self::FILTER_TABLE]) && !empty($meta[self::FILTER_STRICT])) {
219: return NULL;
220:
221: } elseif (isset($meta[self::FILTER_IN])) {
222: $params[$name] = call_user_func($meta[self::FILTER_IN], (string) $params[$name]);
223: if ($params[$name] === NULL && !isset($meta['fixity'])) {
224: return NULL;
225: }
226: }
227:
228: } elseif (isset($meta['fixity'])) {
229: $params[$name] = $meta[self::VALUE];
230: }
231: }
232:
233: if (isset($this->metadata[NULL][self::FILTER_IN])) {
234: $params = call_user_func($this->metadata[NULL][self::FILTER_IN], $params);
235: if ($params === NULL) {
236: return NULL;
237: }
238: }
239:
240:
241: if (!isset($params[self::PRESENTER_KEY])) {
242: throw new Nette\InvalidStateException('Missing presenter in route definition.');
243: } elseif (!is_string($params[self::PRESENTER_KEY])) {
244: return NULL;
245: }
246: if (isset($this->metadata[self::MODULE_KEY])) {
247: if (!isset($params[self::MODULE_KEY])) {
248: throw new Nette\InvalidStateException('Missing module in route definition.');
249: }
250: $presenter = $params[self::MODULE_KEY] . ':' . $params[self::PRESENTER_KEY];
251: unset($params[self::MODULE_KEY], $params[self::PRESENTER_KEY]);
252:
253: } else {
254: $presenter = $params[self::PRESENTER_KEY];
255: unset($params[self::PRESENTER_KEY]);
256: }
257:
258: return new Application\Request(
259: $presenter,
260: $httpRequest->getMethod(),
261: $params,
262: $httpRequest->getPost(),
263: $httpRequest->getFiles(),
264: array(Application\Request::SECURED => $httpRequest->isSecured())
265: );
266: }
267:
268:
269: 270: 271: 272:
273: public function constructUrl(Application\Request $appRequest, Nette\Http\Url $refUrl)
274: {
275: if ($this->flags & self::ONE_WAY) {
276: return NULL;
277: }
278:
279: $params = $appRequest->getParameters();
280: $metadata = $this->metadata;
281:
282: $presenter = $appRequest->getPresenterName();
283: $params[self::PRESENTER_KEY] = $presenter;
284:
285: if (isset($metadata[NULL][self::FILTER_OUT])) {
286: $params = call_user_func($metadata[NULL][self::FILTER_OUT], $params);
287: if ($params === NULL) {
288: return NULL;
289: }
290: }
291:
292: if (isset($metadata[self::MODULE_KEY])) {
293: $module = $metadata[self::MODULE_KEY];
294: if (isset($module['fixity']) && strncasecmp($presenter, $module[self::VALUE] . ':', strlen($module[self::VALUE]) + 1) === 0) {
295: $a = strlen($module[self::VALUE]);
296: } else {
297: $a = strrpos($presenter, ':');
298: }
299: if ($a === FALSE) {
300: $params[self::MODULE_KEY] = '';
301: } else {
302: $params[self::MODULE_KEY] = substr($presenter, 0, $a);
303: $params[self::PRESENTER_KEY] = substr($presenter, $a + 1);
304: }
305: }
306:
307: foreach ($metadata as $name => $meta) {
308: if (!isset($params[$name])) {
309: continue;
310: }
311:
312: if (isset($meta['fixity'])) {
313: if ($params[$name] === FALSE) {
314: $params[$name] = '0';
315: }
316: if (is_scalar($params[$name]) ? strcasecmp($params[$name], $meta[self::VALUE]) === 0
317: : $params[$name] === $meta[self::VALUE]
318: ) {
319: unset($params[$name]);
320: continue;
321:
322: } elseif ($meta['fixity'] === self::CONSTANT) {
323: return NULL;
324: }
325: }
326:
327: if (is_scalar($params[$name]) && isset($meta['filterTable2'][$params[$name]])) {
328: $params[$name] = $meta['filterTable2'][$params[$name]];
329:
330: } elseif (isset($meta['filterTable2']) && !empty($meta[self::FILTER_STRICT])) {
331: return NULL;
332:
333: } elseif (isset($meta[self::FILTER_OUT])) {
334: $params[$name] = call_user_func($meta[self::FILTER_OUT], $params[$name]);
335: }
336:
337: if (isset($meta[self::PATTERN]) && !preg_match($meta[self::PATTERN], rawurldecode($params[$name]))) {
338: return NULL;
339: }
340: }
341:
342:
343: $sequence = $this->sequence;
344: $brackets = array();
345: $required = NULL;
346: $url = '';
347: $i = count($sequence) - 1;
348: do {
349: $url = $sequence[$i] . $url;
350: if ($i === 0) {
351: break;
352: }
353: $i--;
354:
355: $name = $sequence[$i]; $i--;
356:
357: if ($name === ']') {
358: $brackets[] = $url;
359:
360: } elseif ($name[0] === '[') {
361: $tmp = array_pop($brackets);
362: if ($required < count($brackets) + 1) {
363: if ($name !== '[!') {
364: $url = $tmp;
365: }
366: } else {
367: $required = count($brackets);
368: }
369:
370: } elseif ($name[0] === '?') {
371: continue;
372:
373: } elseif (isset($params[$name]) && $params[$name] != '') {
374: $required = count($brackets);
375: $url = $params[$name] . $url;
376: unset($params[$name]);
377:
378: } elseif (isset($metadata[$name]['fixity'])) {
379: if ($required === NULL && !$brackets) {
380: $url = '';
381: } else {
382: $url = $metadata[$name]['defOut'] . $url;
383: }
384:
385: } else {
386: return NULL;
387: }
388: } while (TRUE);
389:
390:
391: if ($this->type !== self::HOST) {
392: if ($this->lastRefUrl !== $refUrl) {
393: $scheme = ($this->flags & self::SECURED ? 'https://' : 'http://');
394: $basePath = ($this->type === self::RELATIVE ? $refUrl->getBasePath() : '');
395: $this->lastBaseUrl = $scheme . $refUrl->getAuthority() . $basePath;
396: $this->lastRefUrl = $refUrl;
397: }
398: $url = $this->lastBaseUrl . $url;
399:
400: } else {
401: $host = $refUrl->getHost();
402: $host = ip2long($host) ? array($host) : array_reverse(explode('.', $host));
403: $url = strtr($url, array(
404: '/%basePath%/' => $refUrl->getBasePath(),
405: '%tld%' => $host[0],
406: '%domain%' => isset($host[1]) ? "$host[1].$host[0]" : $host[0],
407: ));
408: $url = ($this->flags & self::SECURED ? 'https:' : 'http:') . $url;
409: }
410:
411: if (strpos($url, '//', 7) !== FALSE) {
412: return NULL;
413: }
414:
415:
416: if ($this->xlat) {
417: $params = self::renameKeys($params, $this->xlat);
418: }
419:
420: $sep = ini_get('arg_separator.input');
421: $query = http_build_query($params, '', $sep ? $sep[0] : '&');
422: if ($query != '') {
423: $url .= '?' . $query;
424: }
425:
426: return $url;
427: }
428:
429:
430: 431: 432: 433: 434: 435:
436: private function setMask($mask, array $metadata)
437: {
438: $this->mask = $mask;
439:
440:
441: if (substr($mask, 0, 2) === '//') {
442: $this->type = self::HOST;
443:
444: } elseif (substr($mask, 0, 1) === '/') {
445: $this->type = self::PATH;
446:
447: } else {
448: $this->type = self::RELATIVE;
449: }
450:
451: foreach ($metadata as $name => $meta) {
452: if (!is_array($meta)) {
453: $metadata[$name] = array(self::VALUE => $meta, 'fixity' => self::CONSTANT);
454:
455: } elseif (array_key_exists(self::VALUE, $meta)) {
456: $metadata[$name]['fixity'] = self::CONSTANT;
457: }
458: }
459:
460: if (strpbrk($mask, '?<[') === FALSE) {
461: $this->re = '#' . preg_quote($mask, '#') . '/?\z#A';
462: $this->sequence = array($mask);
463: $this->metadata = $metadata;
464: return;
465: }
466:
467:
468:
469: $parts = Strings::split($mask, '/<([^>#= ]+)(=[^># ]*)? *([^>#]*)(#?[^>\[\]]*)>|(\[!?|\]|\s*\?.*)/');
470:
471: $this->xlat = array();
472: $i = count($parts) - 1;
473:
474:
475: if (isset($parts[$i - 1]) && substr(ltrim($parts[$i - 1]), 0, 1) === '?') {
476:
477: $matches = Strings::matchAll($parts[$i - 1], '/(?:([a-zA-Z0-9_.-]+)=)?<([^># ]+) *([^>#]*)(#?[^>]*)>/');
478:
479: foreach ($matches as $match) {
480: list(, $param, $name, $pattern, $class) = $match;
481:
482: if ($class !== '') {
483: if (!isset(static::$styles[$class])) {
484: throw new Nette\InvalidStateException("Parameter '$name' has '$class' flag, but Route::\$styles['$class'] is not set.");
485: }
486: $meta = static::$styles[$class];
487:
488: } elseif (isset(static::$styles['?' . $name])) {
489: $meta = static::$styles['?' . $name];
490:
491: } else {
492: $meta = static::$styles['?#'];
493: }
494:
495: if (isset($metadata[$name])) {
496: $meta = $metadata[$name] + $meta;
497: }
498:
499: if (array_key_exists(self::VALUE, $meta)) {
500: $meta['fixity'] = self::OPTIONAL;
501: }
502:
503: unset($meta['pattern']);
504: $meta['filterTable2'] = empty($meta[self::FILTER_TABLE]) ? NULL : array_flip($meta[self::FILTER_TABLE]);
505:
506: $metadata[$name] = $meta;
507: if ($param !== '') {
508: $this->xlat[$name] = $param;
509: }
510: }
511: $i -= 6;
512: }
513:
514:
515: $brackets = 0;
516: $re = '';
517: $sequence = array();
518: $autoOptional = TRUE;
519: $aliases = array();
520: do {
521: array_unshift($sequence, $parts[$i]);
522: $re = preg_quote($parts[$i], '#') . $re;
523: if ($i === 0) {
524: break;
525: }
526: $i--;
527:
528: $part = $parts[$i];
529: if ($part === '[' || $part === ']' || $part === '[!') {
530: $brackets += $part[0] === '[' ? -1 : 1;
531: if ($brackets < 0) {
532: throw new Nette\InvalidArgumentException("Unexpected '$part' in mask '$mask'.");
533: }
534: array_unshift($sequence, $part);
535: $re = ($part[0] === '[' ? '(?:' : ')?') . $re;
536: $i -= 5;
537: continue;
538: }
539:
540: $class = $parts[$i]; $i--;
541: $pattern = trim($parts[$i]); $i--;
542: $default = $parts[$i]; $i--;
543: $name = $parts[$i]; $i--;
544: array_unshift($sequence, $name);
545:
546: if ($name[0] === '?') {
547: $name = substr($name, 1);
548: $re = $pattern ? '(?:' . preg_quote($name, '#') . "|$pattern)$re" : preg_quote($name, '#') . $re;
549: $sequence[1] = $name . $sequence[1];
550: continue;
551: }
552:
553:
554: if ($class !== '') {
555: if (!isset(static::$styles[$class])) {
556: throw new Nette\InvalidStateException("Parameter '$name' has '$class' flag, but Route::\$styles['$class'] is not set.");
557: }
558: $meta = static::$styles[$class];
559:
560: } elseif (isset(static::$styles[$name])) {
561: $meta = static::$styles[$name];
562:
563: } else {
564: $meta = static::$styles['#'];
565: }
566:
567: if (isset($metadata[$name])) {
568: $meta = $metadata[$name] + $meta;
569: }
570:
571: if ($pattern == '' && isset($meta[self::PATTERN])) {
572: $pattern = $meta[self::PATTERN];
573: }
574:
575: if ($default !== '') {
576: $meta[self::VALUE] = (string) substr($default, 1);
577: $meta['fixity'] = self::PATH_OPTIONAL;
578: }
579:
580: $meta['filterTable2'] = empty($meta[self::FILTER_TABLE]) ? NULL : array_flip($meta[self::FILTER_TABLE]);
581: if (array_key_exists(self::VALUE, $meta)) {
582: if (isset($meta['filterTable2'][$meta[self::VALUE]])) {
583: $meta['defOut'] = $meta['filterTable2'][$meta[self::VALUE]];
584:
585: } elseif (isset($meta[self::FILTER_OUT])) {
586: $meta['defOut'] = call_user_func($meta[self::FILTER_OUT], $meta[self::VALUE]);
587:
588: } else {
589: $meta['defOut'] = $meta[self::VALUE];
590: }
591: }
592: $meta[self::PATTERN] = "#(?:$pattern)\\z#A" . ($this->flags & self::CASE_SENSITIVE ? '' : 'iu');
593:
594:
595: $aliases['p' . $i] = $name;
596: $re = '(?P<p' . $i . '>(?U)' . $pattern . ')' . $re;
597: if ($brackets) {
598: if (!isset($meta[self::VALUE])) {
599: $meta[self::VALUE] = $meta['defOut'] = NULL;
600: }
601: $meta['fixity'] = self::PATH_OPTIONAL;
602:
603: } elseif (!$autoOptional) {
604: unset($meta['fixity']);
605:
606: } elseif (isset($meta['fixity'])) {
607: $re = '(?:' . $re . ')?';
608: $meta['fixity'] = self::PATH_OPTIONAL;
609:
610: } else {
611: $autoOptional = FALSE;
612: }
613:
614: $metadata[$name] = $meta;
615: } while (TRUE);
616:
617: if ($brackets) {
618: throw new Nette\InvalidArgumentException("Missing closing ']' in mask '$mask'.");
619: }
620:
621: $this->aliases = $aliases;
622: $this->re = '#' . $re . '/?\z#A' . ($this->flags & self::CASE_SENSITIVE ? '' : 'iu');
623: $this->metadata = $metadata;
624: $this->sequence = $sequence;
625: }
626:
627:
628: 629: 630: 631:
632: public function getMask()
633: {
634: return $this->mask;
635: }
636:
637:
638: 639: 640: 641:
642: public function getDefaults()
643: {
644: $defaults = array();
645: foreach ($this->metadata as $name => $meta) {
646: if (isset($meta['fixity'])) {
647: $defaults[$name] = $meta[self::VALUE];
648: }
649: }
650: return $defaults;
651: }
652:
653:
654: 655: 656: 657:
658: public function getFlags()
659: {
660: return $this->flags;
661: }
662:
663:
664:
665:
666:
667: 668: 669: 670: 671:
672: public function getTargetPresenter()
673: {
674: if ($this->flags & self::ONE_WAY) {
675: return FALSE;
676: }
677:
678: $m = $this->metadata;
679: $module = '';
680:
681: if (isset($m[self::MODULE_KEY])) {
682: if (isset($m[self::MODULE_KEY]['fixity']) && $m[self::MODULE_KEY]['fixity'] === self::CONSTANT) {
683: $module = $m[self::MODULE_KEY][self::VALUE] . ':';
684: } else {
685: return NULL;
686: }
687: }
688:
689: if (isset($m[self::PRESENTER_KEY]['fixity']) && $m[self::PRESENTER_KEY]['fixity'] === self::CONSTANT) {
690: return $module . $m[self::PRESENTER_KEY][self::VALUE];
691: }
692: return NULL;
693: }
694:
695:
696: 697: 698: 699: 700: 701:
702: private static function renameKeys($arr, $xlat)
703: {
704: if (empty($xlat)) {
705: return $arr;
706: }
707:
708: $res = array();
709: $occupied = array_flip($xlat);
710: foreach ($arr as $k => $v) {
711: if (isset($xlat[$k])) {
712: $res[$xlat[$k]] = $v;
713:
714: } elseif (!isset($occupied[$k])) {
715: $res[$k] = $v;
716: }
717: }
718: return $res;
719: }
720:
721:
722:
723:
724:
725: 726: 727: 728: 729:
730: private static function action2path($s)
731: {
732: $s = preg_replace('#(.)(?=[A-Z])#', '$1-', $s);
733: $s = strtolower($s);
734: $s = rawurlencode($s);
735: return $s;
736: }
737:
738:
739: 740: 741: 742: 743:
744: private static function path2action($s)
745: {
746: $s = strtolower($s);
747: $s = preg_replace('#-(?=[a-z])#', ' ', $s);
748: $s = lcfirst(ucwords($s));
749: $s = str_replace(' ', '', $s);
750: return $s;
751: }
752:
753:
754: 755: 756: 757: 758:
759: private static function presenter2path($s)
760: {
761: $s = strtr($s, ':', '.');
762: $s = preg_replace('#([^.])(?=[A-Z])#', '$1-', $s);
763: $s = strtolower($s);
764: $s = rawurlencode($s);
765: return $s;
766: }
767:
768:
769: 770: 771: 772: 773:
774: private static function path2presenter($s)
775: {
776: $s = strtolower($s);
777: $s = preg_replace('#([.-])(?=[a-z])#', '$1 ', $s);
778: $s = ucwords($s);
779: $s = str_replace('. ', ':', $s);
780: $s = str_replace('- ', '', $s);
781: return $s;
782: }
783:
784:
785: 786: 787: 788: 789:
790: private static function param2path($s)
791: {
792: return str_replace('%2F', '/', rawurlencode($s));
793: }
794:
795:
796:
797:
798:
799: 800: 801:
802: public static function addStyle($style, $parent = '#')
803: {
804: if (isset(static::$styles[$style])) {
805: throw new Nette\InvalidArgumentException("Style '$style' already exists.");
806: }
807:
808: if ($parent !== NULL) {
809: if (!isset(static::$styles[$parent])) {
810: throw new Nette\InvalidArgumentException("Parent style '$parent' doesn't exist.");
811: }
812: static::$styles[$style] = static::$styles[$parent];
813:
814: } else {
815: static::$styles[$style] = array();
816: }
817: }
818:
819:
820: 821: 822:
823: public static function setStyleProperty($style, $key, $value)
824: {
825: if (!isset(static::$styles[$style])) {
826: throw new Nette\InvalidArgumentException("Style '$style' doesn't exist.");
827: }
828: static::$styles[$style][$key] = $value;
829: }
830:
831: }
832: