d0b6bdfe4adb58dcf8e6f4c59709e0b023ad3c2f
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Dispatcher.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 *
17 * This script is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * This copyright notice MUST APPEAR in all copies of the script!
23 ***************************************************************/
24
25 /**
26 * Creates a request an dispatches it to the controller which was specified
27 * by TS Setup, Flexform and returns the content to the v4 framework.
28 *
29 * This class is the main entry point for extbase extensions.
30 *
31 * @package Extbase
32 * @version $ID:$
33 */
34 class Tx_Extbase_Dispatcher {
35
36 /**
37 * Back reference to the parent content object
38 * This has to be public as it is set directly from TYPO3
39 *
40 * @var tslib_cObj
41 */
42 public $cObj;
43
44 /**
45 * @var Tx_Extbase_Utility_ClassLoader
46 */
47 protected $classLoader;
48
49 /**
50 * @var Tx_Extbase_Configuration_AbstractConfigurationManager
51 */
52 protected static $configurationManager;
53
54 /**
55 * @var t3lib_cache_Manager
56 */
57 protected $cacheManager;
58
59 /**
60 * @var Tx_Extbase_Reflection_Service
61 */
62 protected static $reflectionService;
63
64 /**
65 * @var Tx_Extbase_Persistence_Manager
66 */
67 protected static $persistenceManager;
68
69 /**
70 * The configuration for the Extbase framework
71 * @var array
72 */
73 protected static $extbaseFrameworkConfiguration;
74
75
76 /**
77 * Constructs this Dispatcher and registers the autoloader
78 */
79 public function __construct() {
80 t3lib_cache::initializeCachingFramework();
81 $this->initializeClassLoader();
82 $this->initializeCache();
83 $this->initializeReflection();
84 }
85
86 /**
87 * Creates a request an dispatches it to a controller.
88 *
89 * @param string $content The content
90 * @param array $configuration The TS configuration array
91 * @return string $content The processed content
92 */
93 public function dispatch($content, $configuration) {
94 // FIXME Remove the next lines. These are only there to generate the ext_autoload.php file
95 //$extutil = new Tx_Extbase_Utility_Extension;
96 //$extutil->createAutoloadRegistryForExtension('extbase', t3lib_extMgm::extPath('extbase'));
97 //$extutil->createAutoloadRegistryForExtension('fluid', t3lib_extMgm::extPath('fluid'));
98
99 $this->timeTrackPush('Extbase is called.','');
100 $this->timeTrackPush('Extbase gets initialized.','');
101
102 if (!is_array($configuration)) {
103 t3lib_div::sysLog('Extbase was not able to dispatch the request. No configuration.', 'extbase', t3lib_div::SYSLOG_SEVERITY_ERROR);
104 return $content;
105 }
106 $this->initializeConfigurationManagerAndFrameworkConfiguration($configuration);
107
108 $requestBuilder = t3lib_div::makeInstance('Tx_Extbase_MVC_Web_RequestBuilder');
109 $request = $requestBuilder->initialize(self::$extbaseFrameworkConfiguration);
110 $request = $requestBuilder->build();
111 if (isset($this->cObj->data) && is_array($this->cObj->data)) {
112 // we need to check the above conditions as cObj is not available in Backend.
113 $request->setContentObjectData($this->cObj->data);
114 }
115 $response = t3lib_div::makeInstance('Tx_Extbase_MVC_Web_Response');
116
117 // Request hash service
118 $requestHashService = t3lib_div::makeInstance('Tx_Extbase_Security_Channel_RequestHashService'); // singleton
119 $requestHashService->verifyRequest($request);
120
121 $persistenceManager = self::getPersistenceManager();
122
123 $this->timeTrackPull();
124
125 $this->timeTrackPush('Extbase dispatches request.','');
126 $dispatchLoopCount = 0;
127 while (!$request->isDispatched()) {
128 if ($dispatchLoopCount++ > 99) throw new Tx_Extbase_MVC_Exception_InfiniteLoop('Could not ultimately dispatch the request after ' . $dispatchLoopCount . ' iterations.', 1217839467);
129 $controller = $this->getPreparedController($request);
130 try {
131 $controller->processRequest($request, $response);
132 } catch (Tx_Extbase_MVC_Exception_StopAction $ignoredException) {
133 }
134 }
135 $this->timeTrackPull();
136
137 $this->timeTrackPush('Extbase persists all changes.','');
138 $flashMessages = t3lib_div::makeInstance('Tx_Extbase_MVC_Controller_FlashMessages'); // singleton
139 $flashMessages->persist();
140 $persistenceManager->persistAll();
141 $this->timeTrackPull();
142
143 self::$reflectionService->shutdown();
144
145 if (substr($response->getStatus(), 0, 3) === '303') {
146 $response->sendHeaders();
147 exit;
148 }
149
150 if (count($response->getAdditionalHeaderData()) > 0) {
151 $GLOBALS['TSFE']->additionalHeaderData[$request->getControllerExtensionName()] = implode("\n", $response->getAdditionalHeaderData());
152 }
153 $this->timeTrackPull();
154 return $response->getContent();
155 }
156
157 /**
158 * Initializes the autoload mechanism of Extbase. This is supplement to the core autoloader.
159 *
160 * @return void
161 */
162 protected function initializeClassLoader() {
163 if (!class_exists('Tx_Extbase_Utility_ClassLoader')) {
164 require(t3lib_extmgm::extPath('extbase') . 'Classes/Utility/ClassLoader.php');
165 }
166
167 $classLoader = new Tx_Extbase_Utility_ClassLoader();
168 spl_autoload_register(array($classLoader, 'loadClass'));
169 }
170
171 /**
172 * Initializes the configuration manager and the Extbase settings
173 *
174 * @param $configuration The current incoming configuration
175 * @return void
176 */
177 protected function initializeConfigurationManagerAndFrameworkConfiguration($configuration) {
178 if (TYPO3_MODE === 'FE') {
179 self::$configurationManager = t3lib_div::makeInstance('Tx_Extbase_Configuration_FrontendConfigurationManager');
180 self::$configurationManager->setContentObject($this->cObj);
181 } else {
182 self::$configurationManager = t3lib_div::makeInstance('Tx_Extbase_Configuration_BackendConfigurationManager');
183 }
184 self::$extbaseFrameworkConfiguration = self::$configurationManager->getFrameworkConfiguration($configuration);
185 }
186
187 /**
188 * Initializes the cache framework
189 *
190 * @return void
191 */
192 protected function initializeCache() {
193 $this->cacheManager = $GLOBALS['typo3CacheManager'];
194 try {
195 $this->cacheManager->getCache('cache_extbase_reflection');
196 } catch (t3lib_cache_exception_NoSuchCache $exception) {
197 $GLOBALS['typo3CacheFactory']->create(
198 'cache_extbase_reflection',
199 't3lib_cache_frontend_VariableFrontend',
200 $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_extbase_reflection']['backend'],
201 $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_extbase_reflection']['options']
202 );
203 }
204 }
205
206 /**
207 * Initializes the Reflection Service
208 *
209 * @return void
210 */
211 protected function initializeReflection() {
212 self::$reflectionService = t3lib_div::makeInstance('Tx_Extbase_Reflection_Service');
213 self::$reflectionService->setCache($this->cacheManager->getCache('cache_extbase_reflection'));
214 if (!self::$reflectionService->isInitialized()) {
215 self::$reflectionService->initialize();
216 }
217 }
218
219 /**
220 * Builds and returns a controller
221 *
222 * @param Tx_Extbase_MVC_Web_Request $request
223 * @return Tx_Extbase_MVC_Controller_ControllerInterface The prepared controller
224 */
225 protected function getPreparedController(Tx_Extbase_MVC_Web_Request $request) {
226 $controllerObjectName = $request->getControllerObjectName();
227 $controller = t3lib_div::makeInstance($controllerObjectName);
228 if (!$controller instanceof Tx_Extbase_MVC_Controller_ControllerInterface) {
229 throw new Tx_Extbase_MVC_Exception_InvalidController('Invalid controller "' . $request->getControllerObjectName() . '". The controller must implement the Tx_Extbase_MVC_Controller_ControllerInterface.', 1202921619);
230 }
231 $propertyMapper = t3lib_div::makeInstance('Tx_Extbase_Property_Mapper');
232 $propertyMapper->injectReflectionService(self::$reflectionService);
233 $controller->injectPropertyMapper($propertyMapper);
234
235 $controller->injectSettings(!empty(self::$extbaseFrameworkConfiguration['settings']) ? self::$extbaseFrameworkConfiguration['settings'] : array());
236
237 $flashMessages = t3lib_div::makeInstance('Tx_Extbase_MVC_Controller_FlashMessages'); // singleton
238 $flashMessages->reset();
239 $controller->injectFlashMessages($flashMessages);
240
241 $objectManager = t3lib_div::makeInstance('Tx_Extbase_Object_Manager');
242 $validatorResolver = t3lib_div::makeInstance('Tx_Extbase_Validation_ValidatorResolver');
243 $validatorResolver->injectObjectManager($objectManager);
244 $validatorResolver->injectReflectionService(self::$reflectionService);
245 $controller->injectValidatorResolver($validatorResolver);
246 $controller->injectReflectionService(self::$reflectionService);
247 $controller->injectObjectManager($objectManager);
248 return $controller;
249 }
250
251 /**
252 * This function prepares and returns the Persistance Manager
253 *
254 * @return Tx_Extbase_Persistence_Manager A (singleton) instance of the Persistence Manager
255 */
256 public static function getPersistenceManager() {
257 if (self::$persistenceManager === NULL) {
258 $identityMap = t3lib_div::makeInstance('Tx_Extbase_Persistence_IdentityMap');
259 $persistenceSession = t3lib_div::makeInstance('Tx_Extbase_Persistence_Session'); // singleton
260
261 $dataMapper = t3lib_div::makeInstance('Tx_Extbase_Persistence_Mapper_DataMapper'); // singleton
262 $dataMapper->injectIdentityMap($identityMap);
263 $dataMapper->injectSession($persistenceSession);
264 $dataMapper->injectReflectionService(self::$reflectionService);
265
266 $storageBackend = t3lib_div::makeInstance('Tx_Extbase_Persistence_Storage_Typo3DbBackend', $GLOBALS['TYPO3_DB']); // singleton
267 $storageBackend->injectDataMapper($dataMapper);
268
269 $qomFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QOM_QueryObjectModelFactory', $storageBackend);
270
271 $dataMapper->setQomFactory($qomFactory);
272
273 $persistenceBackend = t3lib_div::makeInstance('Tx_Extbase_Persistence_Backend', $persistenceSession, $storageBackend); // singleton
274 $persistenceBackend->injectDataMapper($dataMapper);
275 $persistenceBackend->injectIdentityMap($identityMap);
276 $persistenceBackend->injectReflectionService(self::$reflectionService);
277 $persistenceBackend->injectQueryFactory(t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory'));
278 $persistenceBackend->injectQomFactory($qomFactory);
279 $persistenceBackend->injectValueFactory(t3lib_div::makeInstance('Tx_Extbase_Persistence_ValueFactory'));
280
281 $objectManager = t3lib_div::makeInstance('Tx_Extbase_Object_Manager'); // singleton
282
283 $persistenceManager = t3lib_div::makeInstance('Tx_Extbase_Persistence_Manager'); // singleton
284 $persistenceManager->injectBackend($persistenceBackend);
285 $persistenceManager->injectSession($persistenceSession);
286 $persistenceManager->injectObjectManager($objectManager);
287
288 self::$persistenceManager = $persistenceManager;
289 }
290
291 return self::$persistenceManager;
292 }
293
294 /**
295 * This function returns the Configuration Manager. It is instanciated for
296 * each call to dispatch() only once.
297 *
298 * @return Tx_Extbase_Configuration_Manager An instance of the Configuration Manager
299 */
300 public static function getConfigurationManager() {
301 return self::$configurationManager;
302 }
303
304 /**
305 * This function returns the settings of Extbase
306 *
307 * @return array The settings
308 */
309 public static function getExtbaseFrameworkConfiguration() {
310 return self::$extbaseFrameworkConfiguration;
311 }
312
313 /**
314 * Calls an Extbase Backend module.
315 *
316 * @param string $module The name of the module
317 * @return void
318 */
319 public function callModule($module) {
320 if (isset($GLOBALS['TBE_MODULES'][$module])) {
321 $config = $GLOBALS['TBE_MODULES'][$module];
322
323 // Check permissions and exit if the user has no permission for entry
324 $GLOBALS['BE_USER']->modAccess($config, TRUE);
325 if (t3lib_div::_GP('id')) {
326 // Check page access
327 $id = t3lib_div::_GP('id');
328 $permClause = $GLOBALS['BE_USER']->getPagePermsClause(TRUE);
329 $access = is_array(t3lib_BEfunc::readPageAccess($id, $permClause));
330 if (!$access) {
331 t3lib_BEfunc::typo3PrintError('No Access', 'You don\'t have access to this page', 0);
332 }
333 }
334
335 // Resolve the controller/action to use
336 $controllerAction = $this->resolveControllerAction($module);
337
338 // As for SCbase modules, output of the controller/action pair should be echoed
339 echo $this->transfer($module, $controllerAction['controllerName'], $controllerAction['actionName']);
340 return TRUE;
341 } else {
342 return FALSE;
343 }
344 }
345
346 /**
347 * Resolves the controller and action to use for current call.
348 * This takes into account any function menu that has being called.
349 *
350 * @param string $module The name of the module
351 * @return array The controller/action pair to use for current call
352 */
353 protected function resolveControllerAction($module) {
354 $configuration = $GLOBALS['TBE_MODULES'][$module];
355 $fallbackControllerAction = $this->getFallbackControllerAction($configuration);
356
357 // Extract dispatcher settings from request
358 $argumentPrefix = strtolower('tx_' . $configuration['extensionName'] . '_' . $configuration['name']);
359 $dispatcherParameters = t3lib_div::_GPmerged($argumentPrefix);
360 $dispatcherControllerAction = $this->getDispatcherControllerAction($configuration, $dispatcherParameters);
361
362 // Extract module function settings from request
363 $moduleFunctionControllerAction = $this->getModuleFunctionControllerAction($module, $fallbackControllerAction['controllerName']);
364
365 // Dispatcher controller/action has precedence over default controller/action
366 $controllerAction = t3lib_div::array_merge_recursive_overrule($fallbackControllerAction, $dispatcherControllerAction, FALSE, FALSE);
367 // Module function controller/action has precedence
368 $controllerAction = t3lib_div::array_merge_recursive_overrule($controllerAction, $moduleFunctionControllerAction, FALSE, FALSE);
369
370 return $controllerAction;
371 }
372
373 /**
374 * Returns the fallback controller/action pair to be used when request does not contain
375 * any controller/action to be used or the provided parameters are not valid.
376 *
377 * @param array $configuration The module configuration
378 * @return array The controller/action pair
379 */
380 protected function getFallbackControllerAction($configuration) {
381 // Extract module settings from its registration in ext_tables.php
382 $controllers = array_keys($configuration['controllerActions']);
383 $defaultController = array_shift($controllers);
384 $actions = t3lib_div::trimExplode(',', $configuration['controllerActions'][$defaultController], TRUE);
385 $defaultAction = $actions[0];
386
387 return array(
388 'controllerName' => $defaultController,
389 'actionName' => $defaultAction,
390 );
391 }
392
393 /**
394 * Returns the controller/action pair that was specified by the request if it is valid,
395 * otherwise, will just return a blank controller/action pair meaning the default
396 * controller/action should be used instead.
397 *
398 * @param array $configuration The module configuration
399 * @param array $dispatcherParameters The dispatcher parameters
400 * @return array The controller/action pair
401 */
402 protected function getDispatcherControllerAction($configuration, $dispatcherParameters) {
403 $controllerAction = array(
404 'controllerName' => '',
405 'actionName' => '',
406 );
407
408 if (!isset($dispatcherParameters['controllerName'])) {
409 // Early return: should use fallback controller/action
410 return $controllerAction;
411 }
412
413 // Extract configured controllers from module's registration in ext_tables.php
414 $controllers = array_keys($configuration['controllerActions']);
415
416 $controller = $dispatcherParameters['controllerName'];
417 if (in_array($controller, $controllers)) {
418 // Update return value as selected controller is valid
419 $controllerAction['controllerName'] = $controller;
420 $actions = t3lib_div::trimExplode(',', $configuration['controllerActions'][$controller], TRUE);
421 if (isset($dispatcherParameters['actionName'])) {
422 // Extract configured actions for selected controllers
423 $action = $dispatcherParameters['actionName'];
424 if (in_array($action, $actions)) {
425 // Requested action is valid for selected controller
426 $controllerAction['actionName'] = $action;
427 } else {
428 // Use first action of selected controller as fallback action
429 $controllerAction['actionName'] = $actions[0];
430 }
431 } else {
432 // Use first action of selected controller as fallback action
433 $controllerAction['actionName'] = $actions[0];
434 }
435 }
436
437 return $controllerAction;
438 }
439
440 /**
441 * Returns the controller/action pair to use if a module function parameter is found
442 * in the request, otherwise, will just return a blank controller/action pair.
443 *
444 * @param string $module The name of the module
445 * @param string $defaultController The module's default controller
446 * @return array The controller/action pair
447 */
448 protected function getModuleFunctionControllerAction($module, $defaultController) {
449 $controllerAction = array(
450 'controllerName' => '',
451 'actionName' => '',
452 );
453
454 $set = t3lib_div::_GP('SET');
455 if (!$set) {
456 // Early return
457 return $controllerAction;
458 }
459
460 $moduleFunction = $set['function'];
461 $matches = array();
462 if (preg_match('/^(.*)->(.*)$/', $moduleFunction, $matches)) {
463 $controllerAction['controllerName'] = $matches[1];
464 $controllerAction['actionName'] = $matches[2];
465 } else {
466 // Support for external SCbase module function rendering
467 $functions = $GLOBALS['TBE_MODULES_EXT'][$module]['MOD_MENU']['function'];
468 if (isset($functions[$moduleFunction])) {
469 $controllerAction['controllerName'] = $defaultController;
470 $controllerAction['actionName'] = 'extObj';
471 }
472 }
473
474 return $controllerAction;
475 }
476
477 /**
478 * Transfers the request to an Extbase backend module, calling
479 * a given controller/action.
480 *
481 * @param string $module The name of the module
482 * @param string $controller The controller to use
483 * @param string $action The controller's action to execute
484 * @return string The module rendered view
485 */
486 protected function transfer($module, $controller, $action) {
487 $config = $GLOBALS['TBE_MODULES'][$module];
488
489 $extbaseConfiguration = array(
490 'userFunc' => 'tx_extbase_dispatcher->dispatch',
491 'pluginName' => $module,
492 'extensionName' => $config['extensionName'],
493 'controller' => $controller,
494 'action' => $action,
495 'switchableControllerActions.' => array(),
496 'settings' => '< module.tx_' . strtolower($config['extensionName']) . '.settings',
497 'persistence' => '< module.tx_' . strtolower($config['extensionName']) . '.persistence',
498 'view' => '< module.tx_' . strtolower($config['extensionName']) . '.view',
499 );
500
501 $i = 1;
502 foreach ($config['controllerActions'] as $controller => $actions) {
503 // Add an "extObj" action for the default controller to handle external
504 // SCbase modules which add function menu entries
505 if ($i == 1) {
506 $actions .= ',extObj';
507 }
508 $extbaseConfiguration['switchableControllerActions.'][$i++ . '.'] = array(
509 'controller' => $controller,
510 'actions' => $actions,
511 );
512 }
513
514 // BACK_PATH is the path from the typo3/ directory from within the
515 // directory containing the controller file. We are using mod.php dispatcher
516 // and thus we are already within typo3/ because we call typo3/mod.php
517 $GLOBALS['BACK_PATH'] = '';
518 return $this->dispatch('', $extbaseConfiguration);
519 }
520
521 /**
522 * Push some information to time tracking if in Frontend
523 *
524 * @param string $name
525 * @todo correct variable names
526 * @return void
527 */
528 protected function timeTrackPush($name, $param2) {
529 if (isset($GLOBALS['TT'])) {
530 $GLOBALS['TT']->push($name, $param2);
531 }
532 }
533
534 /**
535 * Time track pull
536 * @todo complete documentation of this method.
537 */
538 protected function timeTrackPull() {
539 if (isset($GLOBALS['TT'])) {
540 $GLOBALS['TT']->pull();
541 }
542 }
543
544 }
545 ?>