2e03ec06f30a6c6fd7f5139d71340f1a14bab4f2
[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 if (!is_array($configuration)) {
100 t3lib_div::sysLog('Extbase was not able to dispatch the request. No configuration.', 'extbase', t3lib_div::SYSLOG_SEVERITY_ERROR);
101 return $content;
102 }
103 $this->initializeConfigurationManagerAndFrameworkConfiguration($configuration);
104
105 $requestBuilder = t3lib_div::makeInstance('Tx_Extbase_MVC_Web_RequestBuilder');
106 $request = $requestBuilder->initialize(self::$extbaseFrameworkConfiguration);
107 $request = $requestBuilder->build();
108 $request->setContentObjectData($this->cObj->data);
109 $response = t3lib_div::makeInstance('Tx_Extbase_MVC_Web_Response');
110
111 // Request hash service
112 $requestHashService = t3lib_div::makeInstance('Tx_Extbase_Security_Channel_RequestHashService'); // singleton
113 $requestHashService->verifyRequest($request);
114
115 $persistenceManager = self::getPersistenceManager();
116
117 $dispatchLoopCount = 0;
118 while (!$request->isDispatched()) {
119 if ($dispatchLoopCount++ > 99) throw new Tx_Extbase_MVC_Exception_InfiniteLoop('Could not ultimately dispatch the request after ' . $dispatchLoopCount . ' iterations.', 1217839467);
120 $controller = $this->getPreparedController($request);
121 try {
122 $controller->processRequest($request, $response);
123 } catch (Tx_Extbase_MVC_Exception_StopAction $ignoredException) {
124 }
125 }
126
127 $flashMessages = t3lib_div::makeInstance('Tx_Extbase_MVC_Controller_FlashMessages'); // singleton
128 $flashMessages->persist();
129
130 $persistenceManager->persistAll();
131 self::$reflectionService->shutdown();
132 if (count($response->getAdditionalHeaderData()) > 0) {
133 $GLOBALS['TSFE']->additionalHeaderData[$request->getControllerExtensionName()] = implode("\n", $response->getAdditionalHeaderData());
134 }
135 $response->sendHeaders();
136 return $response->getContent();
137 }
138
139 /**
140 * Initializes the autoload mechanism of Extbase. This is supplement to the core autoloader.
141 *
142 * @return void
143 */
144 protected function initializeClassLoader() {
145 if (!class_exists('Tx_Extbase_Utility_ClassLoader')) {
146 require(t3lib_extmgm::extPath('extbase') . 'Classes/Utility/ClassLoader.php');
147 }
148
149 $classLoader = new Tx_Extbase_Utility_ClassLoader();
150 spl_autoload_register(array($classLoader, 'loadClass'));
151 }
152
153 /**
154 * Initializes the configuration manager and the Extbase settings
155 *
156 * @param $configuration The current incoming configuration
157 * @return void
158 */
159 protected function initializeConfigurationManagerAndFrameworkConfiguration($configuration) {
160 self::$configurationManager = t3lib_div::makeInstance('Tx_Extbase_Configuration_FrontendConfigurationManager', $configurationSources);
161
162 if (TYPO3_MODE === 'FE') {
163 self::$configurationManager->setContentObject($this->cObj);
164 }
165 self::$extbaseFrameworkConfiguration = self::$configurationManager->getFrameworkConfiguration($configuration);
166 }
167
168 /**
169 * Initializes the cache framework
170 *
171 * @return void
172 */
173 protected function initializeCache() {
174 $this->cacheManager = $GLOBALS['typo3CacheManager'];
175 try {
176 $this->cacheManager->getCache('cache_extbase_reflection');
177 } catch (t3lib_cache_exception_NoSuchCache $exception) {
178 $GLOBALS['typo3CacheFactory']->create(
179 'cache_extbase_reflection',
180 't3lib_cache_frontend_VariableFrontend',
181 $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_extbase_reflection']['backend'],
182 $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_extbase_reflection']['options']
183 );
184 }
185 }
186
187 /**
188 * Initializes the Reflection Service
189 *
190 * @return void
191 */
192 protected function initializeReflection() {
193 self::$reflectionService = t3lib_div::makeInstance('Tx_Extbase_Reflection_Service');
194 self::$reflectionService->setCache($this->cacheManager->getCache('cache_extbase_reflection'));
195 if (!self::$reflectionService->isInitialized()) {
196 self::$reflectionService->initialize();
197 }
198 }
199
200 /**
201 * Builds and returns a controller
202 *
203 * @param Tx_Extbase_MVC_Web_Request $request
204 * @return Tx_Extbase_MVC_Controller_ControllerInterface The prepared controller
205 */
206 protected function getPreparedController(Tx_Extbase_MVC_Web_Request $request) {
207 $controllerObjectName = $request->getControllerObjectName();
208 $controller = t3lib_div::makeInstance($controllerObjectName);
209 if (!$controller instanceof Tx_Extbase_MVC_Controller_ControllerInterface) {
210 throw new Tx_Extbase_MVC_Exception_InvalidController('Invalid controller "' . $request->getControllerObjectName() . '". The controller must implement the Tx_Extbase_MVC_Controller_ControllerInterface.', 1202921619);
211 }
212 $propertyMapper = t3lib_div::makeInstance('Tx_Extbase_Property_Mapper');
213 $propertyMapper->injectReflectionService(self::$reflectionService);
214 $controller->injectPropertyMapper($propertyMapper);
215 $controller->injectSettings(self::$extbaseFrameworkConfiguration['settings']);
216
217 $flashMessages = t3lib_div::makeInstance('Tx_Extbase_MVC_Controller_FlashMessages'); // singleton
218 $flashMessages->reset();
219 $controller->injectFlashMessages($flashMessages);
220
221 $objectManager = t3lib_div::makeInstance('Tx_Extbase_Object_Manager');
222 $validatorResolver = t3lib_div::makeInstance('Tx_Extbase_Validation_ValidatorResolver');
223 $validatorResolver->injectObjectManager($objectManager);
224 $validatorResolver->injectReflectionService(self::$reflectionService);
225 $controller->injectValidatorResolver($validatorResolver);
226 $controller->injectReflectionService(self::$reflectionService);
227 $controller->injectObjectManager($objectManager);
228 return $controller;
229 }
230
231 /**
232 * This function prepares and returns the Persistance Manager
233 *
234 * @return Tx_Extbase_Persistence_Manager A (singleton) instance of the Persistence Manager
235 */
236 public static function getPersistenceManager() {
237 if (self::$persistenceManager === NULL) {
238 $dataMapper = t3lib_div::makeInstance('Tx_Extbase_Persistence_Mapper_DataMapper'); // singleton
239 $dataMapper->injectReflectionService(self::$reflectionService);
240
241 $storageBackend = t3lib_div::makeInstance('Tx_Extbase_Persistence_Storage_Typo3DbBackend', $GLOBALS['TYPO3_DB']); // singleton
242 $storageBackend->injectDataMapper($dataMapper);
243
244 $qomFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QOM_QueryObjectModelFactory', $storageBackend, $dataMapper);
245
246 $persistenceSession = t3lib_div::makeInstance('Tx_Extbase_Persistence_Session'); // singleton
247
248 $persistenceBackend = t3lib_div::makeInstance('Tx_Extbase_Persistence_Backend', $persistenceSession, $storageBackend); // singleton
249 $persistenceBackend->injectDataMapper($dataMapper);
250 $persistenceBackend->injectIdentityMap(t3lib_div::makeInstance('Tx_Extbase_Persistence_IdentityMap'));
251 $persistenceBackend->injectQueryFactory(t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory'));
252 $persistenceBackend->injectQOMFactory($qomFactory);
253 $persistenceBackend->injectValueFactory(t3lib_div::makeInstance('Tx_Extbase_Persistence_ValueFactory'));
254
255 $objectManager = t3lib_div::makeInstance('Tx_Extbase_Object_Manager'); // singleton
256
257 $persistenceManager = t3lib_div::makeInstance('Tx_Extbase_Persistence_Manager'); // singleton
258 $persistenceManager->injectBackend($persistenceBackend);
259 $persistenceManager->injectSession($persistenceSession);
260 $persistenceManager->injectObjectManager($objectManager);
261
262 self::$persistenceManager = $persistenceManager;
263 }
264
265 return self::$persistenceManager;
266 }
267
268 /**
269 * This function returns the Configuration Manager. It is instanciated for
270 * each call to dispatch() only once.
271 *
272 * @return Tx_Extbase_Configuration_Manager An instance of the Configuration Manager
273 */
274 public static function getConfigurationManager() {
275 return self::$configurationManager;
276 }
277
278 /**
279 * This function returns the settings of Extbase
280 *
281 * @return array The settings
282 */
283 public static function getExtbaseFrameworkConfiguration() {
284 return self::$extbaseFrameworkConfiguration;
285 }
286
287 /**
288 * Calls an Extbase Backend module.
289 *
290 * @param string $module The name of the module
291 * @return void
292 */
293 public function callModule($module) {
294 if (isset($GLOBALS['TBE_MODULES'][$module])) {
295 $config = $GLOBALS['TBE_MODULES'][$module];
296
297 // Check permissions and exit if the user has no permission for entry
298 $GLOBALS['BE_USER']->modAccess($config, TRUE);
299 if (t3lib_div::_GP('id')) {
300 // Check page access
301 $id = t3lib_div::_GP('id');
302 $permClause = $GLOBALS['BE_USER']->getPagePermsClause(TRUE);
303 $access = is_array(t3lib_BEfunc::readPageAccess($id, $permClause));
304 if (!$access) {
305 t3lib_BEfunc::typo3PrintError('No Access', 'You don\'t have access to this page', 0);
306 }
307 }
308
309 // Resolve the controller/action to use
310 $controllerAction = $this->resolveControllerAction($module);
311
312 // As for SCbase modules, output of the controller/action pair should be echoed
313 echo $this->transfer($module, $controllerAction['controllerName'], $controllerAction['actionName']);
314 return TRUE;
315 } else {
316 return FALSE;
317 }
318 }
319
320 /**
321 * Resolves the controller and action to use for current call.
322 * This takes into account any function menu that has being called.
323 *
324 * @param string $module The name of the module
325 * @return array The controller/action pair to use for current call
326 */
327 protected function resolveControllerAction($module) {
328 $configuration = $GLOBALS['TBE_MODULES'][$module];
329 $fallbackControllerAction = $this->getFallbackControllerAction($configuration);
330
331 // Extract dispatcher settings from request
332 $argumentPrefix = strtolower('tx_' . $configuration['extensionName'] . '_' . $configuration['name']);
333 $dispatcherParameters = t3lib_div::_GPmerged($argumentPrefix);
334 $dispatcherControllerAction = $this->getDispatcherControllerAction($configuration, $dispatcherParameters);
335
336 // Extract module function settings from request
337 $moduleFunctionControllerAction = $this->getModuleFunctionControllerAction($module, $fallbackControllerAction['controllerName']);
338
339 // Dispatcher controller/action has precedence over default controller/action
340 $controllerAction = t3lib_div::array_merge_recursive_overrule($fallbackControllerAction, $dispatcherControllerAction, FALSE, FALSE);
341 // Module function controller/action has precedence
342 $controllerAction = t3lib_div::array_merge_recursive_overrule($controllerAction, $moduleFunctionControllerAction, FALSE, FALSE);
343
344 return $controllerAction;
345 }
346
347 /**
348 * Returns the fallback controller/action pair to be used when request does not contain
349 * any controller/action to be used or the provided parameters are not valid.
350 *
351 * @param array $configuration The module configuration
352 * @return array The controller/action pair
353 */
354 protected function getFallbackControllerAction($configuration) {
355 // Extract module settings from its registration in ext_tables.php
356 $controllers = array_keys($configuration['controllerActions']);
357 $defaultController = array_shift($controllers);
358 $actions = t3lib_div::trimExplode(',', $configuration['controllerActions'][$defaultController], TRUE);
359 $defaultAction = $actions[0];
360
361 return array(
362 'controllerName' => $defaultController,
363 'actionName' => $defaultAction,
364 );
365 }
366
367 /**
368 * Returns the controller/action pair that was specified by the request if it is valid,
369 * otherwise, will just return a blank controller/action pair meaning the default
370 * controller/action should be used instead.
371 *
372 * @param array $configuration The module configuration
373 * @param array $dispatcherParameters The dispatcher parameters
374 * @return array The controller/action pair
375 */
376 protected function getDispatcherControllerAction($configuration, $dispatcherParameters) {
377 $controllerAction = array(
378 'controllerName' => '',
379 'actionName' => '',
380 );
381
382 if (!isset($dispatcherParameters['controllerName'])) {
383 // Early return: should use fallback controller/action
384 return $controllerAction;
385 }
386
387 // Extract configured controllers from module's registration in ext_tables.php
388 $controllers = array_keys($configuration['controllerActions']);
389
390 $controller = $dispatcherParameters['controllerName'];
391 if (in_array($controller, $controllers)) {
392 // Update return value as selected controller is valid
393 $controllerAction['controllerName'] = $controller;
394 $actions = t3lib_div::trimExplode(',', $configuration['controllerActions'][$controller], TRUE);
395 if (isset($dispatcherParameters['actionName'])) {
396 // Extract configured actions for selected controllers
397 $action = $dispatcherParameters['actionName'];
398 if (in_array($action, $actions)) {
399 // Requested action is valid for selected controller
400 $controllerAction['actionName'] = $action;
401 } else {
402 // Use first action of selected controller as fallback action
403 $controllerAction['actionName'] = $actions[0];
404 }
405 } else {
406 // Use first action of selected controller as fallback action
407 $controllerAction['actionName'] = $actions[0];
408 }
409 }
410
411 return $controllerAction;
412 }
413
414 /**
415 * Returns the controller/action pair to use if a module function parameter is found
416 * in the request, otherwise, will just return a blank controller/action pair.
417 *
418 * @param string $module The name of the module
419 * @param string $defaultController The module's default controller
420 * @return array The controller/action pair
421 */
422 protected function getModuleFunctionControllerAction($module, $defaultController) {
423 $controllerAction = array(
424 'controllerName' => '',
425 'actionName' => '',
426 );
427
428 $set = t3lib_div::_GP('SET');
429 if (!$set) {
430 // Early return
431 return $controllerAction;
432 }
433
434 $moduleFunction = $set['function'];
435 $matches = array();
436 if (preg_match('/^(.*)->(.*)$/', $moduleFunction, $matches)) {
437 $controllerAction['controllerName'] = $matches[1];
438 $controllerAction['actionName'] = $matches[2];
439 } else {
440 // Support for external SCbase module function rendering
441 $functions = $GLOBALS['TBE_MODULES_EXT'][$module]['MOD_MENU']['function'];
442 if (isset($functions[$moduleFunction])) {
443 $controllerAction['controllerName'] = $defaultController;
444 $controllerAction['actionName'] = 'extObj';
445 }
446 }
447
448 return $controllerAction;
449 }
450
451 /**
452 * Transfers the request to an Extbase backend module, calling
453 * a given controller/action.
454 *
455 * @param string $module The name of the module
456 * @param string $controller The controller to use
457 * @param string $action The controller's action to execute
458 * @return string The module rendered view
459 */
460 protected function transfer($module, $controller, $action) {
461 $config = $GLOBALS['TBE_MODULES'][$module];
462
463 $extbaseConfiguration = array(
464 'userFunc' => 'tx_extbase_dispatcher->dispatch',
465 'pluginName' => $module,
466 'extensionName' => $config['extensionName'],
467 'controller' => $controller,
468 'action' => $action,
469 'switchableControllerActions.' => array(),
470 'settings' => '< module.tx_' . strtolower($config['extensionName']) . '.settings',
471 'persistence' => '< module.tx_' . strtolower($config['extensionName']) . '.persistence',
472 'view' => '< module.tx_' . strtolower($config['extensionName']) . '.view',
473 );
474
475 $i = 1;
476 foreach ($config['controllerActions'] as $controller => $actions) {
477 // Add an "extObj" action for the default controller to handle external
478 // SCbase modules which add function menu entries
479 if ($i == 1) {
480 $actions .= ',extObj';
481 }
482 $extbaseConfiguration['switchableControllerActions.'][$i++ . '.'] = array(
483 'controller' => $controller,
484 'actions' => $actions,
485 );
486 }
487
488 // BACK_PATH is the path from the typo3/ directory from within the
489 // directory containing the controller file. We are using mod.php dispatcher
490 // and thus we are already within typo3/ because we call typo3/mod.php
491 $GLOBALS['BACK_PATH'] = '';
492 return $this->dispatch('', $extbaseConfiguration);
493 }
494
495 }
496 ?>