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