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

  • NAppForm
  • NControl
  • NMultiplier
  • NPresenter
  • NPresenterComponent

Interfaces

  • IRenderable
  • ISignalReceiver
  • IStatePersistent

Exceptions

  • NBadSignalException
  • NInvalidLinkException
  • Overview
  • Package
  • Class
  • Tree
   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 NPresenterRequest $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 NPresenterRequest $lastCreatedRequest
  28:  * @property-read NSessionSection $flashSession
  29:  * @property-read SystemContainer|IDIContainer $context
  30:  * @property-read NApplication $application
  31:  * @property-read NSession $session
  32:  * @property-read NUser $user
  33:  * @package Nette\Application\UI
  34:  */
  35: abstract class NPresenter extends NControl implements IPresenter
  36: {
  37:     /** bad link handling {@link NPresenter::$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 NPresenterRequest */
  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 NPresenterRequest */
 100:     private $lastCreatedRequest;
 101: 
 102:     /** @var array */
 103:     private $lastCreatedRequestFlag;
 104: 
 105:     /** @var IDIContainer */
 106:     private $context;
 107: 
 108: 
 109: 
 110:     public function __construct(IDIContainer $context)
 111:     {
 112:         $this->context = $context;
 113:         if ($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 NPresenterRequest
 122:      */
 123:     final public function getRequest()
 124:     {
 125:         return $this->request;
 126:     }
 127: 
 128: 
 129: 
 130:     /**
 131:      * Returns self.
 132:      * @return NPresenter
 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:      * @param  NPresenterRequest
 158:      * @return IPresenterResponse
 159:      */
 160:     public function run(NPresenterRequest $request)
 161:     {
 162:         try {
 163:             // STARTUP
 164:             $this->request = $request;
 165:             $this->payload = (object) NULL;
 166:             $this->setParent($this->getParent(), $request->getPresenterName());
 167: 
 168:             $this->initGlobalParameters();
 169:             $this->checkRequirements($this->getReflection());
 170:             $this->startup();
 171:             if (!$this->startupCheck) {
 172:                 $class = $this->getReflection()->getMethod('startup')->getDeclaringClass()->getName();
 173:                 throw new InvalidStateException("Method $class::startup() or its descendant doesn't call parent::startup().");
 174:             }
 175:             // calls $this->action<Action>()
 176:             $this->tryCall($this->formatActionMethod($this->getAction()), $this->params);
 177: 
 178:             if ($this->autoCanonicalize) {
 179:                 $this->canonicalize();
 180:             }
 181:             if ($this->getHttpRequest()->isMethod('head')) {
 182:                 $this->terminate();
 183:             }
 184: 
 185:             // SIGNAL HANDLING
 186:             // calls $this->handle<Signal>()
 187:             $this->processSignal();
 188: 
 189:             // RENDERING VIEW
 190:             $this->beforeRender();
 191:             // calls $this->render<View>()
 192:             $this->tryCall($this->formatRenderMethod($this->getView()), $this->params);
 193:             $this->afterRender();
 194: 
 195:             // save component tree persistent state
 196:             $this->saveGlobalState();
 197:             if ($this->isAjax()) {
 198:                 $this->payload->state = $this->getGlobalState();
 199:             }
 200: 
 201:             // finish template rendering
 202:             $this->sendTemplate();
 203: 
 204:         } catch (NAbortException $e) {
 205:             // continue with shutting down
 206:             if ($this->isAjax()) try {
 207:                 $hasPayload = (array) $this->payload; unset($hasPayload['state']);
 208:                 if ($this->response instanceof NTextResponse && $this->isControlInvalid()) { // snippets - TODO
 209:                     $this->snippetMode = TRUE;
 210:                     $this->response->send($this->getHttpRequest(), $this->getHttpResponse());
 211:                     $this->sendPayload();
 212: 
 213:                 } elseif (!$this->response && $hasPayload) { // back compatibility for use terminate() instead of sendPayload()
 214:                     $this->sendPayload();
 215:                 }
 216:             } catch (NAbortException $e) { }
 217: 
 218:             if ($this->hasFlashSession()) {
 219:                 $this->getFlashSession()->setExpiration($this->response instanceof NRedirectResponse ? '+ 30 seconds': '+ 3 seconds');
 220:             }
 221: 
 222:             // SHUTDOWN
 223:             $this->onShutdown($this, $this->response);
 224:             $this->shutdown($this->response);
 225: 
 226:             return $this->response;
 227:         }
 228:     }
 229: 
 230: 
 231: 
 232:     /**
 233:      * @return void
 234:      */
 235:     protected function startup()
 236:     {
 237:         $this->startupCheck = TRUE;
 238:     }
 239: 
 240: 
 241: 
 242:     /**
 243:      * Common render method.
 244:      * @return void
 245:      */
 246:     protected function beforeRender()
 247:     {
 248:     }
 249: 
 250: 
 251: 
 252:     /**
 253:      * Common render method.
 254:      * @return void
 255:      */
 256:     protected function afterRender()
 257:     {
 258:     }
 259: 
 260: 
 261: 
 262:     /**
 263:      * @param  IPresenterResponse  optional catched exception
 264:      * @return void
 265:      */
 266:     protected function shutdown($response)
 267:     {
 268:     }
 269: 
 270: 
 271: 
 272:     /**
 273:      * Checks authorization.
 274:      * @return void
 275:      */
 276:     public function checkRequirements($element)
 277:     {
 278:         $user = (array) $element->getAnnotation('User');
 279:         if (in_array('loggedIn', $user) && !$this->getUser()->isLoggedIn()) {
 280:             throw new NForbiddenRequestException;
 281:         }
 282:     }
 283: 
 284: 
 285: 
 286:     /********************* signal handling ****************d*g**/
 287: 
 288: 
 289: 
 290:     /**
 291:      * @return void
 292:      * @throws NBadSignalException
 293:      */
 294:     public function processSignal()
 295:     {
 296:         if ($this->signal === NULL) {
 297:             return;
 298:         }
 299: 
 300:         try {
 301:             $component = $this->signalReceiver === '' ? $this : $this->getComponent($this->signalReceiver, FALSE);
 302:         } catch (InvalidArgumentException $e) {}
 303: 
 304:         if (isset($e) || $component === NULL) {
 305:             throw new NBadSignalException("The signal receiver component '$this->signalReceiver' is not found.");
 306: 
 307:         } elseif (!$component instanceof ISignalReceiver) {
 308:             throw new NBadSignalException("The signal receiver component '$this->signalReceiver' is not ISignalReceiver implementor.");
 309:         }
 310: 
 311:         $component->signalReceived($this->signal);
 312:         $this->signal = NULL;
 313:     }
 314: 
 315: 
 316: 
 317:     /**
 318:      * Returns pair signal receiver and name.
 319:      * @return array|NULL
 320:      */
 321:     final public function getSignal()
 322:     {
 323:         return $this->signal === NULL ? NULL : array($this->signalReceiver, $this->signal);
 324:     }
 325: 
 326: 
 327: 
 328:     /**
 329:      * Checks if the signal receiver is the given one.
 330:      * @param  mixed  component or its id
 331:      * @param  string signal name (optional)
 332:      * @return bool
 333:      */
 334:     final public function isSignalReceiver($component, $signal = NULL)
 335:     {
 336:         if ($component instanceof NComponent) {
 337:             $component = $component === $this ? '' : $component->lookupPath(__CLASS__, TRUE);
 338:         }
 339: 
 340:         if ($this->signal === NULL) {
 341:             return FALSE;
 342: 
 343:         } elseif ($signal === TRUE) {
 344:             return $component === ''
 345:                 || strncmp($this->signalReceiver . '-', $component . '-', strlen($component) + 1) === 0;
 346: 
 347:         } elseif ($signal === NULL) {
 348:             return $this->signalReceiver === $component;
 349: 
 350:         } else {
 351:             return $this->signalReceiver === $component && strcasecmp($signal, $this->signal) === 0;
 352:         }
 353:     }
 354: 
 355: 
 356: 
 357:     /********************* rendering ****************d*g**/
 358: 
 359: 
 360: 
 361:     /**
 362:      * Returns current action name.
 363:      * @return string
 364:      */
 365:     final public function getAction($fullyQualified = FALSE)
 366:     {
 367:         return $fullyQualified ? ':' . $this->getName() . ':' . $this->action : $this->action;
 368:     }
 369: 
 370: 
 371: 
 372:     /**
 373:      * Changes current action. Only alphanumeric characters are allowed.
 374:      * @param  string
 375:      * @return void
 376:      */
 377:     public function changeAction($action)
 378:     {
 379:         if (is_string($action) && NStrings::match($action, '#^[a-zA-Z0-9][a-zA-Z0-9_\x7f-\xff]*$#')) {
 380:             $this->action = $action;
 381:             $this->view = $action;
 382: 
 383:         } else {
 384:             $this->error('Action name is not alphanumeric string.');
 385:         }
 386:     }
 387: 
 388: 
 389: 
 390:     /**
 391:      * Returns current view.
 392:      * @return string
 393:      */
 394:     final public function getView()
 395:     {
 396:         return $this->view;
 397:     }
 398: 
 399: 
 400: 
 401:     /**
 402:      * Changes current view. Any name is allowed.
 403:      * @param  string
 404:      * @return NPresenter  provides a fluent interface
 405:      */
 406:     public function setView($view)
 407:     {
 408:         $this->view = (string) $view;
 409:         return $this;
 410:     }
 411: 
 412: 
 413: 
 414:     /**
 415:      * Returns current layout name.
 416:      * @return string|FALSE
 417:      */
 418:     final public function getLayout()
 419:     {
 420:         return $this->layout;
 421:     }
 422: 
 423: 
 424: 
 425:     /**
 426:      * Changes or disables layout.
 427:      * @param  string|FALSE
 428:      * @return NPresenter  provides a fluent interface
 429:      */
 430:     public function setLayout($layout)
 431:     {
 432:         $this->layout = $layout === FALSE ? FALSE : (string) $layout;
 433:         return $this;
 434:     }
 435: 
 436: 
 437: 
 438:     /**
 439:      * @return void
 440:      * @throws NBadRequestException if no template found
 441:      * @throws NAbortException
 442:      */
 443:     public function sendTemplate()
 444:     {
 445:         $template = $this->getTemplate();
 446:         if (!$template) {
 447:             return;
 448:         }
 449: 
 450:         if ($template instanceof IFileTemplate && !$template->getFile()) { // content template
 451:             $files = $this->formatTemplateFiles();
 452:             foreach ($files as $file) {
 453:                 if (is_file($file)) {
 454:                     $template->setFile($file);
 455:                     break;
 456:                 }
 457:             }
 458: 
 459:             if (!$template->getFile()) {
 460:                 $file = preg_replace('#^.*([/\\\\].{1,70})$#U', "\xE2\x80\xA6\$1", reset($files));
 461:                 $file = strtr($file, '/', DIRECTORY_SEPARATOR);
 462:                 $this->error("Page not found. Missing template '$file'.");
 463:             }
 464:         }
 465: 
 466:         $this->sendResponse(new NTextResponse($template));
 467:     }
 468: 
 469: 
 470: 
 471:     /**
 472:      * Finds layout template file name.
 473:      * @return string
 474:      */
 475:     public function findLayoutTemplateFile()
 476:     {
 477:         if ($this->layout === FALSE) {
 478:             return;
 479:         }
 480:         $files = $this->formatLayoutTemplateFiles();
 481:         foreach ($files as $file) {
 482:             if (is_file($file)) {
 483:                 return $file;
 484:             }
 485:         }
 486: 
 487:         if ($this->layout) {
 488:             $file = preg_replace('#^.*([/\\\\].{1,70})$#U', "\xE2\x80\xA6\$1", reset($files));
 489:             $file = strtr($file, '/', DIRECTORY_SEPARATOR);
 490:             throw new FileNotFoundException("Layout not found. Missing template '$file'.");
 491:         }
 492:     }
 493: 
 494: 
 495: 
 496:     /**
 497:      * Formats layout template file names.
 498:      * @return array
 499:      */
 500:     public function formatLayoutTemplateFiles()
 501:     {
 502:         $name = $this->getName();
 503:         $presenter = substr($name, strrpos(':' . $name, ':'));
 504:         $layout = $this->layout ? $this->layout : 'layout';
 505:         $dir = dirname(dirname($this->getReflection()->getFileName()));
 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(dirname($this->getReflection()->getFileName()));
 531:         return array(
 532:             "$dir/templates/$presenter/$this->view.latte",
 533:             "$dir/templates/$presenter.$this->view.latte",
 534:             "$dir/templates/$presenter/$this->view.phtml",
 535:             "$dir/templates/$presenter.$this->view.phtml",
 536:         );
 537:     }
 538: 
 539: 
 540: 
 541:     /**
 542:      * Formats action method name.
 543:      * @param  string
 544:      * @return string
 545:      */
 546:     protected static function formatActionMethod($action)
 547:     {
 548:         return 'action' . $action;
 549:     }
 550: 
 551: 
 552: 
 553:     /**
 554:      * Formats render view method name.
 555:      * @param  string
 556:      * @return string
 557:      */
 558:     protected static function formatRenderMethod($view)
 559:     {
 560:         return 'render' . $view;
 561:     }
 562: 
 563: 
 564: 
 565:     /********************* partial AJAX rendering ****************d*g**/
 566: 
 567: 
 568: 
 569:     /**
 570:      * @return stdClass
 571:      */
 572:     final public function getPayload()
 573:     {
 574:         return $this->payload;
 575:     }
 576: 
 577: 
 578: 
 579:     /**
 580:      * Is AJAX request?
 581:      * @return bool
 582:      */
 583:     public function isAjax()
 584:     {
 585:         if ($this->ajaxMode === NULL) {
 586:             $this->ajaxMode = $this->getHttpRequest()->isAjax();
 587:         }
 588:         return $this->ajaxMode;
 589:     }
 590: 
 591: 
 592: 
 593:     /**
 594:      * Sends AJAX payload to the output.
 595:      * @return void
 596:      * @throws NAbortException
 597:      */
 598:     public function sendPayload()
 599:     {
 600:         $this->sendResponse(new NJsonResponse($this->payload));
 601:     }
 602: 
 603: 
 604: 
 605:     /********************* navigation & flow ****************d*g**/
 606: 
 607: 
 608: 
 609:     /**
 610:      * Sends response and terminates presenter.
 611:      * @param  IPresenterResponse
 612:      * @return void
 613:      * @throws NAbortException
 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 NAbortException
 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 NAbortException();
 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 NAbortException
 645:      */
 646:     public function forward($destination, $args = array())
 647:     {
 648:         if ($destination instanceof NPresenterRequest) {
 649:             $this->sendResponse(new NForwardResponse($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 NForwardResponse($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 NAbortException
 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 NRedirectResponse($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 NBadRequestException
 698:      */
 699:     public function error($message = NULL, $code = IHttpResponse::S404_NOT_FOUND)
 700:     {
 701:         throw new NBadRequestException($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 NPresenterRequest
 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 NAbortException
 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 (NInvalidLinkException $e) {}
 751:             if (isset($url) && !$this->getHttpRequest()->getUrl()->isEqual($url)) {
 752:                 $this->sendResponse(new NRedirectResponse($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 NAbortException
 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  NPresenterComponent  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 NInvalidLinkException
 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 NUrl($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 NPresenter || 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 NInvalidLinkException("Signal must be non-empty string.");
 842:             }
 843:             $destination = 'this';
 844:         }
 845: 
 846:         if ($destination == NULL) {  // intentionally ==
 847:             throw new NInvalidLinkException("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 NInvalidLinkException("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 (NInvalidPresenterException $e) {
 878:                 throw new NInvalidLinkException($e->getMessage());
 879:             }
 880:         }
 881: 
 882:         // PROCESS SIGNAL ARGUMENTS
 883:         if (isset($signal)) { // $component must be IStatePersistent
 884:             $reflection = new NPresenterComponentReflection(get_class($component));
 885:             if ($signal === 'this') { // means "no signal"
 886:                 $signal = '';
 887:                 if (array_key_exists(0, $args)) {
 888:                     throw new NInvalidLinkException("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 NInvalidLinkException("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 NPresenterComponentReflection($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 NInvalidLinkException("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 ((string) $val !== (isset($tmp[$key]) ? (string) $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 NPresenterRequest(
 982:             $presenter,
 983:             NPresenterRequest::FORWARD,
 984:             $args,
 985:             array(),
 986:             array()
 987:         );
 988:         $this->lastCreatedRequestFlag = array('current' => $current);
 989: 
 990:         if ($mode === 'forward') {
 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 NInvalidLinkException("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 NInvalidLinkException
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: 
1046:             $def = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL;
1047:             $val = $args[$name];
1048:             if ($val === NULL) {
1049:                 continue;
1050:             } elseif ($param->isArray() || is_array($def)) {
1051:                 if (!is_array($val)) {
1052:                     throw new NInvalidLinkException("Invalid value for parameter '$name', expected array.");
1053:                 }
1054:             } elseif ($param->getClass() || is_object($val)) {
1055:                 // ignore
1056:             } elseif (!is_scalar($val)) {
1057:                 throw new NInvalidLinkException("Invalid value for parameter '$name', expected scalar.");
1058: 
1059:             } elseif ($def === NULL) {
1060:                 if ((string) $val === '') {
1061:                     $args[$name] = NULL; // value transmit is unnecessary
1062:                 }
1063:                 continue;
1064:             } else {
1065:                 settype($args[$name], gettype($def));
1066:                 if ((string) $args[$name] !== (string) $val) {
1067:                     throw new NInvalidLinkException("Invalid value for parameter '$name', expected ".gettype($def).".");
1068:                 }
1069:             }
1070: 
1071:             if ($args[$name] === $def) {
1072:                 $args[$name] = NULL; // value transmit is unnecessary
1073:             }
1074:         }
1075: 
1076:         if (array_key_exists($i, $args)) {
1077:             $method = $rm->getName();
1078:             throw new NInvalidLinkException("Passed more parameters than method $class::$method() expects.");
1079:         }
1080:     }
1081: 
1082: 
1083: 
1084:     /**
1085:      * Invalid link handler. Descendant can override this method to change default behaviour.
1086:      * @param  NInvalidLinkException
1087:      * @return string
1088:      * @throws NInvalidLinkException
1089:      */
1090:     protected function handleInvalidLink($e)
1091:     {
1092:         if ($this->invalidLinkMode === self::INVALID_LINK_SILENT) {
1093:             return '#';
1094: 
1095:         } elseif ($this->invalidLinkMode === self::INVALID_LINK_WARNING) {
1096:             return 'error: ' . $e->getMessage();
1097: 
1098:         } else { // self::INVALID_LINK_EXCEPTION
1099:             throw $e;
1100:         }
1101:     }
1102: 
1103: 
1104: 
1105:     /********************* request serialization ****************d*g**/
1106: 
1107: 
1108: 
1109:     /**
1110:      * Stores current request to session.
1111:      * @param  mixed  optional expiration time
1112:      * @return string key
1113:      */
1114:     public function storeRequest($expiration = '+ 10 minutes')
1115:     {
1116:         $session = $this->getSession('Nette.Application/requests');
1117:         do {
1118:             $key = NStrings::random(5);
1119:         } while (isset($session[$key]));
1120: 
1121:         $session[$key] = array($this->getUser()->getId(), $this->request);
1122:         $session->setExpiration($expiration, $key);
1123:         return $key;
1124:     }
1125: 
1126: 
1127: 
1128:     /**
1129:      * Restores current request to session.
1130:      * @param  string key
1131:      * @return void
1132:      */
1133:     public function restoreRequest($key)
1134:     {
1135:         $session = $this->getSession('Nette.Application/requests');
1136:         if (!isset($session[$key]) || ($session[$key][0] !== NULL && $session[$key][0] !== $this->getUser()->getId())) {
1137:             return;
1138:         }
1139:         $request = clone $session[$key][1];
1140:         unset($session[$key]);
1141:         $request->setFlag(NPresenterRequest::RESTORED, TRUE);
1142:         $params = $request->getParameters();
1143:         $params[self::FLASH_KEY] = $this->getParameter(self::FLASH_KEY);
1144:         $request->setParameters($params);
1145:         $this->sendResponse(new NForwardResponse($request));
1146:     }
1147: 
1148: 
1149: 
1150:     /********************* interface IStatePersistent ****************d*g**/
1151: 
1152: 
1153: 
1154:     /**
1155:      * Returns array of persistent components.
1156:      * This default implementation detects components by class-level annotation @persistent(cmp1, cmp2).
1157:      * @return array
1158:      */
1159:     public static function getPersistentComponents()
1160:     {
1161:         $arg = func_get_arg(0);
1162:         return (array) NClassReflection::from($arg)
1163:             ->getAnnotation('persistent');
1164:     }
1165: 
1166: 
1167: 
1168:     /**
1169:      * Saves state information for all subcomponents to $this->globalState.
1170:      * @return array
1171:      */
1172:     private function getGlobalState($forClass = NULL)
1173:     {
1174:         $sinces = & $this->globalStateSinces;
1175: 
1176:         if ($this->globalState === NULL) {
1177:             $state = array();
1178:             foreach ($this->globalParams as $id => $params) {
1179:                 $prefix = $id . self::NAME_SEPARATOR;
1180:                 foreach ($params as $key => $val) {
1181:                     $state[$prefix . $key] = $val;
1182:                 }
1183:             }
1184:             $this->saveState($state, $forClass ? new NPresenterComponentReflection($forClass) : NULL);
1185: 
1186:             if ($sinces === NULL) {
1187:                 $sinces = array();
1188:                 foreach ($this->getReflection()->getPersistentParams() as $nm => $meta) {
1189:                     $sinces[$nm] = $meta['since'];
1190:                 }
1191:             }
1192: 
1193:             $components = $this->getReflection()->getPersistentComponents();
1194:             $iterator = $this->getComponents(TRUE, 'IStatePersistent');
1195: 
1196:             foreach ($iterator as $name => $component) {
1197:                 if ($iterator->getDepth() === 0) {
1198:                     // counts with NRecursiveIteratorIterator::SELF_FIRST
1199:                     $since = isset($components[$name]['since']) ? $components[$name]['since'] : FALSE; // FALSE = nonpersistent
1200:                 }
1201:                 $prefix = $component->getUniqueId() . self::NAME_SEPARATOR;
1202:                 $params = array();
1203:                 $component->saveState($params);
1204:                 foreach ($params as $key => $val) {
1205:                     $state[$prefix . $key] = $val;
1206:                     $sinces[$prefix . $key] = $since;
1207:                 }
1208:             }
1209: 
1210:         } else {
1211:             $state = $this->globalState;
1212:         }
1213: 
1214:         if ($forClass !== NULL) {
1215:             $since = NULL;
1216:             foreach ($state as $key => $foo) {
1217:                 if (!isset($sinces[$key])) {
1218:                     $x = strpos($key, self::NAME_SEPARATOR);
1219:                     $x = $x === FALSE ? $key : substr($key, 0, $x);
1220:                     $sinces[$key] = isset($sinces[$x]) ? $sinces[$x] : FALSE;
1221:                 }
1222:                 if ($since !== $sinces[$key]) {
1223:                     $since = $sinces[$key];
1224:                     $ok = $since && (is_subclass_of($forClass, $since) || $forClass === $since);
1225:                 }
1226:                 if (!$ok) {
1227:                     unset($state[$key]);
1228:                 }
1229:             }
1230:         }
1231: 
1232:         return $state;
1233:     }
1234: 
1235: 
1236: 
1237:     /**
1238:      * Permanently saves state information for all subcomponents to $this->globalState.
1239:      * @return void
1240:      */
1241:     protected function saveGlobalState()
1242:     {
1243:         // load lazy components
1244:         foreach ($this->globalParams as $id => $foo) {
1245:             $this->getComponent($id, FALSE);
1246:         }
1247: 
1248:         $this->globalParams = array();
1249:         $this->globalState = $this->getGlobalState();
1250:     }
1251: 
1252: 
1253: 
1254:     /**
1255:      * Initializes $this->globalParams, $this->signal & $this->signalReceiver, $this->action, $this->view. Called by run().
1256:      * @return void
1257:      * @throws NBadRequestException if action name is not valid
1258:      */
1259:     private function initGlobalParameters()
1260:     {
1261:         // init $this->globalParams
1262:         $this->globalParams = array();
1263:         $selfParams = array();
1264: 
1265:         $params = $this->request->getParameters();
1266:         if ($this->isAjax()) {
1267:             $params += $this->request->getPost();
1268:         }
1269: 
1270:         foreach ($params as $key => $value) {
1271:             $a = strlen($key) > 2 ? strrpos($key, self::NAME_SEPARATOR, -2) : FALSE;
1272:             if (!$a) {
1273:                 $selfParams[$key] = $value;
1274:             } else {
1275:                 $this->globalParams[substr($key, 0, $a)][substr($key, $a + 1)] = $value;
1276:             }
1277:         }
1278: 
1279:         // init & validate $this->action & $this->view
1280:         $this->changeAction(isset($selfParams[self::ACTION_KEY]) ? $selfParams[self::ACTION_KEY] : self::DEFAULT_ACTION);
1281: 
1282:         // init $this->signalReceiver and key 'signal' in appropriate params array
1283:         $this->signalReceiver = $this->getUniqueId();
1284:         if (isset($selfParams[self::SIGNAL_KEY])) {
1285:             $param = $selfParams[self::SIGNAL_KEY];
1286:             if (!is_string($param)) {
1287:                 $this->error('Signal name is not string.');
1288:             }
1289:             $pos = strrpos($param, '-');
1290:             if ($pos) {
1291:                 $this->signalReceiver = substr($param, 0, $pos);
1292:                 $this->signal = substr($param, $pos + 1);
1293:             } else {
1294:                 $this->signalReceiver = $this->getUniqueId();
1295:                 $this->signal = $param;
1296:             }
1297:             if ($this->signal == NULL) { // intentionally ==
1298:                 $this->signal = NULL;
1299:             }
1300:         }
1301: 
1302:         $this->loadState($selfParams);
1303:     }
1304: 
1305: 
1306: 
1307:     /**
1308:      * Pops parameters for specified component.
1309:      * @param  string  component id
1310:      * @return array
1311:      */
1312:     final public function popGlobalParameters($id)
1313:     {
1314:         if (isset($this->globalParams[$id])) {
1315:             $res = $this->globalParams[$id];
1316:             unset($this->globalParams[$id]);
1317:             return $res;
1318: 
1319:         } else {
1320:             return array();
1321:         }
1322:     }
1323: 
1324: 
1325: 
1326:     /********************* flash session ****************d*g**/
1327: 
1328: 
1329: 
1330:     /**
1331:      * Checks if a flash session namespace exists.
1332:      * @return bool
1333:      */
1334:     public function hasFlashSession()
1335:     {
1336:         return !empty($this->params[self::FLASH_KEY])
1337:             && $this->getSession()->hasSection('Nette.Application.Flash/' . $this->params[self::FLASH_KEY]);
1338:     }
1339: 
1340: 
1341: 
1342:     /**
1343:      * Returns session namespace provided to pass temporary data between redirects.
1344:      * @return NSessionSection
1345:      */
1346:     public function getFlashSession()
1347:     {
1348:         if (empty($this->params[self::FLASH_KEY])) {
1349:             $this->params[self::FLASH_KEY] = NStrings::random(4);
1350:         }
1351:         return $this->getSession('Nette.Application.Flash/' . $this->params[self::FLASH_KEY]);
1352:     }
1353: 
1354: 
1355: 
1356:     /********************* services ****************d*g**/
1357: 
1358: 
1359: 
1360:     /**
1361:      * Gets the context.
1362:      * @return SystemContainer|IDIContainer
1363:      */
1364:     final public function getContext()
1365:     {
1366:         return $this->context;
1367:     }
1368: 
1369: 
1370: 
1371:     /**
1372:      * @deprecated
1373:      */
1374:     final public function getService($name)
1375:     {
1376:         return $this->context->getService($name);
1377:     }
1378: 
1379: 
1380: 
1381:     /**
1382:      * @return NHttpRequest
1383:      */
1384:     protected function getHttpRequest()
1385:     {
1386:         return $this->context->getByType('IHttpRequest');
1387:     }
1388: 
1389: 
1390: 
1391:     /**
1392:      * @return NHttpResponse
1393:      */
1394:     protected function getHttpResponse()
1395:     {
1396:         return $this->context->getByType('IHttpResponse');
1397:     }
1398: 
1399: 
1400: 
1401:     /**
1402:      * @return NHttpContext
1403:      */
1404:     protected function getHttpContext()
1405:     {
1406:         return $this->context->getByType('NHttpContext');
1407:     }
1408: 
1409: 
1410: 
1411:     /**
1412:      * @return NApplication
1413:      */
1414:     public function getApplication()
1415:     {
1416:         return $this->context->getByType('NApplication');
1417:     }
1418: 
1419: 
1420: 
1421:     /**
1422:      * @return NSession
1423:      */
1424:     public function getSession($namespace = NULL)
1425:     {
1426:         $handler = $this->context->getByType('NSession');
1427:         return $namespace === NULL ? $handler : $handler->getSection($namespace);
1428:     }
1429: 
1430: 
1431: 
1432:     /**
1433:      * @return NUser
1434:      */
1435:     public function getUser()
1436:     {
1437:         return $this->context->getByType('NUser');
1438:     }
1439: 
1440: }
1441: 
Nette Framework 2.0.0 (for PHP 5.2, prefixed) API API documentation generated by ApiGen 2.7.0