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