[FEATURE] Fluid (TemplateView): Made templateRootPath configurable via TypoScript...
[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 */
35 class Tx_Extbase_MVC_Controller_ActionController extends Tx_Extbase_MVC_Controller_AbstractController {
36
37 /**
38 * @var Tx_Extbase_Reflection_Service
39 */
40 protected $reflectionService;
41
42 /**
43 * By default a Fluid TemplateView is provided, if a template is available,
44 * then a view with the same name as the current action will be looked up.
45 * If none is available the $defaultViewObjectName will be used and finally
46 * an EmptyView will be created.
47 * @var Tx_Extbase_MVC_View_ViewInterface
48 * @api
49 */
50 protected $view = NULL;
51
52 /**
53 * Pattern after which the view object name is built if no Fluid template
54 * is found.
55 * @var string
56 * @api
57 */
58 protected $viewObjectNamePattern = 'Tx_@extension_View_@controller_@action@format';
59
60 /**
61 * The default view object to use if neither a Fluid template nor an action
62 * specific view object could be found.
63 * @var string
64 * @api
65 */
66 protected $defaultViewObjectName = NULL;
67
68 /**
69 * Name of the action method
70 * @var string
71 * @api
72 */
73 protected $actionMethodName = 'indexAction';
74
75 /**
76 * Name of the special error action method which is called in case of errors
77 * @var string
78 * @api
79 */
80 protected $errorMethodName = 'errorAction';
81
82 /**
83 * Injects the reflection service
84 *
85 * @param Tx_Extbase_Reflection_Service $reflectionService
86 * @return void
87 */
88 public function injectReflectionService(Tx_Extbase_Reflection_Service $reflectionService) {
89 $this->reflectionService = $reflectionService;
90 }
91
92 /**
93 * Checks if the current request type is supported by the controller.
94 *
95 * If your controller only supports certain request types, either
96 * replace / modify the supporteRequestTypes property or override this
97 * method.
98 *
99 * @param Tx_Extbase_MVC_Request $request The current request
100 * @return boolean TRUE if this request type is supported, otherwise FALSE
101 */
102 public function canProcessRequest(Tx_Extbase_MVC_Request $request) {
103 return parent::canProcessRequest($request);
104
105 }
106
107 /**
108 * Handles a request. The result output is returned by altering the given response.
109 *
110 * @param Tx_Extbase_MVC_Request $request The request object
111 * @param Tx_Extbase_MVC_Response $response The response, modified by this handler
112 * @return void
113 */
114 public function processRequest(Tx_Extbase_MVC_Request $request, Tx_Extbase_MVC_Response $response) {
115 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);
116
117 $this->request = $request;
118 $this->request->setDispatched(TRUE);
119 $this->response = $response;
120
121 $this->URIBuilder = t3lib_div::makeInstance('Tx_Extbase_MVC_Web_Routing_URIBuilder');
122 $this->URIBuilder->setRequest($request);
123
124 $this->actionMethodName = $this->resolveActionMethodName();
125
126 $this->initializeActionMethodArguments();
127 $this->initializeControllerArgumentsBaseValidators();
128 $this->initializeActionMethodValidators();
129
130 $this->initializeAction();
131 $actionInitializationMethodName = 'initialize' . ucfirst($this->actionMethodName);
132 if (method_exists($this, $actionInitializationMethodName)) {
133 call_user_func(array($this, $actionInitializationMethodName));
134 }
135
136 $this->mapRequestArgumentsToControllerArguments();
137 $this->view = $this->resolveView();
138 if ($this->view !== NULL) $this->initializeView($this->view);
139 $this->callActionMethod();
140 }
141
142 /**
143 * Implementation of the arguments initilization in the action controller:
144 * Automatically registers arguments of the current action
145 *
146 * Don't override this method - use initializeAction() instead.
147 *
148 * @return void
149 * @see initializeArguments()
150 */
151 protected function initializeActionMethodArguments() {
152 $methodParameters = $this->reflectionService->getMethodParameters(get_class($this), $this->actionMethodName);
153 foreach ($methodParameters as $parameterName => $parameterInfo) {
154 $dataType = 'Text';
155 if (isset($parameterInfo['type'])) {
156 $dataType = $parameterInfo['type'];
157 } elseif ($parameterInfo['array']) {
158 $dataType = 'array';
159 }
160 $defaultValue = (isset($parameterInfo['defaultValue']) ? $parameterInfo['defaultValue'] : NULL);
161
162 $this->arguments->addNewArgument($parameterName, $dataType, ($parameterInfo['optional'] === FALSE), $defaultValue);
163 }
164 }
165
166 /**
167 * Detects and registers any additional validators for arguments which were
168 * specified in the @validate annotations of an action method
169 *
170 * @return void
171 */
172 protected function initializeActionMethodValidators() {
173 $validatorConjunctions = $this->validatorResolver->buildMethodArgumentsValidatorConjunctions(get_class($this), $this->actionMethodName);
174 foreach ($validatorConjunctions as $argumentName => $validatorConjunction) {
175 if (!isset($this->arguments[$argumentName])) throw new Tx_Extbase_MVC_Exception_NoSuchArgument('Found custom validation rule for non existing argument "' . $argumentName . '" in ' . get_class($this) . '->' . $this->actionMethodName . '().', 1239853108);
176 $argument = $this->arguments[$argumentName];
177 $existingValidator = $argument->getValidator();
178 if ($existingValidator !== NULL) {
179 $validatorConjunction->addValidator($existingValidator);
180 }
181 $argument->setValidator($validatorConjunction);
182 }
183
184 $this->evaluateDontValidateAnnotations();
185 }
186
187 /**
188 * Parses @dontvalidate annotations of an action method an disables validation for
189 * the specified arguments.
190 *
191 * @return void
192 */
193 protected function evaluateDontValidateAnnotations() {
194 $methodTagsValues = $this->reflectionService->getMethodTagsValues(get_class($this), $this->actionMethodName);
195 if (isset($methodTagsValues['dontvalidate'])) {
196 foreach ($methodTagsValues['dontvalidate'] as $dontValidateValue) {
197 $argumentName = substr($dontValidateValue, 1);
198 if (!isset($this->arguments[$argumentName])) throw new Tx_Extbase_MVC_Exception_NoSuchArgument('Found @dontvalidate annotation for non existing argument "$' . $argumentName . '" in ' . get_class($this) . '->' . $this->actionMethodName . '().', 1249484908);
199 $this->arguments[$argumentName]->disableValidation();
200 }
201 }
202 }
203
204 /**
205 * Determines the action method and assures that the method exists.
206 *
207 * @return string The action method name
208 * @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).
209 */
210 protected function resolveActionMethodName() {
211 $actionMethodName = $this->request->getControllerActionName() . 'Action';
212 if (!method_exists($this, $actionMethodName)) throw new Tx_Extbase_MVC_Exception_NoSuchAction('An action "' . $actionMethodName . '" does not exist in controller "' . get_class($this) . '".', 1186669086);
213 return $actionMethodName;
214 }
215
216 /**
217 * Calls the specified action method and passes the arguments.
218 *
219 * If the action returns a string, it is appended to the content in the
220 * response object. If the action doesn't return anything and a valid
221 * view exists, the view is rendered automatically.
222 *
223 * @param string $actionMethodName Name of the action method to call
224 * @return void
225 * @api
226 */
227 protected function callActionMethod() {
228 $argumentsAreValid = TRUE;
229 $preparedArguments = array();
230 foreach ($this->arguments as $argument) {
231 $preparedArguments[] = $argument->getValue();
232 }
233
234 if ($this->argumentsMappingResults->hasErrors()) {
235 $actionResult = call_user_func(array($this, $this->errorMethodName));
236 } else {
237 $actionResult = call_user_func_array(array($this, $this->actionMethodName), $preparedArguments);
238 }
239 if ($actionResult === NULL && $this->view instanceof Tx_Extbase_MVC_View_ViewInterface) {
240 $this->response->appendContent($this->view->render());
241 } elseif (is_string($actionResult) && strlen($actionResult) > 0) {
242 $this->response->appendContent($actionResult);
243 }
244 }
245
246 /**
247 * Prepares a view for the current action and stores it in $this->view.
248 * By default, this method tries to locate a view with a name matching
249 * the current action.
250 *
251 * @return void
252 * @api
253 */
254 protected function resolveView() {
255 $view = $this->objectManager->getObject('Tx_Fluid_View_TemplateView');
256 $controllerContext = $this->buildControllerContext();
257 $view->setControllerContext($controllerContext);
258
259 // Template Path Override
260 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
261 if (isset($extbaseFrameworkConfiguration['view']['templateRootPath']) && $extbaseFrameworkConfiguration['view']['templateRootPath']) {
262 $view->setTemplateRootPath($extbaseFrameworkConfiguration['view']['templateRootPath']);
263 }
264
265 if ($view->hasTemplate() === FALSE) {
266 $viewObjectName = $this->resolveViewObjectName();
267 if (class_exists($viewObjectName) === FALSE) $viewObjectName = 'Tx_Extbase_MVC_View_EmptyView';
268 $view = $this->objectManager->getObject($viewObjectName);
269 $view->setControllerContext($controllerContext);
270 }
271 if (method_exists($view, 'injectSettings')) {
272 $view->injectSettings($this->settings);
273 }
274 $view->initializeView(); // In FLOW3, solved through Object Lifecycle methods, we need to call it explicitely.
275 // $view->assign('flashMessages', $this->popFlashMessages());
276 return $view;
277 }
278
279 /**
280 * Determines the fully qualified view object name.
281 *
282 * @return mixed The fully qualified view object name or FALSE if no matching view could be found.
283 * @api
284 */
285 protected function resolveViewObjectName() {
286 $possibleViewName = $this->viewObjectNamePattern;
287 $extensionName = $this->request->getControllerExtensionName();
288 $subextensionName = $this->request->getControllerSubextensionName();
289 if ($subextensionName !== NULL && $subextensionName !== '') {
290 $extensionName.= '_' . $subextensionName;
291 }
292 $possibleViewName = str_replace('@extension', $extensionName, $possibleViewName);
293 $possibleViewName = str_replace('@controller', $this->request->getControllerName(), $possibleViewName);
294 $possibleViewName = str_replace('@action', ucfirst($this->request->getControllerActionName()), $possibleViewName);
295
296 $viewObjectName = str_replace('@format', ucfirst($this->request->getFormat()), $possibleViewName);
297 if (class_exists($viewObjectName) === FALSE) {
298 $viewObjectName = str_replace('@format', '', $possibleViewName);
299 }
300 if (class_exists($viewObjectName) === FALSE && $this->defaultViewObjectName !== NULL) {
301 $viewObjectName = $this->defaultViewObjectName;
302 }
303 return $viewObjectName;
304 }
305
306 /**
307 * Initializes the view before invoking an action method.
308 *
309 * Override this method to solve assign variables common for all actions
310 * or prepare the view in another way before the action is called.
311 *
312 * @param Tx_Extbase_View_ViewInterface $view The view to be initialized
313 * @return void
314 * @api
315 */
316 protected function initializeView(Tx_Extbase_MVC_View_ViewInterface $view) {
317 }
318
319 /**
320 * Initializes the controller before invoking an action method.
321 *
322 * Override this method to solve tasks which all actions have in
323 * common.
324 *
325 * @return void
326 * @api
327 */
328 protected function initializeAction() {
329 }
330
331 /**
332 * A special action which is called if the originally intended action could
333 * not be called, for example if the arguments were not valid.
334 *
335 * The default implementation sets a flash message, request errors and forwards back
336 * to the originating action. This is suitable for most actions dealing with form input.
337 *
338 * We clear the page cache by default on an error as well, as we need to make sure the
339 * data is re-evaluated when the user changes something.
340 *
341 * @return string
342 * @api
343 */
344 protected function errorAction() {
345 $this->request->setErrors($this->argumentsMappingResults->getErrors());
346 $this->clearCacheOnError();
347
348 if ($this->request->hasArgument('__referrer')) {
349 $referrer = $this->request->getArgument('__referrer');
350 $this->forward($referrer['actionName'], $referrer['controllerName'], $referrer['extensionName'], $this->request->getArguments());
351 }
352
353 $message = 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName . '().' . PHP_EOL;
354 foreach ($this->argumentsMappingResults->getErrors() as $error) {
355 $message .= 'Error: ' . $error->getMessage() . PHP_EOL;
356 }
357 foreach ($this->argumentsMappingResults->getWarnings() as $warning) {
358 $message .= 'Warning: ' . $warning->getMessage() . PHP_EOL;
359 }
360 return $message;
361 }
362
363 /**
364 * Clear cache of current page on error. Needed because we want a re-evaluation of the data.
365 * Better would be just do delete the cache for the error action, but that is not possible right now.
366 *
367 * @return void
368 */
369 protected function clearCacheOnError() {
370 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
371 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
372 if (isset($GLOBALS['TSFE'])) {
373 $pageUid = $GLOBALS['TSFE']->id;
374 Tx_Extbase_Utility_Cache::clearPageCache(array($pageUid));
375 }
376 }
377 }
378
379 }
380 ?>