2 namespace TYPO3\CMS\Extbase\Mvc\Controller
;
4 /***************************************************************
7 * (c) 2010-2013 Extbase Team (http://forge.typo3.org/projects/typo3v4-mvc)
8 * Extbase is a backport of TYPO3 Flow. All credits go to the TYPO3 Flow team.
11 * This script is part of the TYPO3 project. The TYPO3 project is
12 * free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
19 * A copy is found in the text file GPL.txt and important notices to the license
20 * from the author is found in LICENSE.txt distributed with these scripts.
23 * This script is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * This copyright notice MUST APPEAR in all copies of the script!
29 ***************************************************************/
30 use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
;
31 use TYPO3\CMS\Extbase\Mvc\View\ViewInterface
;
34 * A multi action controller. This is by far the most common base class for Controllers.
38 class ActionController
extends \TYPO3\CMS\Extbase\Mvc\Controller\AbstractController
{
41 * @var \TYPO3\CMS\Extbase\Reflection\ReflectionService
44 protected $reflectionService;
47 * @var \TYPO3\CMS\Extbase\Service\CacheService
50 protected $cacheService;
53 * The current view, as resolved by resolveView()
58 protected $view = NULL;
61 * Pattern after which the view object name is built if no Fluid template
66 * @deprecated since Extbase 6.2, will be removed two versions later
68 protected $viewObjectNamePattern = 'Tx_@extension_View_@controller_@action@format';
74 protected $namespacesViewObjectNamePattern = '@vendor\@extension\View\@controller\@action@format';
77 * A list of formats and object names of the views which should render them.
81 * array('html' => 'Tx_MyExtension_View_MyHtmlView', 'json' => 'F3...
85 protected $viewFormatToObjectNameMap = array();
88 * The default view object to use if none of the resolved views can render
89 * a response for the current request.
94 protected $defaultViewObjectName = 'TYPO3\\CMS\\Fluid\\View\\TemplateView';
97 * Name of the action method
102 protected $actionMethodName = 'indexAction';
105 * Name of the special error action method which is called in case of errors
110 protected $errorMethodName = 'errorAction';
113 * @var \TYPO3\CMS\Extbase\Mvc\Controller\MvcPropertyMappingConfigurationService
117 protected $mvcPropertyMappingConfigurationService;
120 * Checks if the current request type is supported by the controller.
122 * If your controller only supports certain request types, either
123 * replace / modify the supporteRequestTypes property or override this
126 * @param \TYPO3\CMS\Extbase\Mvc\RequestInterface $request The current request
128 * @return boolean TRUE if this request type is supported, otherwise FALSE
130 public function canProcessRequest(\TYPO3\CMS\Extbase\Mvc\RequestInterface
$request) {
131 return parent
::canProcessRequest($request);
135 * Handles a request. The result output is returned by altering the given response.
137 * @param \TYPO3\CMS\Extbase\Mvc\RequestInterface $request The request object
138 * @param \TYPO3\CMS\Extbase\Mvc\ResponseInterface $response The response, modified by this handler
140 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
143 public function processRequest(\TYPO3\CMS\Extbase\Mvc\RequestInterface
$request, \TYPO3\CMS\Extbase\Mvc\ResponseInterface
$response) {
144 if (!$this->canProcessRequest($request)) {
145 throw new \TYPO3\CMS\Extbase\Mvc\Exception\
UnsupportedRequestTypeException(get_class($this) . ' does not support requests of type "' . get_class($request) . '". Supported types are: ' . implode(' ', $this->supportedRequestTypes
), 1187701131);
147 if ($response instanceof \TYPO3\CMS\Extbase\Mvc\Web\Response
) {
148 $response->setRequest($request);
150 $this->request
= $request;
151 $this->request
->setDispatched(TRUE);
152 $this->response
= $response;
153 $this->uriBuilder
= $this->objectManager
->get('TYPO3\\CMS\\Extbase\\Mvc\\Web\\Routing\\UriBuilder');
154 $this->uriBuilder
->setRequest($request);
155 $this->actionMethodName
= $this->resolveActionMethodName();
156 $this->initializeActionMethodArguments();
157 $this->initializeActionMethodValidators();
158 $this->mvcPropertyMappingConfigurationService
->initializePropertyMappingConfigurationFromRequest($request, $this->arguments
);
159 $this->initializeAction();
160 $actionInitializationMethodName = 'initialize' . ucfirst($this->actionMethodName
);
161 if (method_exists($this, $actionInitializationMethodName)) {
162 call_user_func(array($this, $actionInitializationMethodName));
164 $this->mapRequestArgumentsToControllerArguments();
165 $this->checkRequestHash();
166 $this->controllerContext
= $this->buildControllerContext();
167 $this->view
= $this->resolveView();
168 if ($this->view
!== NULL) {
169 $this->initializeView($this->view
);
171 $this->callActionMethod();
175 * Implementation of the arguments initilization in the action controller:
176 * Automatically registers arguments of the current action
178 * Don't override this method - use initializeAction() instead.
180 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\InvalidArgumentTypeException
182 * @see initializeArguments()
184 protected function initializeActionMethodArguments() {
185 $methodParameters = $this->reflectionService
->getMethodParameters(get_class($this), $this->actionMethodName
);
186 foreach ($methodParameters as $parameterName => $parameterInfo) {
188 if (isset($parameterInfo['type'])) {
189 $dataType = $parameterInfo['type'];
190 } elseif ($parameterInfo['array']) {
193 if ($dataType === NULL) {
194 throw new \TYPO3\CMS\Extbase\Mvc\Exception\
InvalidArgumentTypeException('The argument type for parameter $' . $parameterName . ' of method ' . get_class($this) . '->' . $this->actionMethodName
. '() could not be detected.', 1253175643);
196 $defaultValue = isset($parameterInfo['defaultValue']) ?
$parameterInfo['defaultValue'] : NULL;
197 $this->arguments
->addNewArgument($parameterName, $dataType, $parameterInfo['optional'] === FALSE, $defaultValue);
202 * Adds the needed validators to the Arguments:
204 * - Validators checking the data type from the @param annotation
205 * - Custom validators specified with validate annotations.
206 * - Model-based validators (validate annotations in the model)
207 * - Custom model validator classes
211 protected function initializeActionMethodValidators() {
213 if (!$this->configurationManager
->isFeatureEnabled('rewrittenPropertyMapper')) {
214 // @deprecated since Extbase 1.4.0, will be removed two versions after Extbase 6.1
216 $parameterValidators = $this->validatorResolver
->buildMethodArgumentsValidatorConjunctions(get_class($this), $this->actionMethodName
);
217 $dontValidateAnnotations = array();
219 $methodTagsValues = $this->reflectionService
->getMethodTagsValues(get_class($this), $this->actionMethodName
);
220 if (isset($methodTagsValues['dontvalidate'])) {
221 $dontValidateAnnotations = $methodTagsValues['dontvalidate'];
224 foreach ($this->arguments
as $argument) {
225 $validator = $parameterValidators[$argument->getName()];
226 if (array_search('$' . $argument->getName(), $dontValidateAnnotations) === FALSE) {
227 $baseValidatorConjunction = $this->validatorResolver
->getBaseValidatorConjunction($argument->getDataType());
228 if ($baseValidatorConjunction !== NULL) {
229 $validator->addValidator($baseValidatorConjunction);
232 $argument->setValidator($validator);
236 * @todo: add validation group support
237 * (https://review.typo3.org/#/c/13556/4)
240 $actionMethodParameters = static::getActionMethodParameters($this->objectManager
);
241 if (isset($actionMethodParameters[$this->actionMethodName
])) {
242 $methodParameters = $actionMethodParameters[$this->actionMethodName
];
244 $methodParameters = array();
248 * @todo: add resolving of $actionValidateAnnotations and pass them to
249 * buildMethodArgumentsValidatorConjunctions as in TYPO3.Flow
252 $parameterValidators = $this->validatorResolver
->buildMethodArgumentsValidatorConjunctions(get_class($this), $this->actionMethodName
, $methodParameters);
254 foreach ($this->arguments
as $argument) {
255 $validator = $parameterValidators[$argument->getName()];
257 $baseValidatorConjunction = $this->validatorResolver
->getBaseValidatorConjunction($argument->getDataType());
258 if (count($baseValidatorConjunction) > 0) {
259 $validator->addValidator($baseValidatorConjunction);
261 $argument->setValidator($validator);
267 * Resolves and checks the current action method name
269 * @return string Method name of the current action
270 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchActionException if the action specified in the request object does not exist (and if there's no default action either).
272 protected function resolveActionMethodName() {
273 $actionMethodName = $this->request
->getControllerActionName() . 'Action';
274 if (!method_exists($this, $actionMethodName)) {
275 throw new \TYPO3\CMS\Extbase\Mvc\Exception\
NoSuchActionException('An action "' . $actionMethodName . '" does not exist in controller "' . get_class($this) . '".', 1186669086);
277 return $actionMethodName;
281 * Calls the specified action method and passes the arguments.
283 * If the action returns a string, it is appended to the content in the
284 * response object. If the action doesn't return anything and a valid
285 * view exists, the view is rendered automatically.
290 protected function callActionMethod() {
291 if ($this->configurationManager
->isFeatureEnabled('rewrittenPropertyMapper')) {
292 // enabled since Extbase 1.4.0.
293 $preparedArguments = array();
294 foreach ($this->arguments
as $argument) {
295 $preparedArguments[] = $argument->getValue();
297 $validationResult = $this->arguments
->getValidationResults();
298 if (!$validationResult->hasErrors()) {
299 $this->emitBeforeCallActionMethodSignal($preparedArguments);
300 $actionResult = call_user_func_array(array($this, $this->actionMethodName
), $preparedArguments);
302 $methodTagsValues = $this->reflectionService
->getMethodTagsValues(get_class($this), $this->actionMethodName
);
303 $ignoreValidationAnnotations = array();
304 if (isset($methodTagsValues['ignorevalidation'])) {
305 $ignoreValidationAnnotations = $methodTagsValues['ignorevalidation'];
307 // if there exists more errors than in ignoreValidationAnnotations_=> call error method
308 // else => call action method
309 $shouldCallActionMethod = TRUE;
310 foreach ($validationResult->getSubResults() as $argumentName => $subValidationResult) {
311 if (!$subValidationResult->hasErrors()) {
314 if (array_search('$' . $argumentName, $ignoreValidationAnnotations) !== FALSE) {
317 $shouldCallActionMethod = FALSE;
319 if ($shouldCallActionMethod) {
320 $this->emitBeforeCallActionMethodSignal($preparedArguments);
321 $actionResult = call_user_func_array(array($this, $this->actionMethodName
), $preparedArguments);
323 $actionResult = call_user_func(array($this, $this->errorMethodName
));
327 // @deprecated since Extbase 1.4.0, will be removed two versions after Extbase 6.1
328 $preparedArguments = array();
329 foreach ($this->arguments
as $argument) {
330 $preparedArguments[] = $argument->getValue();
332 if ($this->argumentsMappingResults
->hasErrors()) {
333 $actionResult = call_user_func(array($this, $this->errorMethodName
));
335 $this->emitBeforeCallActionMethodSignal($preparedArguments);
336 $actionResult = call_user_func_array(array($this, $this->actionMethodName
), $preparedArguments);
339 if ($actionResult === NULL && $this->view
instanceof ViewInterface
) {
340 $this->response
->appendContent($this->view
->render());
341 } elseif (is_string($actionResult) && strlen($actionResult) > 0) {
342 $this->response
->appendContent($actionResult);
343 } elseif (is_object($actionResult) && method_exists($actionResult, '__toString')) {
344 $this->response
->appendContent((string)$actionResult);
349 * Emits a signal before the current action is called
351 * @param array $preparedArguments
353 protected function emitBeforeCallActionMethodSignal(array $preparedArguments) {
354 $this->signalSlotDispatcher
->dispatch(__CLASS__
, 'beforeCallActionMethod', array('controllerName' => get_class($this), 'actionMethodName' => $this->actionMethodName
, 'preparedArguments' => $preparedArguments));
358 * Prepares a view for the current action and stores it in $this->view.
359 * By default, this method tries to locate a view with a name matching
360 * the current action.
365 protected function resolveView() {
366 $viewObjectName = $this->resolveViewObjectName();
367 if ($viewObjectName !== FALSE) {
368 /** @var $view ViewInterface */
369 $view = $this->objectManager
->get($viewObjectName);
370 $this->setViewConfiguration($view);
371 if ($view->canRender($this->controllerContext
) === FALSE) {
375 if (!isset($view) && $this->defaultViewObjectName
!= '') {
376 /** @var $view ViewInterface */
377 $view = $this->objectManager
->get($this->defaultViewObjectName
);
378 $this->setViewConfiguration($view);
379 if ($view->canRender($this->controllerContext
) === FALSE) {
384 $view = $this->objectManager
->get('TYPO3\\CMS\\Extbase\\Mvc\\View\\NotFoundView');
385 $view->assign('errorMessage', 'No template was found. View could not be resolved for action "'
386 . $this->request
->getControllerActionName() . '" in class "' . $this->request
->getControllerObjectName() . '"');
388 $view->setControllerContext($this->controllerContext
);
389 if (method_exists($view, 'injectSettings')) {
390 $view->injectSettings($this->settings
);
392 $view->initializeView();
393 // In FLOW3, solved through Object Lifecycle methods, we need to call it explicitely
394 $view->assign('settings', $this->settings
);
395 // same with settings injection.
400 * @param ViewInterface $view
404 protected function setViewConfiguration(ViewInterface
$view) {
405 // Template Path Override
406 $extbaseFrameworkConfiguration = $this->configurationManager
->getConfiguration(
407 ConfigurationManagerInterface
::CONFIGURATION_TYPE_FRAMEWORK
410 // set TemplateRootPaths
411 $viewFunctionName = 'setTemplateRootPaths';
412 if (method_exists($view, $viewFunctionName)) {
413 $deprecatedSetting = 'templateRootPath';
414 $setting = 'templateRootPaths';
415 $parameter = $this->getViewProperty($extbaseFrameworkConfiguration, $setting, $deprecatedSetting);
416 // no need to bother if there is nothing to set
418 $view->$viewFunctionName($parameter);
422 // set LayoutRootPaths
423 $viewFunctionName = 'setLayoutRootPaths';
424 if (method_exists($view, $viewFunctionName)) {
425 $deprecatedSetting = 'layoutRootPath';
426 $setting = 'layoutRootPaths';
427 $parameter = $this->getViewProperty($extbaseFrameworkConfiguration, $setting, $deprecatedSetting);
428 // no need to bother if there is nothing to set
430 $view->$viewFunctionName($parameter);
434 // set PartialRootPaths
435 $viewFunctionName = 'setPartialRootPaths';
436 if (method_exists($view, $viewFunctionName)) {
437 $deprecatedSetting = 'partialRootPath';
438 $setting = 'partialRootPaths';
439 $parameter = $this->getViewProperty($extbaseFrameworkConfiguration, $setting, $deprecatedSetting);
440 // no need to bother if there is nothing to set
442 $view->$viewFunctionName($parameter);
448 * Handles the path resolving for *rootPath(s)
449 * singular one is deprecated and will be removed two versions after 6.2
450 * if deprecated setting is found, use it as the very last fallback target
452 * numerical arrays get ordered by key ascending
454 * @param array $extbaseFrameworkConfiguration
455 * @param string $setting parameter name from TypoScript
456 * @param string $deprecatedSetting parameter name from TypoScript
460 protected function getViewProperty($extbaseFrameworkConfiguration, $setting, $deprecatedSetting = '') {
465 !empty($extbaseFrameworkConfiguration['view'][$setting])
466 && is_array($extbaseFrameworkConfiguration['view'][$setting])
468 $values = \TYPO3\CMS\Extbase\Utility\ArrayUtility
::sortArrayWithIntegerKeys($extbaseFrameworkConfiguration['view'][$setting]);
469 $values = array_reverse($values, TRUE);
472 // @todo remove handling of deprecatedSetting two versions after 6.2
474 isset($extbaseFrameworkConfiguration['view'][$deprecatedSetting])
475 && strlen($extbaseFrameworkConfiguration['view'][$deprecatedSetting]) > 0
477 $values[] = $extbaseFrameworkConfiguration['view'][$deprecatedSetting];
484 * Determines the fully qualified view object name.
486 * @return mixed The fully qualified view object name or FALSE if no matching view could be found.
489 protected function resolveViewObjectName() {
490 $vendorName = $this->request
->getControllerVendorName();
492 if ($vendorName !== NULL) {
493 $possibleViewName = str_replace('@vendor', $vendorName, $this->namespacesViewObjectNamePattern
);
495 $possibleViewName = $this->viewObjectNamePattern
;
498 $possibleViewName = str_replace(
505 $this->request
->getControllerExtensionName(),
506 $this->request
->getControllerName(),
507 ucfirst($this->request
->getControllerActionName())
511 $format = $this->request
->getFormat();
512 $viewObjectName = str_replace('@format', ucfirst($format), $possibleViewName);
513 if (class_exists($viewObjectName) === FALSE) {
514 $viewObjectName = str_replace('@format', '', $possibleViewName);
516 if (isset($this->viewFormatToObjectNameMap
[$format]) && class_exists($viewObjectName) === FALSE) {
517 $viewObjectName = $this->viewFormatToObjectNameMap
[$format];
519 return class_exists($viewObjectName) ?
$viewObjectName : FALSE;
523 * Initializes the view before invoking an action method.
525 * Override this method to solve assign variables common for all actions
526 * or prepare the view in another way before the action is called.
528 * @param ViewInterface $view The view to be initialized
533 protected function initializeView(ViewInterface
$view) {
537 * Initializes the controller before invoking an action method.
539 * Override this method to solve tasks which all actions have in
545 protected function initializeAction() {
549 * A special action which is called if the originally intended action could
550 * not be called, for example if the arguments were not valid.
552 * The default implementation sets a flash message, request errors and forwards back
553 * to the originating action. This is suitable for most actions dealing with form input.
555 * We clear the page cache by default on an error as well, as we need to make sure the
556 * data is re-evaluated when the user changes something.
561 protected function errorAction() {
562 $this->clearCacheOnError();
563 if ($this->configurationManager
->isFeatureEnabled('rewrittenPropertyMapper')) {
564 $errorFlashMessage = $this->getErrorFlashMessage();
565 if ($errorFlashMessage !== FALSE) {
566 $errorFlashMessageObject = new \TYPO3\CMS\Core\Messaging\
FlashMessage(
569 \TYPO3\CMS\Core\Messaging\FlashMessage
::ERROR
571 $this->controllerContext
->getFlashMessageQueue()->enqueue($errorFlashMessageObject);
573 $referringRequest = $this->request
->getReferringRequest();
574 if ($referringRequest !== NULL) {
575 $originalRequest = clone $this->request
;
576 $this->request
->setOriginalRequest($originalRequest);
577 $this->request
->setOriginalRequestMappingResults($this->arguments
->getValidationResults());
578 $this->forward($referringRequest->getControllerActionName(), $referringRequest->getControllerName(), $referringRequest->getControllerExtensionName(), $referringRequest->getArguments());
580 $message = 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName
. '().' . PHP_EOL
;
583 // @deprecated since Extbase 1.4.0, will be removed two versions after Extbase 6.1
584 $this->request
->setErrors($this->argumentsMappingResults
->getErrors());
585 $errorFlashMessage = $this->getErrorFlashMessage();
586 if ($errorFlashMessage !== FALSE) {
587 $errorFlashMessageObject = new \TYPO3\CMS\Core\Messaging\
FlashMessage(
590 \TYPO3\CMS\Core\Messaging\FlashMessage
::ERROR
592 $this->controllerContext
->getFlashMessageQueue()->enqueue($errorFlashMessageObject);
594 $referrer = $this->request
->getInternalArgument('__referrer');
595 if ($referrer !== NULL) {
596 $this->forward($referrer['actionName'], $referrer['controllerName'], $referrer['extensionName'], $this->request
->getArguments());
598 $message = 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName
. '().' . PHP_EOL
;
604 * A template method for displaying custom error flash messages, or to
605 * display no flash message at all on errors. Override this to customize
606 * the flash message in your action controller.
608 * @return string The flash message or FALSE if no flash message should be set
611 protected function getErrorFlashMessage() {
612 return 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName
. '()';
616 * Checks the request hash (HMAC), if arguments have been touched by the property mapper.
618 * In case the @dontverifyrequesthash-Annotation has been set, this suppresses the exception.
621 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\InvalidOrNoRequestHashException In case request hash checking failed
622 * @deprecated since Extbase 1.4.0, will be removed two versions after Extbase 6.1
624 protected function checkRequestHash() {
625 if ($this->configurationManager
->isFeatureEnabled('rewrittenPropertyMapper')) {
626 // If the new property mapper is enabled, the request hash is not needed anymore.
629 if (!$this->request
instanceof \TYPO3\CMS\Extbase\Mvc\Web\Request
) {
632 // We only want to check it for now for web requests.
633 if ($this->request
->isHmacVerified()) {
637 $verificationNeeded = FALSE;
638 foreach ($this->arguments
as $argument) {
639 if ($argument->getOrigin() == \TYPO3\CMS\Extbase\Mvc\Controller\Argument
::ORIGIN_NEWLY_CREATED ||
$argument->getOrigin() == \TYPO3\CMS\Extbase\Mvc\Controller\Argument
::ORIGIN_PERSISTENCE_AND_MODIFIED
) {
640 $verificationNeeded = TRUE;
643 if ($verificationNeeded) {
644 $methodTagsValues = $this->reflectionService
->getMethodTagsValues(get_class($this), $this->actionMethodName
);
645 if (!isset($methodTagsValues['dontverifyrequesthash'])) {
646 throw new \TYPO3\CMS\Extbase\Mvc\Exception\
InvalidOrNoRequestHashException('Request hash (HMAC) checking failed. The parameter __hmac was invalid or not set, and objects were modified.', 1255082824);
652 * Clear cache of current page on error. Needed because we want a re-evaluation of the data.
653 * Better would be just do delete the cache for the error action, but that is not possible right now.
657 protected function clearCacheOnError() {
658 $extbaseSettings = $this->configurationManager
->getConfiguration(ConfigurationManagerInterface
::CONFIGURATION_TYPE_FRAMEWORK
);
659 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
660 if (isset($GLOBALS['TSFE'])) {
661 $pageUid = $GLOBALS['TSFE']->id
;
662 $this->cacheService
->clearPageCache(array($pageUid));
668 * Returns a map of action method names and their parameters.
670 * @param \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager
672 * @return array Array of method parameters by action name
674 static public function getActionMethodParameters($objectManager) {
675 $reflectionService = $objectManager->get('TYPO3\CMS\Extbase\Reflection\ReflectionService');
679 $className = get_called_class();
680 $methodNames = get_class_methods($className);
681 foreach ($methodNames as $methodName) {
682 if (strlen($methodName) > 6 && strpos($methodName, 'Action', strlen($methodName) - 6) !== FALSE) {
683 $result[$methodName] = $reflectionService->getMethodParameters($className, $methodName);