1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Application\UI;
9:
10: use Nette,
11: Nette\Application,
12: Nette\Application\Responses,
13: Nette\Http,
14: Nette\Reflection;
15:
16:
17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34:
35: abstract class Presenter extends Control implements Application\IPresenter
36: {
37:
38: const INVALID_LINK_SILENT = 1,
39: INVALID_LINK_WARNING = 2,
40: INVALID_LINK_EXCEPTION = 3;
41:
42:
43: const SIGNAL_KEY = 'do',
44: ACTION_KEY = 'action',
45: FLASH_KEY = '_fid',
46: DEFAULT_ACTION = 'default';
47:
48:
49: public $invalidLinkMode;
50:
51:
52: public $onShutdown;
53:
54:
55: private $request;
56:
57:
58: private $response;
59:
60:
61: public $autoCanonicalize = TRUE;
62:
63:
64: public $absoluteUrls = FALSE;
65:
66:
67: private $globalParams;
68:
69:
70: private $globalState;
71:
72:
73: private $globalStateSinces;
74:
75:
76: private $action;
77:
78:
79: private $view;
80:
81:
82: private $layout;
83:
84:
85: private $payload;
86:
87:
88: private $signalReceiver;
89:
90:
91: private $signal;
92:
93:
94: private $ajaxMode;
95:
96:
97: private $startupCheck;
98:
99:
100: private $lastCreatedRequest;
101:
102:
103: private $lastCreatedRequestFlag;
104:
105:
106: private $context;
107:
108:
109: private $httpRequest;
110:
111:
112: private $httpResponse;
113:
114:
115: private $session;
116:
117:
118: private $presenterFactory;
119:
120:
121: private $router;
122:
123:
124: private $user;
125:
126:
127: private $templateFactory;
128:
129:
130: public function __construct()
131: {
132: $this->payload = new \stdClass;
133: }
134:
135:
136: 137: 138:
139: public function getRequest()
140: {
141: return $this->request;
142: }
143:
144:
145: 146: 147: 148:
149: public function getPresenter($need = TRUE)
150: {
151: return $this;
152: }
153:
154:
155: 156: 157: 158:
159: public function getUniqueId()
160: {
161: return '';
162: }
163:
164:
165:
166:
167:
168: 169: 170:
171: public function run(Application\Request $request)
172: {
173: try {
174:
175: $this->request = $request;
176: $this->payload = $this->payload ?: new \stdClass;
177: $this->setParent($this->getParent(), $request->getPresenterName());
178:
179: if (!$this->httpResponse->isSent()) {
180: $this->httpResponse->addHeader('Vary', 'X-Requested-With');
181: }
182:
183: $this->initGlobalParameters();
184: $this->checkRequirements($this->getReflection());
185: $this->startup();
186: if (!$this->startupCheck) {
187: $class = $this->getReflection()->getMethod('startup')->getDeclaringClass()->getName();
188: throw new Nette\InvalidStateException("Method $class::startup() or its descendant doesn't call parent::startup().");
189: }
190:
191: $this->tryCall($this->formatActionMethod($this->action), $this->params);
192:
193:
194: foreach ($this->globalParams as $id => $foo) {
195: $this->getComponent($id, FALSE);
196: }
197:
198: if ($this->autoCanonicalize) {
199: $this->canonicalize();
200: }
201: if ($this->httpRequest->isMethod('head')) {
202: $this->terminate();
203: }
204:
205:
206:
207: $this->processSignal();
208:
209:
210: $this->beforeRender();
211:
212: $this->tryCall($this->formatRenderMethod($this->view), $this->params);
213: $this->afterRender();
214:
215:
216: $this->saveGlobalState();
217: if ($this->isAjax()) {
218: $this->payload->state = $this->getGlobalState();
219: }
220:
221:
222: $this->sendTemplate();
223:
224: } catch (Application\AbortException $e) {
225:
226: if ($this->isAjax()) try {
227: $hasPayload = (array) $this->payload; unset($hasPayload['state']);
228: if ($this->response instanceof Responses\TextResponse && $this->isControlInvalid()) {
229: $this->snippetMode = TRUE;
230: $this->response->send($this->httpRequest, $this->httpResponse);
231: $this->sendPayload();
232:
233: } elseif (!$this->response && $hasPayload) {
234: $this->sendPayload();
235: }
236: } catch (Application\AbortException $e) { }
237:
238: if ($this->hasFlashSession()) {
239: $this->getFlashSession()->setExpiration($this->response instanceof Responses\RedirectResponse ? '+ 30 seconds' : '+ 3 seconds');
240: }
241:
242:
243: $this->onShutdown($this, $this->response);
244: $this->shutdown($this->response);
245:
246: return $this->response;
247: }
248: }
249:
250:
251: 252: 253:
254: protected function startup()
255: {
256: $this->startupCheck = TRUE;
257: }
258:
259:
260: 261: 262: 263:
264: protected function beforeRender()
265: {
266: }
267:
268:
269: 270: 271: 272:
273: protected function afterRender()
274: {
275: }
276:
277:
278: 279: 280: 281:
282: protected function shutdown($response)
283: {
284: }
285:
286:
287: 288: 289: 290:
291: public function checkRequirements($element)
292: {
293: $user = (array) $element->getAnnotation('User');
294: if (in_array('loggedIn', $user, TRUE) && !$this->getUser()->isLoggedIn()) {
295: throw new Application\ForbiddenRequestException;
296: }
297: }
298:
299:
300:
301:
302:
303: 304: 305: 306:
307: public function processSignal()
308: {
309: if ($this->signal === NULL) {
310: return;
311: }
312:
313: try {
314: $component = $this->signalReceiver === '' ? $this : $this->getComponent($this->signalReceiver, FALSE);
315: } catch (Nette\InvalidArgumentException $e) {}
316:
317: if (isset($e) || $component === NULL) {
318: throw new BadSignalException("The signal receiver component '$this->signalReceiver' is not found.", NULL, isset($e) ? $e : NULL);
319:
320: } elseif (!$component instanceof ISignalReceiver) {
321: throw new BadSignalException("The signal receiver component '$this->signalReceiver' is not ISignalReceiver implementor.");
322: }
323:
324: $component->signalReceived($this->signal);
325: $this->signal = NULL;
326: }
327:
328:
329: 330: 331: 332:
333: public function getSignal()
334: {
335: return $this->signal === NULL ? NULL : array($this->signalReceiver, $this->signal);
336: }
337:
338:
339: 340: 341: 342: 343: 344:
345: public function isSignalReceiver($component, $signal = NULL)
346: {
347: if ($component instanceof Nette\ComponentModel\Component) {
348: $component = $component === $this ? '' : $component->lookupPath(__CLASS__, TRUE);
349: }
350:
351: if ($this->signal === NULL) {
352: return FALSE;
353:
354: } elseif ($signal === TRUE) {
355: return $component === ''
356: || strncmp($this->signalReceiver . '-', $component . '-', strlen($component) + 1) === 0;
357:
358: } elseif ($signal === NULL) {
359: return $this->signalReceiver === $component;
360:
361: } else {
362: return $this->signalReceiver === $component && strcasecmp($signal, $this->signal) === 0;
363: }
364: }
365:
366:
367:
368:
369:
370: 371: 372: 373:
374: public function getAction($fullyQualified = FALSE)
375: {
376: return $fullyQualified ? ':' . $this->getName() . ':' . $this->action : $this->action;
377: }
378:
379:
380: 381: 382: 383: 384:
385: public function changeAction($action)
386: {
387: if (is_string($action) && Nette\Utils\Strings::match($action, '#^[a-zA-Z0-9][a-zA-Z0-9_\x7f-\xff]*\z#')) {
388: $this->action = $action;
389: $this->view = $action;
390:
391: } else {
392: $this->error('Action name is not alphanumeric string.');
393: }
394: }
395:
396:
397: 398: 399: 400:
401: public function getView()
402: {
403: return $this->view;
404: }
405:
406:
407: 408: 409: 410: 411:
412: public function setView($view)
413: {
414: $this->view = (string) $view;
415: return $this;
416: }
417:
418:
419: 420: 421: 422:
423: public function getLayout()
424: {
425: return $this->layout;
426: }
427:
428:
429: 430: 431: 432: 433:
434: public function setLayout($layout)
435: {
436: $this->layout = $layout === FALSE ? FALSE : (string) $layout;
437: return $this;
438: }
439:
440:
441: 442: 443: 444: 445:
446: public function sendTemplate()
447: {
448: $template = $this->getTemplate();
449: if (!$template) {
450: return;
451: }
452:
453: if (!$template->getFile()) {
454: $files = $this->formatTemplateFiles();
455: foreach ($files as $file) {
456: if (is_file($file)) {
457: $template->setFile($file);
458: break;
459: }
460: }
461:
462: if (!$template->getFile()) {
463: $file = preg_replace('#^.*([/\\\\].{1,70})\z#U', "\xE2\x80\xA6\$1", reset($files));
464: $file = strtr($file, '/', DIRECTORY_SEPARATOR);
465: $this->error("Page not found. Missing template '$file'.");
466: }
467: }
468:
469: $this->sendResponse(new Responses\TextResponse($template));
470: }
471:
472:
473: 474: 475: 476: 477:
478: public function findLayoutTemplateFile()
479: {
480: if ($this->layout === FALSE) {
481: return;
482: }
483: $files = $this->formatLayoutTemplateFiles();
484: foreach ($files as $file) {
485: if (is_file($file)) {
486: return $file;
487: }
488: }
489:
490: if ($this->layout) {
491: $file = preg_replace('#^.*([/\\\\].{1,70})\z#U', "\xE2\x80\xA6\$1", reset($files));
492: $file = strtr($file, '/', DIRECTORY_SEPARATOR);
493: throw new Nette\FileNotFoundException("Layout not found. Missing template '$file'.");
494: }
495: }
496:
497:
498: 499: 500: 501:
502: public function formatLayoutTemplateFiles()
503: {
504: $name = $this->getName();
505: $presenter = substr($name, strrpos(':' . $name, ':'));
506: $layout = $this->layout ? $this->layout : 'layout';
507: $dir = dirname($this->getReflection()->getFileName());
508: $dir = is_dir("$dir/templates") ? $dir : dirname($dir);
509: $list = array(
510: "$dir/templates/$presenter/@$layout.latte",
511: "$dir/templates/$presenter.@$layout.latte",
512: "$dir/templates/$presenter/@$layout.phtml",
513: "$dir/templates/$presenter.@$layout.phtml",
514: );
515: do {
516: $list[] = "$dir/templates/@$layout.latte";
517: $list[] = "$dir/templates/@$layout.phtml";
518: $dir = dirname($dir);
519: } while ($dir && ($name = substr($name, 0, strrpos($name, ':'))));
520: return $list;
521: }
522:
523:
524: 525: 526: 527:
528: public function formatTemplateFiles()
529: {
530: $name = $this->getName();
531: $presenter = substr($name, strrpos(':' . $name, ':'));
532: $dir = dirname($this->getReflection()->getFileName());
533: $dir = is_dir("$dir/templates") ? $dir : dirname($dir);
534: return array(
535: "$dir/templates/$presenter/$this->view.latte",
536: "$dir/templates/$presenter.$this->view.latte",
537: "$dir/templates/$presenter/$this->view.phtml",
538: "$dir/templates/$presenter.$this->view.phtml",
539: );
540: }
541:
542:
543: 544: 545: 546: 547:
548: public static function formatActionMethod($action)
549: {
550: return 'action' . $action;
551: }
552:
553:
554: 555: 556: 557: 558:
559: public static function formatRenderMethod($view)
560: {
561: return 'render' . $view;
562: }
563:
564:
565: 566: 567:
568: protected function createTemplate()
569: {
570: return $this->getTemplateFactory()->createTemplate($this);
571: }
572:
573:
574:
575:
576:
577: 578: 579:
580: public function getPayload()
581: {
582: return $this->payload;
583: }
584:
585:
586: 587: 588: 589:
590: public function isAjax()
591: {
592: if ($this->ajaxMode === NULL) {
593: $this->ajaxMode = $this->httpRequest->isAjax();
594: }
595: return $this->ajaxMode;
596: }
597:
598:
599: 600: 601: 602: 603:
604: public function sendPayload()
605: {
606: $this->sendResponse(new Responses\JsonResponse($this->payload));
607: }
608:
609:
610: 611: 612: 613: 614: 615:
616: public function sendJson($data)
617: {
618: $this->sendResponse(new Responses\JsonResponse($data));
619: }
620:
621:
622:
623:
624:
625: 626: 627: 628: 629:
630: public function sendResponse(Application\IResponse $response)
631: {
632: $this->response = $response;
633: $this->terminate();
634: }
635:
636:
637: 638: 639: 640: 641:
642: public function terminate()
643: {
644: if (func_num_args() !== 0) {
645: trigger_error(__METHOD__ . ' is not intended to send a Application\Response; use sendResponse() instead.', E_USER_WARNING);
646: $this->sendResponse(func_get_arg(0));
647: }
648: throw new Application\AbortException();
649: }
650:
651:
652: 653: 654: 655: 656: 657: 658:
659: public function forward($destination, $args = array())
660: {
661: if ($destination instanceof Application\Request) {
662: $this->sendResponse(new Responses\ForwardResponse($destination));
663: }
664:
665: $this->createRequest($this, $destination, is_array($args) ? $args : array_slice(func_get_args(), 1), 'forward');
666: $this->sendResponse(new Responses\ForwardResponse($this->lastCreatedRequest));
667: }
668:
669:
670: 671: 672: 673: 674: 675: 676:
677: public function redirectUrl($url, $code = NULL)
678: {
679: if ($this->isAjax()) {
680: $this->payload->redirect = (string) $url;
681: $this->sendPayload();
682:
683: } elseif (!$code) {
684: $code = $this->httpRequest->isMethod('post')
685: ? Http\IResponse::S303_POST_GET
686: : Http\IResponse::S302_FOUND;
687: }
688: $this->sendResponse(new Responses\RedirectResponse($url, $code));
689: }
690:
691:
692: 693: 694: 695: 696: 697: 698:
699: public function error($message = NULL, $code = Http\IResponse::S404_NOT_FOUND)
700: {
701: throw new Application\BadRequestException($message, $code);
702: }
703:
704:
705: 706: 707: 708: 709:
710: public function backlink()
711: {
712: return $this->getAction(TRUE);
713: }
714:
715:
716: 717: 718: 719: 720:
721: public function getLastCreatedRequest()
722: {
723: return $this->lastCreatedRequest;
724: }
725:
726:
727: 728: 729: 730: 731: 732:
733: public function getLastCreatedRequestFlag($flag)
734: {
735: return !empty($this->lastCreatedRequestFlag[$flag]);
736: }
737:
738:
739: 740: 741: 742: 743:
744: public function canonicalize()
745: {
746: if (!$this->isAjax() && ($this->request->isMethod('get') || $this->request->isMethod('head'))) {
747: try {
748: $url = $this->createRequest($this, $this->action, $this->getGlobalState() + $this->request->getParameters(), 'redirectX');
749: } catch (InvalidLinkException $e) {}
750: if (isset($url) && !$this->httpRequest->getUrl()->isEqual($url)) {
751: $this->sendResponse(new Responses\RedirectResponse($url, Http\IResponse::S301_MOVED_PERMANENTLY));
752: }
753: }
754: }
755:
756:
757: 758: 759: 760: 761: 762: 763: 764:
765: public function lastModified($lastModified, $etag = NULL, $expire = NULL)
766: {
767: if ($expire !== NULL) {
768: $this->httpResponse->setExpiration($expire);
769: }
770: $helper = new Nette\Http\Context($this->httpRequest, $this->httpResponse);
771: if (!$helper->isModified($lastModified, $etag)) {
772: $this->terminate();
773: }
774: }
775:
776:
777: 778: 779: 780: 781: 782: 783: 784: 785: 786:
787: protected function createRequest($component, $destination, array $args, $mode)
788: {
789:
790:
791: $this->lastCreatedRequest = $this->lastCreatedRequestFlag = NULL;
792:
793:
794:
795: $a = strpos($destination, '#');
796: if ($a === FALSE) {
797: $fragment = '';
798: } else {
799: $fragment = substr($destination, $a);
800: $destination = substr($destination, 0, $a);
801: }
802:
803:
804: $a = strpos($destination, '?');
805: if ($a !== FALSE) {
806: parse_str(substr($destination, $a + 1), $args);
807: $destination = substr($destination, 0, $a);
808: }
809:
810:
811: $a = strpos($destination, '//');
812: if ($a === FALSE) {
813: $scheme = FALSE;
814: } else {
815: $scheme = substr($destination, 0, $a);
816: $destination = substr($destination, $a + 2);
817: }
818:
819:
820: if (!$component instanceof Presenter || substr($destination, -1) === '!') {
821: $signal = rtrim($destination, '!');
822: $a = strrpos($signal, ':');
823: if ($a !== FALSE) {
824: $component = $component->getComponent(strtr(substr($signal, 0, $a), ':', '-'));
825: $signal = (string) substr($signal, $a + 1);
826: }
827: if ($signal == NULL) {
828: throw new InvalidLinkException("Signal must be non-empty string.");
829: }
830: $destination = 'this';
831: }
832:
833: if ($destination == NULL) {
834: throw new InvalidLinkException("Destination must be non-empty string.");
835: }
836:
837:
838: $current = FALSE;
839: $a = strrpos($destination, ':');
840: if ($a === FALSE) {
841: $action = $destination === 'this' ? $this->action : $destination;
842: $presenter = $this->getName();
843: $presenterClass = get_class($this);
844:
845: } else {
846: $action = (string) substr($destination, $a + 1);
847: if ($destination[0] === ':') {
848: if ($a < 2) {
849: throw new InvalidLinkException("Missing presenter name in '$destination'.");
850: }
851: $presenter = substr($destination, 1, $a - 1);
852:
853: } else {
854: $presenter = $this->getName();
855: $b = strrpos($presenter, ':');
856: if ($b === FALSE) {
857: $presenter = substr($destination, 0, $a);
858: } else {
859: $presenter = substr($presenter, 0, $b + 1) . substr($destination, 0, $a);
860: }
861: }
862: if (!$this->presenterFactory) {
863: throw new Nette\InvalidStateException('Unable to create link to other presenter, service PresenterFactory has not been set.');
864: }
865: try {
866: $presenterClass = $this->presenterFactory->getPresenterClass($presenter);
867: } catch (Application\InvalidPresenterException $e) {
868: throw new InvalidLinkException($e->getMessage(), NULL, $e);
869: }
870: }
871:
872:
873: if (isset($signal)) {
874: $reflection = new PresenterComponentReflection(get_class($component));
875: if ($signal === 'this') {
876: $signal = '';
877: if (array_key_exists(0, $args)) {
878: throw new InvalidLinkException("Unable to pass parameters to 'this!' signal.");
879: }
880:
881: } elseif (strpos($signal, self::NAME_SEPARATOR) === FALSE) {
882:
883: $method = $component->formatSignalMethod($signal);
884: if (!$reflection->hasCallableMethod($method)) {
885: throw new InvalidLinkException("Unknown signal '$signal', missing handler {$reflection->name}::$method()");
886: }
887: if ($args) {
888: self::argsToParams(get_class($component), $method, $args);
889: }
890: }
891:
892:
893: if ($args && array_intersect_key($args, $reflection->getPersistentParams())) {
894: $component->saveState($args);
895: }
896:
897: if ($args && $component !== $this) {
898: $prefix = $component->getUniqueId() . self::NAME_SEPARATOR;
899: foreach ($args as $key => $val) {
900: unset($args[$key]);
901: $args[$prefix . $key] = $val;
902: }
903: }
904: }
905:
906:
907: if (is_subclass_of($presenterClass, __CLASS__)) {
908: if ($action === '') {
909: $action = self::DEFAULT_ACTION;
910: }
911:
912: $current = ($action === '*' || strcasecmp($action, $this->action) === 0) && $presenterClass === get_class($this);
913:
914: $reflection = new PresenterComponentReflection($presenterClass);
915: if ($args || $destination === 'this') {
916:
917: $method = $presenterClass::formatActionMethod($action);
918: if (!$reflection->hasCallableMethod($method)) {
919: $method = $presenterClass::formatRenderMethod($action);
920: if (!$reflection->hasCallableMethod($method)) {
921: $method = NULL;
922: }
923: }
924:
925:
926: if ($method === NULL) {
927: if (array_key_exists(0, $args)) {
928: throw new InvalidLinkException("Unable to pass parameters to action '$presenter:$action', missing corresponding method.");
929: }
930:
931: } elseif ($destination === 'this') {
932: self::argsToParams($presenterClass, $method, $args, $this->params);
933:
934: } else {
935: self::argsToParams($presenterClass, $method, $args);
936: }
937: }
938:
939:
940: if ($args && array_intersect_key($args, $reflection->getPersistentParams())) {
941: $this->saveState($args, $reflection);
942: }
943:
944: if ($mode === 'redirect') {
945: $this->saveGlobalState();
946: }
947:
948: $globalState = $this->getGlobalState($destination === 'this' ? NULL : $presenterClass);
949: if ($current && $args) {
950: $tmp = $globalState + $this->params;
951: foreach ($args as $key => $val) {
952: if (http_build_query(array($val)) !== (isset($tmp[$key]) ? http_build_query(array($tmp[$key])) : '')) {
953: $current = FALSE;
954: break;
955: }
956: }
957: }
958: $args += $globalState;
959: }
960:
961:
962: if ($action) {
963: $args[self::ACTION_KEY] = $action;
964: }
965: if (!empty($signal)) {
966: $args[self::SIGNAL_KEY] = $component->getParameterId($signal);
967: $current = $current && $args[self::SIGNAL_KEY] === $this->getParameter(self::SIGNAL_KEY);
968: }
969: if (($mode === 'redirect' || $mode === 'forward') && $this->hasFlashSession()) {
970: $args[self::FLASH_KEY] = $this->getParameter(self::FLASH_KEY);
971: }
972:
973: $this->lastCreatedRequest = new Application\Request(
974: $presenter,
975: Application\Request::FORWARD,
976: $args,
977: array(),
978: array()
979: );
980: $this->lastCreatedRequestFlag = array('current' => $current);
981:
982: if ($mode === 'forward' || $mode === 'test') {
983: return;
984: }
985:
986:
987: static $refUrl;
988: if ($refUrl === NULL) {
989: $refUrl = new Http\Url($this->httpRequest->getUrl());
990: $refUrl->setPath($this->httpRequest->getUrl()->getScriptPath());
991: }
992: if (!$this->router) {
993: throw new Nette\InvalidStateException('Unable to generate URL, service Router has not been set.');
994: }
995: $url = $this->router->constructUrl($this->lastCreatedRequest, $refUrl);
996: if ($url === NULL) {
997: unset($args[self::ACTION_KEY]);
998: $params = urldecode(http_build_query($args, NULL, ', '));
999: throw new InvalidLinkException("No route for $presenter:$action($params)");
1000: }
1001:
1002:
1003: if ($mode === 'link' && $scheme === FALSE && !$this->absoluteUrls) {
1004: $hostUrl = $refUrl->getHostUrl() . '/';
1005: if (strncmp($url, $hostUrl, strlen($hostUrl)) === 0) {
1006: $url = substr($url, strlen($hostUrl) - 1);
1007: }
1008: }
1009:
1010: return $url . $fragment;
1011: }
1012:
1013:
1014: 1015: 1016: 1017: 1018: 1019: 1020: 1021: 1022:
1023: private static function argsToParams($class, $method, & $args, $supplemental = array())
1024: {
1025: $i = 0;
1026: $rm = new \ReflectionMethod($class, $method);
1027: foreach ($rm->getParameters() as $param) {
1028: $name = $param->getName();
1029: if (array_key_exists($i, $args)) {
1030: $args[$name] = $args[$i];
1031: unset($args[$i]);
1032: $i++;
1033:
1034: } elseif (array_key_exists($name, $args)) {
1035:
1036:
1037: } elseif (array_key_exists($name, $supplemental)) {
1038: $args[$name] = $supplemental[$name];
1039:
1040: } else {
1041: continue;
1042: }
1043:
1044: if ($args[$name] === NULL) {
1045: continue;
1046: }
1047:
1048: $def = $param->isDefaultValueAvailable() && $param->isOptional() ? $param->getDefaultValue() : NULL;
1049: $type = $param->isArray() ? 'array' : gettype($def);
1050: if (!PresenterComponentReflection::convertType($args[$name], $type)) {
1051: throw new InvalidLinkException("Invalid value for parameter '$name' in method $class::$method(), expected " . ($type === 'NULL' ? 'scalar' : $type) . ".");
1052: }
1053:
1054: if ($args[$name] === $def || ($def === NULL && is_scalar($args[$name]) && (string) $args[$name] === '')) {
1055: $args[$name] = NULL;
1056: }
1057: }
1058:
1059: if (array_key_exists($i, $args)) {
1060: $method = $rm->getName();
1061: throw new InvalidLinkException("Passed more parameters than method $class::$method() expects.");
1062: }
1063: }
1064:
1065:
1066: 1067: 1068: 1069: 1070:
1071: protected function handleInvalidLink(InvalidLinkException $e)
1072: {
1073: if ($this->invalidLinkMode === self::INVALID_LINK_SILENT) {
1074: return '#';
1075:
1076: } elseif ($this->invalidLinkMode === self::INVALID_LINK_WARNING) {
1077: return '#error: ' . $e->getMessage();
1078:
1079: } else {
1080: throw $e;
1081: }
1082: }
1083:
1084:
1085:
1086:
1087:
1088: 1089: 1090: 1091: 1092:
1093: public function storeRequest($expiration = '+ 10 minutes')
1094: {
1095: $session = $this->getSession('Nette.Application/requests');
1096: do {
1097: $key = Nette\Utils\Random::generate(5);
1098: } while (isset($session[$key]));
1099:
1100: $session[$key] = array($this->getUser()->getId(), $this->request);
1101: $session->setExpiration($expiration, $key);
1102: return $key;
1103: }
1104:
1105:
1106: 1107: 1108: 1109: 1110:
1111: public function restoreRequest($key)
1112: {
1113: $session = $this->getSession('Nette.Application/requests');
1114: if (!isset($session[$key]) || ($session[$key][0] !== NULL && $session[$key][0] !== $this->getUser()->getId())) {
1115: return;
1116: }
1117: $request = clone $session[$key][1];
1118: unset($session[$key]);
1119: $request->setFlag(Application\Request::RESTORED, TRUE);
1120: $params = $request->getParameters();
1121: $params[self::FLASH_KEY] = $this->getParameter(self::FLASH_KEY);
1122: $request->setParameters($params);
1123: $this->sendResponse(new Responses\ForwardResponse($request));
1124: }
1125:
1126:
1127:
1128:
1129:
1130: 1131: 1132: 1133: 1134:
1135: public static function getPersistentComponents()
1136: {
1137: return (array) Reflection\ClassType::from(get_called_class())->getAnnotation('persistent');
1138: }
1139:
1140:
1141: 1142: 1143: 1144:
1145: protected function getGlobalState($forClass = NULL)
1146: {
1147: $sinces = & $this->globalStateSinces;
1148:
1149: if ($this->globalState === NULL) {
1150: $state = array();
1151: foreach ($this->globalParams as $id => $params) {
1152: $prefix = $id . self::NAME_SEPARATOR;
1153: foreach ($params as $key => $val) {
1154: $state[$prefix . $key] = $val;
1155: }
1156: }
1157: $this->saveState($state, $forClass ? new PresenterComponentReflection($forClass) : NULL);
1158:
1159: if ($sinces === NULL) {
1160: $sinces = array();
1161: foreach ($this->getReflection()->getPersistentParams() as $name => $meta) {
1162: $sinces[$name] = $meta['since'];
1163: }
1164: }
1165:
1166: $components = $this->getReflection()->getPersistentComponents();
1167: $iterator = $this->getComponents(TRUE, 'Nette\Application\UI\IStatePersistent');
1168:
1169: foreach ($iterator as $name => $component) {
1170: if ($iterator->getDepth() === 0) {
1171:
1172: $since = isset($components[$name]['since']) ? $components[$name]['since'] : FALSE;
1173: }
1174: $prefix = $component->getUniqueId() . self::NAME_SEPARATOR;
1175: $params = array();
1176: $component->saveState($params);
1177: foreach ($params as $key => $val) {
1178: $state[$prefix . $key] = $val;
1179: $sinces[$prefix . $key] = $since;
1180: }
1181: }
1182:
1183: } else {
1184: $state = $this->globalState;
1185: }
1186:
1187: if ($forClass !== NULL) {
1188: $since = NULL;
1189: foreach ($state as $key => $foo) {
1190: if (!isset($sinces[$key])) {
1191: $x = strpos($key, self::NAME_SEPARATOR);
1192: $x = $x === FALSE ? $key : substr($key, 0, $x);
1193: $sinces[$key] = isset($sinces[$x]) ? $sinces[$x] : FALSE;
1194: }
1195: if ($since !== $sinces[$key]) {
1196: $since = $sinces[$key];
1197: $ok = $since && (is_subclass_of($forClass, $since) || $forClass === $since);
1198: }
1199: if (!$ok) {
1200: unset($state[$key]);
1201: }
1202: }
1203: }
1204:
1205: return $state;
1206: }
1207:
1208:
1209: 1210: 1211: 1212:
1213: protected function saveGlobalState()
1214: {
1215: $this->globalParams = array();
1216: $this->globalState = $this->getGlobalState();
1217: }
1218:
1219:
1220: 1221: 1222: 1223: 1224:
1225: private function initGlobalParameters()
1226: {
1227:
1228: $this->globalParams = array();
1229: $selfParams = array();
1230:
1231: $params = $this->request->getParameters();
1232: if ($this->isAjax()) {
1233: $params += $this->request->getPost();
1234: } elseif (isset($this->request->post[self::SIGNAL_KEY])) {
1235: $params[self::SIGNAL_KEY] = $this->request->post[self::SIGNAL_KEY];
1236: }
1237:
1238: foreach ($params as $key => $value) {
1239: if (!preg_match('#^((?:[a-z0-9_]+-)*)((?!\d+\z)[a-z0-9_]+)\z#i', $key, $matches)) {
1240: continue;
1241: } elseif (!$matches[1]) {
1242: $selfParams[$key] = $value;
1243: } else {
1244: $this->globalParams[substr($matches[1], 0, -1)][$matches[2]] = $value;
1245: }
1246: }
1247:
1248:
1249: $this->changeAction(isset($selfParams[self::ACTION_KEY]) ? $selfParams[self::ACTION_KEY] : self::DEFAULT_ACTION);
1250:
1251:
1252: $this->signalReceiver = $this->getUniqueId();
1253: if (isset($selfParams[self::SIGNAL_KEY])) {
1254: $param = $selfParams[self::SIGNAL_KEY];
1255: if (!is_string($param)) {
1256: $this->error('Signal name is not string.');
1257: }
1258: $pos = strrpos($param, '-');
1259: if ($pos) {
1260: $this->signalReceiver = substr($param, 0, $pos);
1261: $this->signal = substr($param, $pos + 1);
1262: } else {
1263: $this->signalReceiver = $this->getUniqueId();
1264: $this->signal = $param;
1265: }
1266: if ($this->signal == NULL) {
1267: $this->signal = NULL;
1268: }
1269: }
1270:
1271: $this->loadState($selfParams);
1272: }
1273:
1274:
1275: 1276: 1277: 1278: 1279: 1280:
1281: public function popGlobalParameters($id)
1282: {
1283: if (isset($this->globalParams[$id])) {
1284: $res = $this->globalParams[$id];
1285: unset($this->globalParams[$id]);
1286: return $res;
1287:
1288: } else {
1289: return array();
1290: }
1291: }
1292:
1293:
1294:
1295:
1296:
1297: 1298: 1299: 1300:
1301: public function hasFlashSession()
1302: {
1303: return !empty($this->params[self::FLASH_KEY])
1304: && $this->getSession()->hasSection('Nette.Application.Flash/' . $this->params[self::FLASH_KEY]);
1305: }
1306:
1307:
1308: 1309: 1310: 1311:
1312: public function getFlashSession()
1313: {
1314: if (empty($this->params[self::FLASH_KEY])) {
1315: $this->params[self::FLASH_KEY] = Nette\Utils\Random::generate(4);
1316: }
1317: return $this->getSession('Nette.Application.Flash/' . $this->params[self::FLASH_KEY]);
1318: }
1319:
1320:
1321:
1322:
1323:
1324: public function injectPrimary(Nette\DI\Container $context = NULL, Nette\Application\IPresenterFactory $presenterFactory = NULL, Nette\Application\IRouter $router = NULL,
1325: Http\IRequest $httpRequest, Http\IResponse $httpResponse, Http\Session $session = NULL, Nette\Security\User $user = NULL, ITemplateFactory $templateFactory = NULL)
1326: {
1327: if ($this->presenterFactory !== NULL) {
1328: throw new Nette\InvalidStateException("Method " . __METHOD__ . " is intended for initialization and should not be called more than once.");
1329: }
1330:
1331: $this->context = $context;
1332: $this->presenterFactory = $presenterFactory;
1333: $this->router = $router;
1334: $this->httpRequest = $httpRequest;
1335: $this->httpResponse = $httpResponse;
1336: $this->session = $session;
1337: $this->user = $user;
1338: $this->templateFactory = $templateFactory;
1339: }
1340:
1341:
1342: 1343: 1344: 1345: 1346:
1347: public function getContext()
1348: {
1349: if (!$this->context) {
1350: throw new Nette\InvalidStateException('Context has not been set.');
1351: }
1352: return $this->context;
1353: }
1354:
1355:
1356: 1357: 1358:
1359: final public function getService($name)
1360: {
1361: trigger_error(__METHOD__ . '() is deprecated; use dependency injection instead.', E_USER_DEPRECATED);
1362: return $this->context->getService($name);
1363: }
1364:
1365:
1366: 1367: 1368:
1369: protected function getHttpRequest()
1370: {
1371: return $this->httpRequest;
1372: }
1373:
1374:
1375: 1376: 1377:
1378: protected function getHttpResponse()
1379: {
1380: return $this->httpResponse;
1381: }
1382:
1383:
1384: 1385: 1386: 1387:
1388: public function getSession($namespace = NULL)
1389: {
1390: if (!$this->session) {
1391: throw new Nette\InvalidStateException('Service Session has not been set.');
1392: }
1393: return $namespace === NULL ? $this->session : $this->session->getSection($namespace);
1394: }
1395:
1396:
1397: 1398: 1399:
1400: public function getUser()
1401: {
1402: if (!$this->user) {
1403: throw new Nette\InvalidStateException('Service User has not been set.');
1404: }
1405: return $this->user;
1406: }
1407:
1408:
1409: 1410: 1411:
1412: public function getTemplateFactory()
1413: {
1414: if (!$this->templateFactory) {
1415: throw new Nette\InvalidStateException('Service TemplateFactory has not been set.');
1416: }
1417: return $this->templateFactory;
1418: }
1419:
1420: }
1421: