Packages

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Config
      • Adapters
      • Extensions
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Diagnostics
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
      • PhpGenerator
  • NetteModule
  • None
  • PHP

Classes

  • AppForm
  • Control
  • Multiplier
  • Presenter
  • PresenterComponent

Interfaces

  • IRenderable
  • ISignalReceiver
  • IStatePersistent

Exceptions

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