[-TASK] Extbase (Persistence): Removed unnecessary classes, code and empty interfaces.
[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
280 $objectManager = t3lib_div::makeInstance('Tx_Extbase_Object_Manager'); // singleton
281
282 $persistenceManager = t3lib_div::makeInstance('Tx_Extbase_Persistence_Manager'); // singleton
283 $persistenceManager->injectBackend($persistenceBackend);
284 $persistenceManager->injectSession($persistenceSession);
285 $persistenceManager->injectObjectManager($objectManager);
286
287 self::$persistenceManager = $persistenceManager;
288 }
289
290 return self::$persistenceManager;
291 }
292
293 /**
294 * This function returns the Configuration Manager. It is instanciated for
295 * each call to dispatch() only once.
296 *
297 * @return Tx_Extbase_Configuration_Manager An instance of the Configuration Manager
298 */
299 public static function getConfigurationManager() {
300 return self::$configurationManager;
301 }
302
303 /**
304 * This function returns the settings of Extbase
305 *
306 * @return array The settings
307 */
308 public static function getExtbaseFrameworkConfiguration() {
309 return self::$extbaseFrameworkConfiguration;
310 }
311
312 /**
313 * Calls an Extbase Backend module.
314 *
315 * @param string $module The name of the module
316 * @return void
317 */
318 public function callModule($module) {
319 if (isset($GLOBALS['TBE_MODULES'][$module])) {
320 $config = $GLOBALS['TBE_MODULES'][$module];
321
322 // Check permissions and exit if the user has no permission for entry
323 $GLOBALS['BE_USER']->modAccess($config, TRUE);
324 if (t3lib_div::_GP('id')) {
325 // Check page access
326 $id = t3lib_div::_GP('id');
327 $permClause = $GLOBALS['BE_USER']->getPagePermsClause(TRUE);
328 $access = is_array(t3lib_BEfunc::readPageAccess($id, $permClause));
329 if (!$access) {
330 t3lib_BEfunc::typo3PrintError('No Access', 'You don\'t have access to this page', 0);
331 }
332 }
333
334 // Resolve the controller/action to use
335 $controllerAction = $this->resolveControllerAction($module);
336
337 // As for SCbase modules, output of the controller/action pair should be echoed
338 echo $this->transfer($module, $controllerAction['controllerName'], $controllerAction['actionName']);
339 return TRUE;
340 } else {
341 return FALSE;
342 }
343 }
344
345 /**
346 * Resolves the controller and action to use for current call.
347 * This takes into account any function menu that has being called.
348 *
349 * @param string $module The name of the module
350 * @return array The controller/action pair to use for current call
351 */
352 protected function resolveControllerAction($module) {
353 $configuration = $GLOBALS['TBE_MODULES'][$module];
354 $fallbackControllerAction = $this->getFallbackControllerAction($configuration);
355
356 // Extract dispatcher settings from request
357 $argumentPrefix = strtolower('tx_' . $configuration['extensionName'] . '_' . $configuration['name']);
358 $dispatcherParameters = t3lib_div::_GPmerged($argumentPrefix);
359 $dispatcherControllerAction = $this->getDispatcherControllerAction($configuration, $dispatcherParameters);
360
361 // Extract module function settings from request
362 $moduleFunctionControllerAction = $this->getModuleFunctionControllerAction($module, $fallbackControllerAction['controllerName']);
363
364 // Dispatcher controller/action has precedence over default controller/action
365 $controllerAction = t3lib_div::array_merge_recursive_overrule($fallbackControllerAction, $dispatcherControllerAction, FALSE, FALSE);
366 // Module function controller/action has precedence
367 $controllerAction = t3lib_div::array_merge_recursive_overrule($controllerAction, $moduleFunctionControllerAction, FALSE, FALSE);
368
369 return $controllerAction;
370 }
371
372 /**
373 * Returns the fallback controller/action pair to be used when request does not contain
374 * any controller/action to be used or the provided parameters are not valid.
375 *
376 * @param array $configuration The module configuration
377 * @return array The controller/action pair
378 */
379 protected function getFallbackControllerAction($configuration) {
380 // Extract module settings from its registration in ext_tables.php
381 $controllers = array_keys($configuration['controllerActions']);
382 $defaultController = array_shift($controllers);
383 $actions = t3lib_div::trimExplode(',', $configuration['controllerActions'][$defaultController], TRUE);
384 $defaultAction = $actions[0];
385
386 return array(
387 'controllerName' => $defaultController,
388 'actionName' => $defaultAction,
389 );
390 }
391
392 /**
393 * Returns the controller/action pair that was specified by the request if it is valid,
394 * otherwise, will just return a blank controller/action pair meaning the default
395 * controller/action should be used instead.
396 *
397 * @param array $configuration The module configuration
398 * @param array $dispatcherParameters The dispatcher parameters
399 * @return array The controller/action pair
400 */
401 protected function getDispatcherControllerAction($configuration, $dispatcherParameters) {
402 $controllerAction = array(
403 'controllerName' => '',
404 'actionName' => '',
405 );
406
407 if (!isset($dispatcherParameters['controllerName'])) {
408 // Early return: should use fallback controller/action
409 return $controllerAction;
410 }
411
412 // Extract configured controllers from module's registration in ext_tables.php
413 $controllers = array_keys($configuration['controllerActions']);
414
415 $controller = $dispatcherParameters['controllerName'];
416 if (in_array($controller, $controllers)) {
417 // Update return value as selected controller is valid
418 $controllerAction['controllerName'] = $controller;
419 $actions = t3lib_div::trimExplode(',', $configuration['controllerActions'][$controller], TRUE);
420 if (isset($dispatcherParameters['actionName'])) {
421 // Extract configured actions for selected controllers
422 $action = $dispatcherParameters['actionName'];
423 if (in_array($action, $actions)) {
424 // Requested action is valid for selected controller
425 $controllerAction['actionName'] = $action;
426 } else {
427 // Use first action of selected controller as fallback action
428 $controllerAction['actionName'] = $actions[0];
429 }
430 } else {
431 // Use first action of selected controller as fallback action
432 $controllerAction['actionName'] = $actions[0];
433 }
434 }
435
436 return $controllerAction;
437 }
438
439 /**
440 * Returns the controller/action pair to use if a module function parameter is found
441 * in the request, otherwise, will just return a blank controller/action pair.
442 *
443 * @param string $module The name of the module
444 * @param string $defaultController The module's default controller
445 * @return array The controller/action pair
446 */
447 protected function getModuleFunctionControllerAction($module, $defaultController) {
448 $controllerAction = array(
449 'controllerName' => '',
450 'actionName' => '',
451 );
452
453 $set = t3lib_div::_GP('SET');
454 if (!$set) {
455 // Early return
456 return $controllerAction;
457 }
458
459 $moduleFunction = $set['function'];
460 $matches = array();
461 if (preg_match('/^(.*)->(.*)$/', $moduleFunction, $matches)) {
462 $controllerAction['controllerName'] = $matches[1];
463 $controllerAction['actionName'] = $matches[2];
464 } else {
465 // Support for external SCbase module function rendering
466 $functions = $GLOBALS['TBE_MODULES_EXT'][$module]['MOD_MENU']['function'];
467 if (isset($functions[$moduleFunction])) {
468 $controllerAction['controllerName'] = $defaultController;
469 $controllerAction['actionName'] = 'extObj';
470 }
471 }
472
473 return $controllerAction;
474 }
475
476 /**
477 * Transfers the request to an Extbase backend module, calling
478 * a given controller/action.
479 *
480 * @param string $module The name of the module
481 * @param string $controller The controller to use
482 * @param string $action The controller's action to execute
483 * @return string The module rendered view
484 */
485 protected function transfer($module, $controller, $action) {
486 $config = $GLOBALS['TBE_MODULES'][$module];
487
488 $extbaseConfiguration = array(
489 'userFunc' => 'tx_extbase_dispatcher->dispatch',
490 'pluginName' => $module,
491 'extensionName' => $config['extensionName'],
492 'controller' => $controller,
493 'action' => $action,
494 'switchableControllerActions.' => array(),
495 'settings' => '< module.tx_' . strtolower($config['extensionName']) . '.settings',
496 'persistence' => '< module.tx_' . strtolower($config['extensionName']) . '.persistence',
497 'view' => '< module.tx_' . strtolower($config['extensionName']) . '.view',
498 );
499
500 $i = 1;
501 foreach ($config['controllerActions'] as $controller => $actions) {
502 // Add an "extObj" action for the default controller to handle external
503 // SCbase modules which add function menu entries
504 if ($i == 1) {
505 $actions .= ',extObj';
506 }
507 $extbaseConfiguration['switchableControllerActions.'][$i++ . '.'] = array(
508 'controller' => $controller,
509 'actions' => $actions,
510 );
511 }
512
513 // BACK_PATH is the path from the typo3/ directory from within the
514 // directory containing the controller file. We are using mod.php dispatcher
515 // and thus we are already within typo3/ because we call typo3/mod.php
516 $GLOBALS['BACK_PATH'] = '';
517 return $this->dispatch('', $extbaseConfiguration);
518 }
519
520 /**
521 * Push some information to time tracking if in Frontend
522 *
523 * @param string $name
524 * @todo correct variable names
525 * @return void
526 */
527 protected function timeTrackPush($name, $param2) {
528 if (isset($GLOBALS['TT'])) {
529 $GLOBALS['TT']->push($name, $param2);
530 }
531 }
532
533 /**
534 * Time track pull
535 * @todo complete documentation of this method.
536 */
537 protected function timeTrackPull() {
538 if (isset($GLOBALS['TT'])) {
539 $GLOBALS['TT']->pull();
540 }
541 }
542
543 }
544 ?>