2 /***************************************************************
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
8 * This class is a backport of the corresponding class of FLOW3.
9 * All credits go to the v5 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.
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
29 * A multi action controller. This is by far the most common base class for Controllers.
32 * @subpackage MVC\Controller
36 class Tx_Extbase_MVC_Controller_ActionController
extends Tx_Extbase_MVC_Controller_AbstractController
{
39 * @var Tx_Extbase_Reflection_Service
41 protected $reflectionService;
44 * The current view, as resolved by resolveView()
46 * @var Tx_Extbase_MVC_View_ViewInterface
49 protected $view = NULL;
52 * Pattern after which the view object name is built if no Fluid template
57 protected $viewObjectNamePattern = 'Tx_@extension_View_@controller_@action@format';
60 * A list of formats and object names of the views which should render them.
64 * array('html' => 'Tx_MyExtension_View_MyHtmlView', 'json' => 'F3...
68 protected $viewFormatToObjectNameMap = array();
71 * The default view object to use if none of the resolved views can render
72 * a response for the current request.
77 protected $defaultViewObjectName = 'Tx_Fluid_View_TemplateView';
80 * Name of the action method
84 protected $actionMethodName = 'indexAction';
87 * Name of the special error action method which is called in case of errors
91 protected $errorMethodName = 'errorAction';
94 * Injects the reflection service
96 * @param Tx_Extbase_Reflection_Service $reflectionService
99 public function injectReflectionService(Tx_Extbase_Reflection_Service
$reflectionService) {
100 $this->reflectionService
= $reflectionService;
104 * Checks if the current request type is supported by the controller.
106 * If your controller only supports certain request types, either
107 * replace / modify the supporteRequestTypes property or override this
110 * @param Tx_Extbase_MVC_Request $request The current request
111 * @return boolean TRUE if this request type is supported, otherwise FALSE
113 public function canProcessRequest(Tx_Extbase_MVC_RequestInterface
$request) {
114 return parent
::canProcessRequest($request);
119 * Handles a request. The result output is returned by altering the given response.
121 * @param Tx_Extbase_MVC_Request $request The request object
122 * @param Tx_Extbase_MVC_Response $response The response, modified by this handler
125 public function processRequest(Tx_Extbase_MVC_RequestInterface
$request, Tx_Extbase_MVC_ResponseInterface
$response) {
126 if (!$this->canProcessRequest($request)) throw new Tx_Extbase_MVC_Exception_UnsupportedRequestType(get_class($this) . ' does not support requests of type "' . get_class($request) . '". Supported types are: ' . implode(' ', $this->supportedRequestTypes
) , 1187701131);
128 $this->request
= $request;
129 $this->request
->setDispatched(TRUE);
130 $this->response
= $response;
132 $this->uriBuilder
= $this->objectManager
->create('Tx_Extbase_MVC_Web_Routing_UriBuilder');
133 $this->uriBuilder
->setRequest($request);
135 $this->actionMethodName
= $this->resolveActionMethodName();
137 $this->initializeActionMethodArguments();
138 $this->initializeActionMethodValidators();
140 $this->initializeAction();
141 $actionInitializationMethodName = 'initialize' . ucfirst($this->actionMethodName
);
142 if (method_exists($this, $actionInitializationMethodName)) {
143 call_user_func(array($this, $actionInitializationMethodName));
146 $this->mapRequestArgumentsToControllerArguments();
147 $this->checkRequestHash();
148 $this->controllerContext
= $this->buildControllerContext();
149 $this->view
= $this->resolveView();
150 if ($this->view
!== NULL) $this->initializeView($this->view
);
151 $this->callActionMethod();
155 * Implementation of the arguments initilization in the action controller:
156 * Automatically registers arguments of the current action
158 * Don't override this method - use initializeAction() instead.
161 * @see initializeArguments()
163 protected function initializeActionMethodArguments() {
164 $methodParameters = $this->reflectionService
->getMethodParameters(get_class($this), $this->actionMethodName
);
166 foreach ($methodParameters as $parameterName => $parameterInfo) {
168 if (isset($parameterInfo['type'])) {
169 $dataType = $parameterInfo['type'];
170 } elseif ($parameterInfo['array']) {
173 if ($dataType === NULL) throw new Tx_Extbase_MVC_Exception_InvalidArgumentType('The argument type for parameter "' . $parameterName . '" could not be detected.', 1253175643);
175 $defaultValue = (isset($parameterInfo['defaultValue']) ?
$parameterInfo['defaultValue'] : NULL);
177 $this->arguments
->addNewArgument($parameterName, $dataType, ($parameterInfo['optional'] === FALSE), $defaultValue);
182 * Adds the needed valiators to the Arguments:
183 * - Validators checking the data type from the @param annotation
184 * - Custom validators specified with @validate.
186 * In case @dontvalidate is NOT set for an argument, the following two
187 * validators are also added:
188 * - Model-based validators (@validate annotations in the model)
189 * - Custom model validator classes
193 protected function initializeActionMethodValidators() {
194 $parameterValidators = $this->validatorResolver
->buildMethodArgumentsValidatorConjunctions(get_class($this), $this->actionMethodName
);
196 $dontValidateAnnotations = array();
197 $methodTagsValues = $this->reflectionService
->getMethodTagsValues(get_class($this), $this->actionMethodName
);
198 if (isset($methodTagsValues['dontvalidate'])) {
199 $dontValidateAnnotations = $methodTagsValues['dontvalidate'];
202 foreach ($this->arguments
as $argument) {
203 $validator = $parameterValidators[$argument->getName()];
205 if (array_search('$' . $argument->getName(), $dontValidateAnnotations) === FALSE) {
206 $baseValidatorConjunction = $this->validatorResolver
->getBaseValidatorConjunction($argument->getDataType());
207 if ($baseValidatorConjunction !== NULL) {
208 $validator->addValidator($baseValidatorConjunction);
211 $argument->setValidator($validator);
216 * Resolves and checks the current action method name
218 * @return string Method name of the current action
219 * @throws Tx_Extbase_MVC_Exception_NoSuchAction if the action specified in the request object does not exist (and if there's no default action either).
221 protected function resolveActionMethodName() {
222 $actionMethodName = $this->request
->getControllerActionName() . 'Action';
223 if (!method_exists($this, $actionMethodName)) throw new Tx_Extbase_MVC_Exception_NoSuchAction('An action "' . $actionMethodName . '" does not exist in controller "' . get_class($this) . '".', 1186669086);
224 return $actionMethodName;
228 * Calls the specified action method and passes the arguments.
230 * If the action returns a string, it is appended to the content in the
231 * response object. If the action doesn't return anything and a valid
232 * view exists, the view is rendered automatically.
234 * @param string $actionMethodName Name of the action method to call
238 protected function callActionMethod() {
239 $argumentsAreValid = TRUE;
240 $preparedArguments = array();
241 foreach ($this->arguments
as $argument) {
242 $preparedArguments[] = $argument->getValue();
245 if ($this->argumentsMappingResults
->hasErrors()) {
246 $actionResult = call_user_func(array($this, $this->errorMethodName
));
248 $actionResult = call_user_func_array(array($this, $this->actionMethodName
), $preparedArguments);
250 if ($actionResult === NULL && $this->view
instanceof Tx_Extbase_MVC_View_ViewInterface
) {
251 $this->response
->appendContent($this->view
->render());
252 } elseif (is_string($actionResult) && strlen($actionResult) > 0) {
253 $this->response
->appendContent($actionResult);
258 * Prepares a view for the current action and stores it in $this->view.
259 * By default, this method tries to locate a view with a name matching
260 * the current action.
265 protected function resolveView() {
266 $viewObjectName = $this->resolveViewObjectName();
267 if ($viewObjectName !== FALSE) {
268 $view = $this->objectManager
->create($viewObjectName);
269 if ($view->canRender($this->controllerContext
) === FALSE) {
273 if (!isset($view) && $this->defaultViewObjectName
!= '') {
274 $view = $this->objectManager
->create($this->defaultViewObjectName
);
275 if ($view->canRender($this->controllerContext
) === FALSE) {
280 $view = $this->objectManager
->create('Tx_Extbase_MVC_View_NotFoundView');
281 $view->assign('errorMessage', 'No template was found. View could not be resolved for action "' . $this->request
->getControllerActionName() . '"');
283 $view->setControllerContext($this->controllerContext
);
285 $this->setViewConfiguration($view);
287 if (method_exists($view, 'injectSettings')) {
288 $view->injectSettings($this->settings
);
290 $view->initializeView(); // In FLOW3, solved through Object Lifecycle methods, we need to call it explicitely
291 $view->assign('settings', $this->settings
); // same with settings injection.
296 * @param Tx_Extbase_MVC_View_ViewInterface $view
299 protected function setViewConfiguration(Tx_Extbase_MVC_View_ViewInterface
$view) {
300 // Template Path Override
301 $extbaseFrameworkConfiguration = $this->configurationManager
->getConfiguration(Tx_Extbase_Configuration_ConfigurationManagerInterface
::CONFIGURATION_TYPE_FRAMEWORK
);
302 if (isset($extbaseFrameworkConfiguration['view']['templateRootPath'])
303 && strlen($extbaseFrameworkConfiguration['view']['templateRootPath']) > 0
304 && method_exists($view, 'setTemplateRootPath')) {
305 $view->setTemplateRootPath(t3lib_div
::getFileAbsFileName($extbaseFrameworkConfiguration['view']['templateRootPath']));
307 if (isset($extbaseFrameworkConfiguration['view']['layoutRootPath'])
308 && strlen($extbaseFrameworkConfiguration['view']['layoutRootPath']) > 0
309 && method_exists($view, 'setLayoutRootPath')) {
310 $view->setLayoutRootPath(t3lib_div
::getFileAbsFileName($extbaseFrameworkConfiguration['view']['layoutRootPath']));
312 if (isset($extbaseFrameworkConfiguration['view']['partialRootPath'])
313 && strlen($extbaseFrameworkConfiguration['view']['partialRootPath']) > 0
314 && method_exists($view, 'setPartialRootPath')) {
315 $view->setPartialRootPath(t3lib_div
::getFileAbsFileName($extbaseFrameworkConfiguration['view']['partialRootPath']));
320 * Determines the fully qualified view object name.
322 * @return mixed The fully qualified view object name or FALSE if no matching view could be found.
325 protected function resolveViewObjectName() {
326 $possibleViewName = $this->viewObjectNamePattern
;
327 $extensionName = $this->request
->getControllerExtensionName();
328 $possibleViewName = str_replace('@extension', $extensionName, $possibleViewName);
329 $possibleViewName = str_replace('@controller', $this->request
->getControllerName(), $possibleViewName);
330 $possibleViewName = str_replace('@action', ucfirst($this->request
->getControllerActionName()), $possibleViewName);
331 $format = $this->request
->getFormat();
333 $viewObjectName = str_replace('@format', ucfirst($this->request
->getFormat()), $possibleViewName);
334 if (class_exists($viewObjectName) === FALSE) {
335 $viewObjectName = str_replace('@format', '', $possibleViewName);
337 if (class_exists($viewObjectName) === FALSE && isset($this->viewFormatToObjectNameMap
[$format])) {
338 $viewObjectName = $this->viewFormatToObjectNameMap
[$format];
340 return class_exists($viewObjectName) ?
$viewObjectName : FALSE;
344 * Initializes the view before invoking an action method.
346 * Override this method to solve assign variables common for all actions
347 * or prepare the view in another way before the action is called.
349 * @param Tx_Extbase_View_ViewInterface $view The view to be initialized
353 protected function initializeView(Tx_Extbase_MVC_View_ViewInterface
$view) {
357 * Initializes the controller before invoking an action method.
359 * Override this method to solve tasks which all actions have in
365 protected function initializeAction() {
369 * A special action which is called if the originally intended action could
370 * not be called, for example if the arguments were not valid.
372 * The default implementation sets a flash message, request errors and forwards back
373 * to the originating action. This is suitable for most actions dealing with form input.
375 * We clear the page cache by default on an error as well, as we need to make sure the
376 * data is re-evaluated when the user changes something.
381 protected function errorAction() {
382 $this->request
->setErrors($this->argumentsMappingResults
->getErrors());
383 $this->clearCacheOnError();
385 $errorFlashMessage = $this->getErrorFlashMessage();
386 if ($errorFlashMessage !== FALSE) {
387 $this->flashMessages
->add($errorFlashMessage);
390 if ($this->request
->hasArgument('__referrer')) {
391 $referrer = $this->request
->getArgument('__referrer');
392 $this->forward($referrer['actionName'], $referrer['controllerName'], $referrer['extensionName'], $this->request
->getArguments());
395 $message = 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName
. '().' . PHP_EOL
;
396 foreach ($this->argumentsMappingResults
->getErrors() as $error) {
397 $message .= 'Error: ' . $error->getMessage() . PHP_EOL
;
399 foreach ($this->argumentsMappingResults
->getWarnings() as $warning) {
400 $message .= 'Warning: ' . $warning->getMessage() . PHP_EOL
;
406 * A template method for displaying custom error flash messages, or to
407 * display no flash message at all on errors. Override this to customize
408 * the flash message in your action controller.
410 * @return string|boolean The flash message or FALSE if no flash message should be set
413 protected function getErrorFlashMessage() {
414 return 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName
. '()';
418 * Checks the request hash (HMAC), if arguments have been touched by the property mapper.
420 * In case the @dontverifyrequesthash-Annotation has been set, this suppresses the exception.
423 * @throws Tx_Extbase_MVC_Exception_InvalidOrNoRequestHash In case request hash checking failed
424 * @author Sebastian Kurfürst <sebastian@typo3.org>
426 protected function checkRequestHash() {
427 if (!($this->request
instanceof Tx_Extbase_MVC_Web_Request
)) return; // We only want to check it for now for web requests.
428 if ($this->request
->isHmacVerified()) return; // all good
430 $verificationNeeded = FALSE;
431 foreach ($this->arguments
as $argument) {
432 if ($argument->getOrigin() == Tx_Extbase_MVC_Controller_Argument
::ORIGIN_NEWLY_CREATED
433 ||
$argument->getOrigin() == Tx_Extbase_MVC_Controller_Argument
::ORIGIN_PERSISTENCE_AND_MODIFIED
) {
434 $verificationNeeded = TRUE;
437 if ($verificationNeeded) {
438 $methodTagsValues = $this->reflectionService
->getMethodTagsValues(get_class($this), $this->actionMethodName
);
439 if (!isset($methodTagsValues['dontverifyrequesthash'])) {
440 throw new Tx_Extbase_MVC_Exception_InvalidOrNoRequestHash('Request hash (HMAC) checking failed. The parameter __hmac was invalid or not set, and objects were modified.', 1255082824);
446 * Clear cache of current page on error. Needed because we want a re-evaluation of the data.
447 * Better would be just do delete the cache for the error action, but that is not possible right now.
451 protected function clearCacheOnError() {
452 $extbaseSettings = $this->configurationManager
->getConfiguration(Tx_Extbase_Configuration_ConfigurationManagerInterface
::CONFIGURATION_TYPE_FRAMEWORK
);
453 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
454 if (isset($GLOBALS['TSFE'])) {
455 $pageUid = $GLOBALS['TSFE']->id
;
456 Tx_Extbase_Utility_Cache
::clearPageCache(array($pageUid));