Merge "[BUGFIX] ConfigurationManager use FrontendSimulator only if neccessary"
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / MVC / Controller / ActionController.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
6 * All rights reserved
7 *
8 * This class is a backport of the corresponding class of FLOW3.
9 * All credits go to the v5 team.
10 *
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.
16 *
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
19 *
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.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27
28 /**
29 * A multi action controller. This is by far the most common base class for Controllers.
30 *
31 * @package Extbase
32 * @subpackage MVC\Controller
33 * @version $ID:$
34 * @api
35 */
36 class Tx_Extbase_MVC_Controller_ActionController extends Tx_Extbase_MVC_Controller_AbstractController {
37
38 /**
39 * @var Tx_Extbase_Reflection_Service
40 */
41 protected $reflectionService;
42
43 /**
44 * @var Tx_Extbase_Service_CacheService
45 */
46 protected $cacheService;
47
48 /**
49 * The current view, as resolved by resolveView()
50 *
51 * @var Tx_Extbase_MVC_View_ViewInterface
52 * @api
53 */
54 protected $view = NULL;
55
56 /**
57 * Pattern after which the view object name is built if no Fluid template
58 * is found.
59 * @var string
60 * @api
61 */
62 protected $viewObjectNamePattern = 'Tx_@extension_View_@controller_@action@format';
63
64 /**
65 * A list of formats and object names of the views which should render them.
66 *
67 * Example:
68 *
69 * array('html' => 'Tx_MyExtension_View_MyHtmlView', 'json' => 'F3...
70 *
71 * @var array
72 */
73 protected $viewFormatToObjectNameMap = array();
74
75 /**
76 * The default view object to use if none of the resolved views can render
77 * a response for the current request.
78 *
79 * @var string
80 * @api
81 */
82 protected $defaultViewObjectName = 'Tx_Fluid_View_TemplateView';
83
84 /**
85 * Name of the action method
86 * @var string
87 * @api
88 */
89 protected $actionMethodName = 'indexAction';
90
91 /**
92 * Name of the special error action method which is called in case of errors
93 * @var string
94 * @api
95 */
96 protected $errorMethodName = 'errorAction';
97
98 /**
99 * @param Tx_Extbase_Reflection_Service $reflectionService
100 * @return void
101 */
102 public function injectReflectionService(Tx_Extbase_Reflection_Service $reflectionService) {
103 $this->reflectionService = $reflectionService;
104 }
105
106 /**
107 * @param Tx_Extbase_Service_CacheService $cacheService
108 * @return void
109 */
110 public function injectCacheService(Tx_Extbase_Service_CacheService $cacheService) {
111 $this->cacheService = $cacheService;
112 }
113
114 /**
115 * Checks if the current request type is supported by the controller.
116 *
117 * If your controller only supports certain request types, either
118 * replace / modify the supporteRequestTypes property or override this
119 * method.
120 *
121 * @param Tx_Extbase_MVC_Request $request The current request
122 * @return boolean TRUE if this request type is supported, otherwise FALSE
123 */
124 public function canProcessRequest(Tx_Extbase_MVC_RequestInterface $request) {
125 return parent::canProcessRequest($request);
126
127 }
128
129 /**
130 * Handles a request. The result output is returned by altering the given response.
131 *
132 * @param Tx_Extbase_MVC_Request $request The request object
133 * @param Tx_Extbase_MVC_Response $response The response, modified by this handler
134 * @return void
135 */
136 public function processRequest(Tx_Extbase_MVC_RequestInterface $request, Tx_Extbase_MVC_ResponseInterface $response) {
137 if (!$this->canProcessRequest($request)) {
138 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);
139 }
140
141 $this->request = $request;
142 $this->request->setDispatched(TRUE);
143 $this->response = $response;
144
145 $this->uriBuilder = $this->objectManager->create('Tx_Extbase_MVC_Web_Routing_UriBuilder');
146 $this->uriBuilder->setRequest($request);
147
148 $this->actionMethodName = $this->resolveActionMethodName();
149
150 $this->initializeActionMethodArguments();
151 $this->initializeActionMethodValidators();
152
153 $this->initializeAction();
154 $actionInitializationMethodName = 'initialize' . ucfirst($this->actionMethodName);
155 if (method_exists($this, $actionInitializationMethodName)) {
156 call_user_func(array($this, $actionInitializationMethodName));
157 }
158
159 $this->mapRequestArgumentsToControllerArguments();
160 $this->checkRequestHash();
161 $this->controllerContext = $this->buildControllerContext();
162 $this->view = $this->resolveView();
163 if ($this->view !== NULL) {
164 $this->initializeView($this->view);
165 }
166 $this->callActionMethod();
167 }
168
169 /**
170 * Implementation of the arguments initilization in the action controller:
171 * Automatically registers arguments of the current action
172 *
173 * Don't override this method - use initializeAction() instead.
174 *
175 * @return void
176 * @see initializeArguments()
177 */
178 protected function initializeActionMethodArguments() {
179 $methodParameters = $this->reflectionService->getMethodParameters(get_class($this), $this->actionMethodName);
180
181 foreach ($methodParameters as $parameterName => $parameterInfo) {
182 $dataType = NULL;
183 if (isset($parameterInfo['type'])) {
184 $dataType = $parameterInfo['type'];
185 } elseif ($parameterInfo['array']) {
186 $dataType = 'array';
187 }
188 if ($dataType === NULL) throw new Tx_Extbase_MVC_Exception_InvalidArgumentType('The argument type for parameter $' . $parameterName . ' of method ' . get_class($this) . '->' . $this->actionMethodName . '() could not be detected.' , 1253175643);
189
190 $defaultValue = (isset($parameterInfo['defaultValue']) ? $parameterInfo['defaultValue'] : NULL);
191
192 $this->arguments->addNewArgument($parameterName, $dataType, ($parameterInfo['optional'] === FALSE), $defaultValue);
193 }
194 }
195
196 /**
197 * Adds the needed valiators to the Arguments:
198 * - Validators checking the data type from the @param annotation
199 * - Custom validators specified with @validate.
200 *
201 * In case @dontvalidate is NOT set for an argument, the following two
202 * validators are also added:
203 * - Model-based validators (@validate annotations in the model)
204 * - Custom model validator classes
205 *
206 * @return void
207 */
208 protected function initializeActionMethodValidators() {
209 // TODO: still needs to be modified
210 $parameterValidators = $this->validatorResolver->buildMethodArgumentsValidatorConjunctions(get_class($this), $this->actionMethodName);
211
212 $dontValidateAnnotations = array();
213
214 if (!$this->configurationManager->isFeatureEnabled('rewrittenPropertyMapper')) {
215 // If the rewritten property mapper is *enabled*, we do not support @dontvalidate annotation, thus $dontValidateAnnotations stays empty.
216 $methodTagsValues = $this->reflectionService->getMethodTagsValues(get_class($this), $this->actionMethodName);
217 if (isset($methodTagsValues['dontvalidate'])) {
218 $dontValidateAnnotations = $methodTagsValues['dontvalidate'];
219 }
220 }
221
222 foreach ($this->arguments as $argument) {
223 $validator = $parameterValidators[$argument->getName()];
224
225 if (array_search('$' . $argument->getName(), $dontValidateAnnotations) === FALSE) {
226 $baseValidatorConjunction = $this->validatorResolver->getBaseValidatorConjunction($argument->getDataType());
227 if ($baseValidatorConjunction !== NULL) {
228 $validator->addValidator($baseValidatorConjunction);
229 }
230 }
231 $argument->setValidator($validator);
232 }
233 }
234
235 /**
236 * Resolves and checks the current action method name
237 *
238 * @return string Method name of the current action
239 * @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).
240 */
241 protected function resolveActionMethodName() {
242 $actionMethodName = $this->request->getControllerActionName() . 'Action';
243 if (!method_exists($this, $actionMethodName)) throw new Tx_Extbase_MVC_Exception_NoSuchAction('An action "' . $actionMethodName . '" does not exist in controller "' . get_class($this) . '".', 1186669086);
244 return $actionMethodName;
245 }
246
247 /**
248 * Calls the specified action method and passes the arguments.
249 *
250 * If the action returns a string, it is appended to the content in the
251 * response object. If the action doesn't return anything and a valid
252 * view exists, the view is rendered automatically.
253 *
254 * @param string $actionMethodName Name of the action method to call
255 * @return void
256 * @api
257 */
258 protected function callActionMethod() {
259 if ($this->configurationManager->isFeatureEnabled('rewrittenPropertyMapper')) {
260 // enabled since Extbase 1.4.0.
261 $preparedArguments = array();
262 foreach ($this->arguments as $argument) {
263 $preparedArguments[] = $argument->getValue();
264 }
265
266 $validationResult = $this->arguments->getValidationResults();
267
268 if (!$validationResult->hasErrors()) {
269 $actionResult = call_user_func_array(array($this, $this->actionMethodName), $preparedArguments);
270 } else {
271 $methodTagsValues = $this->reflectionService->getMethodTagsValues(get_class($this), $this->actionMethodName);
272 $ignoreValidationAnnotations = array();
273 if (isset($methodTagsValues['ignorevalidation'])) {
274 $ignoreValidationAnnotations = $methodTagsValues['ignorevalidation'];
275 }
276
277 // if there exists more errors than in ignoreValidationAnnotations_=> call error method
278 // else => call action method
279 $shouldCallActionMethod = TRUE;
280 foreach ($validationResult->getSubResults() as $argumentName => $subValidationResult) {
281 if (!$subValidationResult->hasErrors()) continue;
282
283 if (array_search('$' . $argumentName, $ignoreValidationAnnotations) !== FALSE) continue;
284
285 $shouldCallActionMethod = FALSE;
286 }
287
288 if ($shouldCallActionMethod) {
289 $actionResult = call_user_func_array(array($this, $this->actionMethodName), $preparedArguments);
290 } else {
291 $actionResult = call_user_func(array($this, $this->errorMethodName));
292 }
293 }
294 } else {
295 // @deprecated since Extbase 1.4.0, will be removed with Extbase 1.6.0.
296 $argumentsAreValid = TRUE;
297 $preparedArguments = array();
298 foreach ($this->arguments as $argument) {
299 $preparedArguments[] = $argument->getValue();
300 }
301
302 if ($this->argumentsMappingResults->hasErrors()) {
303 $actionResult = call_user_func(array($this, $this->errorMethodName));
304 } else {
305 $actionResult = call_user_func_array(array($this, $this->actionMethodName), $preparedArguments);
306 }
307 }
308
309 if ($actionResult === NULL && $this->view instanceof Tx_Extbase_MVC_View_ViewInterface) {
310 $this->response->appendContent($this->view->render());
311 } elseif (is_string($actionResult) && strlen($actionResult) > 0) {
312 $this->response->appendContent($actionResult);
313 } elseif (is_object($actionResult) && method_exists($actionResult, '__toString')) {
314 $this->response->appendContent((string)$actionResult);
315 }
316 }
317
318 /**
319 * Prepares a view for the current action and stores it in $this->view.
320 * By default, this method tries to locate a view with a name matching
321 * the current action.
322 *
323 * @return void
324 * @api
325 */
326 protected function resolveView() {
327 $viewObjectName = $this->resolveViewObjectName();
328 if ($viewObjectName !== FALSE) {
329 $view = $this->objectManager->create($viewObjectName);
330 $this->setViewConfiguration($view);
331 if ($view->canRender($this->controllerContext) === FALSE) {
332 unset($view);
333 }
334 }
335 if (!isset($view) && $this->defaultViewObjectName != '') {
336 $view = $this->objectManager->create($this->defaultViewObjectName);
337 $this->setViewConfiguration($view);
338 if ($view->canRender($this->controllerContext) === FALSE) {
339 unset($view);
340 }
341 }
342 if (!isset($view)) {
343 $view = $this->objectManager->create('Tx_Extbase_MVC_View_NotFoundView');
344 $view->assign('errorMessage', 'No template was found. View could not be resolved for action "' . $this->request->getControllerActionName() . '"');
345 }
346 $view->setControllerContext($this->controllerContext);
347
348 if (method_exists($view, 'injectSettings')) {
349 $view->injectSettings($this->settings);
350 }
351 $view->initializeView(); // In FLOW3, solved through Object Lifecycle methods, we need to call it explicitely
352 $view->assign('settings', $this->settings); // same with settings injection.
353 return $view;
354 }
355
356 /**
357 * @param Tx_Extbase_MVC_View_ViewInterface $view
358 * @return void
359 */
360 protected function setViewConfiguration(Tx_Extbase_MVC_View_ViewInterface $view) {
361 // Template Path Override
362 $extbaseFrameworkConfiguration = $this->configurationManager->getConfiguration(Tx_Extbase_Configuration_ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
363 if (isset($extbaseFrameworkConfiguration['view']['templateRootPath'])
364 && strlen($extbaseFrameworkConfiguration['view']['templateRootPath']) > 0
365 && method_exists($view, 'setTemplateRootPath')) {
366 $view->setTemplateRootPath(t3lib_div::getFileAbsFileName($extbaseFrameworkConfiguration['view']['templateRootPath']));
367 }
368 if (isset($extbaseFrameworkConfiguration['view']['layoutRootPath'])
369 && strlen($extbaseFrameworkConfiguration['view']['layoutRootPath']) > 0
370 && method_exists($view, 'setLayoutRootPath')) {
371 $view->setLayoutRootPath(t3lib_div::getFileAbsFileName($extbaseFrameworkConfiguration['view']['layoutRootPath']));
372 }
373 if (isset($extbaseFrameworkConfiguration['view']['partialRootPath'])
374 && strlen($extbaseFrameworkConfiguration['view']['partialRootPath']) > 0
375 && method_exists($view, 'setPartialRootPath')) {
376 $view->setPartialRootPath(t3lib_div::getFileAbsFileName($extbaseFrameworkConfiguration['view']['partialRootPath']));
377 }
378 }
379
380 /**
381 * Determines the fully qualified view object name.
382 *
383 * @return mixed The fully qualified view object name or FALSE if no matching view could be found.
384 * @api
385 */
386 protected function resolveViewObjectName() {
387 $possibleViewName = $this->viewObjectNamePattern;
388 $extensionName = $this->request->getControllerExtensionName();
389 $possibleViewName = str_replace('@extension', $extensionName, $possibleViewName);
390 $possibleViewName = str_replace('@controller', $this->request->getControllerName(), $possibleViewName);
391 $possibleViewName = str_replace('@action', ucfirst($this->request->getControllerActionName()), $possibleViewName);
392 $format = $this->request->getFormat();
393
394 $viewObjectName = str_replace('@format', ucfirst($this->request->getFormat()), $possibleViewName);
395 if (class_exists($viewObjectName) === FALSE) {
396 $viewObjectName = str_replace('@format', '', $possibleViewName);
397 }
398 if (class_exists($viewObjectName) === FALSE && isset($this->viewFormatToObjectNameMap[$format])) {
399 $viewObjectName = $this->viewFormatToObjectNameMap[$format];
400 }
401 return class_exists($viewObjectName) ? $viewObjectName : FALSE;
402 }
403
404 /**
405 * Initializes the view before invoking an action method.
406 *
407 * Override this method to solve assign variables common for all actions
408 * or prepare the view in another way before the action is called.
409 *
410 * @param Tx_Extbase_MVC_View_ViewInterface $view The view to be initialized
411 * @return void
412 * @api
413 */
414 protected function initializeView(Tx_Extbase_MVC_View_ViewInterface $view) {
415 }
416
417 /**
418 * Initializes the controller before invoking an action method.
419 *
420 * Override this method to solve tasks which all actions have in
421 * common.
422 *
423 * @return void
424 * @api
425 */
426 protected function initializeAction() {
427 }
428
429 /**
430 * A special action which is called if the originally intended action could
431 * not be called, for example if the arguments were not valid.
432 *
433 * The default implementation sets a flash message, request errors and forwards back
434 * to the originating action. This is suitable for most actions dealing with form input.
435 *
436 * We clear the page cache by default on an error as well, as we need to make sure the
437 * data is re-evaluated when the user changes something.
438 *
439 * @return string
440 * @api
441 */
442 protected function errorAction() {
443 $this->clearCacheOnError();
444
445 if ($this->configurationManager->isFeatureEnabled('rewrittenPropertyMapper')) {
446 $errorFlashMessage = $this->getErrorFlashMessage();
447 if ($errorFlashMessage !== FALSE) {
448 $this->flashMessageContainer->add($errorFlashMessage, '', t3lib_FlashMessage::ERROR);
449 }
450
451 $referringRequest = $this->request->getReferringRequest();
452 if ($referringRequest !== NULL) {
453 $originalRequest = clone $this->request;
454 $this->request->setOriginalRequest($originalRequest);
455 $this->request->setOriginalRequestMappingResults($this->arguments->getValidationResults());
456
457 $this->forward($referringRequest->getControllerActionName(), $referringRequest->getControllerName(), $referringRequest->getControllerExtensionName(), $referringRequest->getArguments());
458 }
459
460 $message = 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName . '().' . PHP_EOL;
461 foreach ($this->arguments->getValidationResults()->getFlattenedErrors() as $propertyPath => $errors) {
462 foreach ($errors as $error) {
463 $message .= 'Error for ' . $propertyPath . ': ' . $error->getMessage() . PHP_EOL;
464 }
465 }
466
467 return $message;
468 } else {
469 // @deprecated since Extbase 1.4.0, will be removed in Extbase 1.6.0.
470 $this->request->setErrors($this->argumentsMappingResults->getErrors());
471
472 $errorFlashMessage = $this->getErrorFlashMessage();
473 if ($errorFlashMessage !== FALSE) {
474 $this->flashMessageContainer->add($errorFlashMessage, '', t3lib_FlashMessage::ERROR);
475 }
476
477 $referrer = $this->request->getInternalArgument('__referrer');
478 if ($referrer !== NULL) {
479 $this->forward($referrer['actionName'], $referrer['controllerName'], $referrer['extensionName'], $this->request->getArguments());
480 }
481
482 $message = 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName . '().' . PHP_EOL;
483 foreach ($this->argumentsMappingResults->getErrors() as $error) {
484 $message .= 'Error: ' . $error->getMessage() . PHP_EOL;
485 }
486 foreach ($this->argumentsMappingResults->getWarnings() as $warning) {
487 $message .= 'Warning: ' . $warning->getMessage() . PHP_EOL;
488 }
489 return $message;
490 }
491 }
492
493 /**
494 * A template method for displaying custom error flash messages, or to
495 * display no flash message at all on errors. Override this to customize
496 * the flash message in your action controller.
497 *
498 * @return string|boolean The flash message or FALSE if no flash message should be set
499 * @api
500 */
501 protected function getErrorFlashMessage() {
502 return 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName . '()';
503 }
504
505 /**
506 * Checks the request hash (HMAC), if arguments have been touched by the property mapper.
507 *
508 * In case the @dontverifyrequesthash-Annotation has been set, this suppresses the exception.
509 *
510 * @return void
511 * @throws Tx_Extbase_MVC_Exception_InvalidOrNoRequestHash In case request hash checking failed
512 * @author Sebastian Kurf├╝rst <sebastian@typo3.org>
513 * @deprecated since Extbase 1.4.0, will be removed in Extbase 1.6.0.
514 */
515 protected function checkRequestHash() {
516 if ($this->configurationManager->isFeatureEnabled('rewrittenPropertyMapper')) {
517 // If the new property mapper is enabled, the request hash is not needed anymore.
518 return;
519 }
520 if (!($this->request instanceof Tx_Extbase_MVC_Web_Request)) return; // We only want to check it for now for web requests.
521 if ($this->request->isHmacVerified()) return; // all good
522
523 $verificationNeeded = FALSE;
524 foreach ($this->arguments as $argument) {
525 if ($argument->getOrigin() == Tx_Extbase_MVC_Controller_Argument::ORIGIN_NEWLY_CREATED
526 || $argument->getOrigin() == Tx_Extbase_MVC_Controller_Argument::ORIGIN_PERSISTENCE_AND_MODIFIED) {
527 $verificationNeeded = TRUE;
528 }
529 }
530 if ($verificationNeeded) {
531 $methodTagsValues = $this->reflectionService->getMethodTagsValues(get_class($this), $this->actionMethodName);
532 if (!isset($methodTagsValues['dontverifyrequesthash'])) {
533 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);
534 }
535 }
536 }
537
538 /**
539 * Clear cache of current page on error. Needed because we want a re-evaluation of the data.
540 * Better would be just do delete the cache for the error action, but that is not possible right now.
541 *
542 * @return void
543 */
544 protected function clearCacheOnError() {
545 $extbaseSettings = $this->configurationManager->getConfiguration(Tx_Extbase_Configuration_ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
546 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
547 if (isset($GLOBALS['TSFE'])) {
548 $pageUid = $GLOBALS['TSFE']->id;
549 $this->cacheService->clearPageCache(array($pageUid));
550 }
551 }
552 }
553
554 }
555 ?>