[BUGFIX] Make category TCA changes cacheable
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / ExtensionManagementUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the text file GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 /**
31 * Extension Management functions
32 *
33 * This class is never instantiated, rather the methods inside is called as functions like
34 * \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('my_extension');
35 *
36 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
37 */
38 class ExtensionManagementUtility {
39
40 static protected $extensionKeyMap;
41
42 /**
43 * TRUE, if ext_tables file was read from cache for this script run.
44 * The frontend tends to do that multiple times, but the caching framework does
45 * not allow this (via a require_once call). This variable is used to track
46 * the access to the cache file to read the single ext_tables.php if it was
47 * already read from cache
48 *
49 * @TODO : See if we can get rid of the 'load multiple times' scenario in fe
50 * @var boolean
51 */
52 static protected $extTablesWasReadFromCacheOnce = FALSE;
53
54 /**
55 * @var \TYPO3\CMS\Core\Package\PackageManager
56 */
57 static protected $packageManager;
58
59 /**
60 * Sets the package manager for all that backwards compatibility stuff,
61 * so it doesn't have to be fetched through the bootstap.
62 *
63 * @param \TYPO3\CMS\Core\Package\PackageManager $packageManager
64 * @internal
65 */
66 static public function setPackageManager(\TYPO3\CMS\Core\Package\PackageManager $packageManager) {
67 static::$packageManager = $packageManager;
68 }
69
70 /**
71 * @var \TYPO3\CMS\Core\Cache\CacheManager
72 */
73 static protected $cacheManager;
74
75 /**
76 * Getter for the cache manager
77 *
78 * @return \TYPO3\CMS\Core\Cache\CacheManager
79 */
80 static protected function getCacheManager() {
81 if (static::$cacheManager === NULL) {
82 static::$cacheManager = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager');
83 }
84 return static::$cacheManager;
85 }
86
87 /**
88 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
89 */
90 static protected $signalSlotDispatcher;
91
92 /**
93 * Getter for the signal slot dispatcher
94 *
95 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
96 */
97 static protected function getSignalSlotDispatcher() {
98 if (static::$signalSlotDispatcher === NULL) {
99 static::$signalSlotDispatcher = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\SignalSlot\\Dispatcher');
100 }
101 return static::$signalSlotDispatcher;
102 }
103
104 /**************************************
105 *
106 * PATHS and other evaluation
107 *
108 ***************************************/
109 /**
110 * Returns TRUE if the extension with extension key $key is loaded.
111 *
112 * @param string $key Extension key to test
113 * @param boolean $exitOnError If $exitOnError is TRUE and the extension is not loaded the function will die with an error message
114 * @return boolean
115 * @throws \BadFunctionCallException
116 */
117 static public function isLoaded($key, $exitOnError = FALSE) {
118 $isLoaded = static::$packageManager->isPackageActive($key);
119 if ($exitOnError && !$isLoaded) {
120 throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension "' . $key . '" is not loaded!', 1270853910);
121 }
122 return $isLoaded;
123 }
124
125 /**
126 * Returns the absolute path to the extension with extension key $key.
127 *
128 * @param $key string Extension key
129 * @param $script string $script is appended to the output if set.
130 * @throws \BadFunctionCallException
131 * @return string
132 */
133 static public function extPath($key, $script = '') {
134 if (!static::$packageManager->isPackageActive($key)) {
135 throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension key "' . $key . '" is NOT loaded!', 1365429656);
136 }
137 return static::$packageManager->getPackage($key)->getPackagePath() . $script;
138 }
139
140 /**
141 * Returns the relative path to the extension as measured from from the TYPO3_mainDir
142 * If the extension is not loaded the function will die with an error message
143 * Useful for images and links from backend
144 *
145 * @param string $key Extension key
146 *
147 * @throws \BadFunctionCallException
148 * @return string
149 */
150 static public function extRelPath($key) {
151 if (!static::$packageManager->isPackageActive($key)) {
152 throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension key "' . $key . '" is NOT loaded!', 1365429673);
153 }
154 $relativePathToSiteRoot = self::siteRelPath($key);
155 if (substr($relativePathToSiteRoot, 0, $typo3MainDirLength = strlen(TYPO3_mainDir)) === TYPO3_mainDir) {
156 $relativePathToSiteRoot = substr($relativePathToSiteRoot, $typo3MainDirLength);
157 } else {
158 $relativePathToSiteRoot = '../' . $relativePathToSiteRoot;
159 }
160 return $relativePathToSiteRoot;
161 }
162
163 /**
164 * Returns the relative path to the extension as measured from the PATH_site (frontend)
165 * If the extension is not loaded the function will die with an error message
166 * Useful for images and links from the frontend
167 *
168 * @param string $key Extension key
169 * @return string
170 */
171 static public function siteRelPath($key) {
172 return \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix(self::extPath($key));
173 }
174
175 /**
176 * Returns the correct class name prefix for the extension key $key
177 *
178 * @param string $key Extension key
179 * @return string
180 * @internal
181 */
182 static public function getCN($key) {
183 return strpos($key, 'user_') === 0 ? 'user_' . str_replace('_', '', substr($key, 5)) : 'tx_' . str_replace('_', '', $key);
184 }
185
186 /**
187 * Returns the real extension key like 'tt_news' from an extension prefix like 'tx_ttnews'.
188 *
189 * @param string $prefix The extension prefix (e.g. 'tx_ttnews')
190 * @return mixed Real extension key (string) or FALSE (boolean) if something went wrong
191 */
192 static public function getExtensionKeyByPrefix($prefix) {
193 $result = FALSE;
194 // Build map of short keys referencing to real keys:
195 if (!isset(self::$extensionKeyMap)) {
196 self::$extensionKeyMap = array();
197 foreach (static::$packageManager->getActivePackages() as $package) {
198 $shortKey = str_replace('_', '', $package->getPackageKey());
199 self::$extensionKeyMap[$shortKey] = $package->getPackageKey();
200 }
201 }
202 // Lookup by the given short key:
203 $parts = explode('_', $prefix);
204 if (isset(self::$extensionKeyMap[$parts[1]])) {
205 $result = self::$extensionKeyMap[$parts[1]];
206 }
207 return $result;
208 }
209
210 /**
211 * Clears the extension key map.
212 *
213 * @return void
214 */
215 static public function clearExtensionKeyMap() {
216 self::$extensionKeyMap = NULL;
217 }
218
219 /**
220 * Retrieves the version of an installed extension.
221 * If the extension is not installed, this function returns an empty string.
222 *
223 * @param string $key The key of the extension to look up, must not be empty
224 *
225 * @throws \InvalidArgumentException
226 * @throws \TYPO3\CMS\Core\Package\Exception
227 * @return string The extension version as a string in the format "x.y.z",
228 */
229 static public function getExtensionVersion($key) {
230 if (!is_string($key) || empty($key)) {
231 throw new \InvalidArgumentException('Extension key must be a non-empty string.', 1294586096);
232 }
233 if (!static::isLoaded($key)) {
234 return '';
235 }
236 $version = static::$packageManager->getPackage($key)->getPackageMetaData()->getVersion();
237 if (empty($version)) {
238 throw new \TYPO3\CMS\Core\Package\Exception('Version number in composer manifest of package "' . $key . '" is missing or invalid', 1395614959);
239 }
240 return $version;
241 }
242
243 /**************************************
244 *
245 * Adding BACKEND features
246 * (related to core features)
247 *
248 ***************************************/
249 /**
250 * Adding fields to an existing table definition in $GLOBALS['TCA']
251 * Adds an array with $GLOBALS['TCA'] column-configuration to the $GLOBALS['TCA']-entry for that table.
252 * This function adds the configuration needed for rendering of the field in TCEFORMS - but it does NOT add the field names to the types lists!
253 * So to have the fields displayed you must also call fx. addToAllTCAtypes or manually add the fields to the types list.
254 * FOR USE IN ext_tables.php FILES
255 *
256 * @param string $table The table name of a table already present in $GLOBALS['TCA'] with a columns section
257 * @param array $columnArray The array with the additional columns (typical some fields an extension wants to add)
258 * @param boolean $addTofeInterface DEPRECATED: Usage of feInterface is no longer part of the TYPO3 CMS Core. Please check EXT:statictemplates.
259 * @return void
260 */
261 static public function addTCAcolumns($table, $columnArray, $addTofeInterface = FALSE) {
262 if (is_array($columnArray) && is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'])) {
263 // Candidate for array_merge() if integer-keys will some day make trouble...
264 $GLOBALS['TCA'][$table]['columns'] = array_merge($GLOBALS['TCA'][$table]['columns'], $columnArray);
265 if ($addTofeInterface) {
266 GeneralUtility::deprecationLog(
267 'Usage of feInterface is no longer part of the TYPO3 CMS Core. Please check EXT:statictemplates.'
268 );
269 }
270 }
271 }
272
273 /**
274 * Makes fields visible in the TCEforms, adding them to the end of (all) "types"-configurations
275 *
276 * Adds a string $string (comma separated list of field names) to all ["types"][xxx]["showitem"] entries for table $table (unless limited by $typeList)
277 * This is needed to have new fields shown automatically in the TCEFORMS of a record from $table.
278 * Typically this function is called after having added new columns (database fields) with the addTCAcolumns function
279 * FOR USE IN ext_tables.php FILES
280 *
281 * @param string $table Table name
282 * @param string $newFieldsString Field list to add.
283 * @param string $typeList List of specific types to add the field list to. (If empty, all type entries are affected)
284 * @param string $position Insert fields before (default) or after one
285 * @return void
286 */
287 static public function addToAllTCAtypes($table, $newFieldsString, $typeList = '', $position = '') {
288 $newFieldsString = trim($newFieldsString);
289 if ($newFieldsString === '' || !is_array($GLOBALS['TCA'][$table]['types'])) {
290 return;
291 }
292 list($positionIdentifier, $entityName) = GeneralUtility::trimExplode(':', $position);
293 $palettesChanged = array();
294
295 foreach ($GLOBALS['TCA'][$table]['types'] as $type => &$typeDetails) {
296 // skip if we don't want to add the field for this type
297 if ($typeList !== '' && !GeneralUtility::inList($typeList, $type)) {
298 continue;
299 }
300 // skip if fields were already added
301 if (strpos($typeDetails['showitem'], $newFieldsString) !== FALSE) {
302 continue;
303 }
304
305 $fieldExists = FALSE;
306 $newPosition = '';
307 $paletteNames = array();
308 if (is_array($GLOBALS['TCA'][$table]['palettes'])) {
309 // Get the palette names used in current showitem
310 $paletteCount = preg_match_all('/(?:^|,) # Line start or a comma
311 (?:
312 \\s*\\-\\-palette\\-\\-;[^;]*;([^,$]*)| # --palette--;label;paletteName
313 \\s*\\b[^;,]+\\b(?:;[^;]*;([^;,]+);?[^;,]*;?)?[^,]* # field;label;paletteName[;options[;colors]]
314 )/x', $typeDetails['showitem'], $paletteMatches);
315 if ($paletteCount > 0) {
316 $paletteNames = array_filter(array_merge($paletteMatches[1], $paletteMatches[2]));
317 if (count($paletteNames)) {
318 foreach ($paletteNames as $paletteName) {
319 $palette = $GLOBALS['TCA'][$table]['palettes'][$paletteName];
320 switch ($positionIdentifier) {
321 case 'after':
322 case 'before':
323 if (preg_match('/\\b' . $entityName . '\\b/', $palette['showitem']) > 0) {
324 $newPosition = $positionIdentifier . ':--palette--;;' . $paletteName;
325 }
326 break;
327 case 'replace':
328 // check if fields have been added to palette before
329 if (isset($palettesChanged[$paletteName])) {
330 $fieldExists = TRUE;
331 continue;
332 }
333 if (preg_match('/\\b' . $entityName . '\\b/', $palette['showitem']) > 0) {
334 self::addFieldsToPalette($table, $paletteName, $newFieldsString, $position);
335 // Memorize that we already changed this palette, in case other types also use it
336 $palettesChanged[$paletteName] = TRUE;
337 $fieldExists = TRUE;
338 continue;
339 }
340 break;
341 default:
342 // Intentionally left blank
343 }
344 }
345 }
346 }
347 }
348 if ($fieldExists === FALSE) {
349 $typeDetails['showitem'] = self::executePositionedStringInsertion(
350 $typeDetails['showitem'],
351 $newFieldsString,
352 $newPosition !== '' ? $newPosition : $position
353 );
354 }
355 }
356 unset($typeDetails);
357 }
358
359 /**
360 * Adds new fields to all palettes of an existing field.
361 * If the field does not have a palette yet, it's created automatically and
362 * gets called "generatedFor-$field".
363 *
364 * @param string $table Name of the table
365 * @param string $field Name of the field that has the palette to be extended
366 * @param string $addFields List of fields to be added to the palette
367 * @param string $insertionPosition Insert fields before (default) or after one
368 * @return void
369 */
370 static public function addFieldsToAllPalettesOfField($table, $field, $addFields, $insertionPosition = '') {
371 $generatedPalette = '';
372 $processedPalettes = array();
373 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
374 $types = &$GLOBALS['TCA'][$table]['types'];
375 if (is_array($types)) {
376 // Iterate through all types and search for the field that defines the palette to be extended:
377 foreach (array_keys($types) as $type) {
378 $items = self::explodeItemList($types[$type]['showitem']);
379 if (isset($items[$field])) {
380 // If the field already has a palette, extend it:
381 if ($items[$field]['details']['palette']) {
382 $palette = $items[$field]['details']['palette'];
383 if (!isset($processedPalettes[$palette])) {
384 self::addFieldsToPalette($table, $palette, $addFields, $insertionPosition);
385 $processedPalettes[$palette] = TRUE;
386 }
387 } else {
388 if ($generatedPalette) {
389 $palette = $generatedPalette;
390 } else {
391 $palette = ($generatedPalette = 'generatedFor-' . $field);
392 self::addFieldsToPalette($table, $palette, $addFields, $insertionPosition);
393 }
394 $items[$field]['details']['palette'] = $palette;
395 $types[$type]['showitem'] = self::generateItemList($items);
396 }
397 }
398 }
399 }
400 }
401 }
402
403 /**
404 * Adds new fields to a palette.
405 * If the palette does not exist yet, it's created automatically.
406 *
407 * @param string $table Name of the table
408 * @param string $palette Name of the palette to be extended
409 * @param string $addFields List of fields to be added to the palette
410 * @param string $insertionPosition Insert fields before (default) or after one
411 * @return void
412 */
413 static public function addFieldsToPalette($table, $palette, $addFields, $insertionPosition = '') {
414 if (isset($GLOBALS['TCA'][$table])) {
415 $paletteData = &$GLOBALS['TCA'][$table]['palettes'][$palette];
416 // If palette already exists, merge the data:
417 if (is_array($paletteData)) {
418 $paletteData['showitem'] = self::executePositionedStringInsertion($paletteData['showitem'], $addFields, $insertionPosition);
419 } else {
420 $paletteData['showitem'] = self::removeDuplicatesForInsertion($addFields);
421 }
422 }
423 }
424
425 /**
426 * Add an item to a select field item list.
427 *
428 * Warning: Do not use this method for radio or check types, especially not
429 * with $relativeToField and $relativePosition parameters. This would shift
430 * existing database data 'off by one'.
431 *
432 * As an example, this can be used to add an item to tt_content CType select
433 * drop-down after the existing 'mailform' field with these parameters:
434 * - $table = 'tt_content'
435 * - $field = 'CType'
436 * - $item = array(
437 * 'LLL:EXT:cms/locallang_ttc.xlf:CType.I.10',
438 * 'login',
439 * 'i/tt_content_login.gif',
440 * ),
441 * - $relativeToField = mailform
442 * - $relativePosition = after
443 *
444 * @throws \InvalidArgumentException If given parameters are not of correct
445 * @throws \RuntimeException If reference to related position fields can not
446 * @param string $table Name of TCA table
447 * @param string $field Name of TCA field
448 * @param array $item New item to add
449 * @param string $relativeToField Add item relative to existing field
450 * @param string $relativePosition Valid keywords: 'before', 'after'
451 * @return void
452 */
453 static public function addTcaSelectItem($table, $field, array $item, $relativeToField = '', $relativePosition = '') {
454 if (!is_string($table)) {
455 throw new \InvalidArgumentException('Given table is of type "' . gettype($table) . '" but a string is expected.', 1303236963);
456 }
457 if (!is_string($field)) {
458 throw new \InvalidArgumentException('Given field is of type "' . gettype($field) . '" but a string is expected.', 1303236964);
459 }
460 if (!is_string($relativeToField)) {
461 throw new \InvalidArgumentException('Given relative field is of type "' . gettype($relativeToField) . '" but a string is expected.', 1303236965);
462 }
463 if (!is_string($relativePosition)) {
464 throw new \InvalidArgumentException('Given relative position is of type "' . gettype($relativePosition) . '" but a string is expected.', 1303236966);
465 }
466 if ($relativePosition !== '' && $relativePosition !== 'before' && $relativePosition !== 'after' && $relativePosition !== 'replace') {
467 throw new \InvalidArgumentException('Relative position must be either empty or one of "before", "after", "replace".', 1303236967);
468 }
469 if (!is_array($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'])) {
470 throw new \RuntimeException('Given select field item list was not found.', 1303237468);
471 }
472 // Make sure item keys are integers
473 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'] = array_values($GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
474 if (strlen($relativePosition) > 0) {
475 // Insert at specified position
476 $matchedPosition = \TYPO3\CMS\Core\Utility\ArrayUtility::filterByValueRecursive($relativeToField, $GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
477 if (count($matchedPosition) > 0) {
478 $relativeItemKey = key($matchedPosition);
479 if ($relativePosition === 'replace') {
480 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][$relativeItemKey] = $item;
481 } else {
482 if ($relativePosition === 'before') {
483 $offset = $relativeItemKey;
484 } else {
485 $offset = $relativeItemKey + 1;
486 }
487 array_splice($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'], $offset, 0, array(0 => $item));
488 }
489 } else {
490 // Insert at new item at the end of the array if relative position was not found
491 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
492 }
493 } else {
494 // Insert at new item at the end of the array
495 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
496 }
497 }
498
499 /**
500 * Gets the TCA configuration for a field handling (FAL) files.
501 *
502 * @param string $fieldName Name of the field to be used
503 * @param array $customSettingOverride Custom field settings overriding the basics
504 * @param string $allowedFileExtensions Comma list of allowed file extensions (e.g. "jpg,gif,pdf")
505 * @param string $disallowedFileExtensions
506 *
507 * @return array
508 */
509 static public function getFileFieldTCAConfig($fieldName, array $customSettingOverride = array(), $allowedFileExtensions = '', $disallowedFileExtensions = '') {
510 $fileFieldTCAConfig = array(
511 'type' => 'inline',
512 'foreign_table' => 'sys_file_reference',
513 'foreign_field' => 'uid_foreign',
514 'foreign_sortby' => 'sorting_foreign',
515 'foreign_table_field' => 'tablenames',
516 'foreign_match_fields' => array(
517 'fieldname' => $fieldName
518 ),
519 'foreign_label' => 'uid_local',
520 'foreign_selector' => 'uid_local',
521 'foreign_selector_fieldTcaOverride' => array(
522 'config' => array(
523 'appearance' => array(
524 'elementBrowserType' => 'file',
525 'elementBrowserAllowed' => $allowedFileExtensions
526 )
527 )
528 ),
529 'filter' => array(
530 array(
531 'userFunc' => 'TYPO3\\CMS\\Core\\Resource\\Filter\\FileExtensionFilter->filterInlineChildren',
532 'parameters' => array(
533 'allowedFileExtensions' => $allowedFileExtensions,
534 'disallowedFileExtensions' => $disallowedFileExtensions
535 )
536 )
537 ),
538 'appearance' => array(
539 'useSortable' => TRUE,
540 'headerThumbnail' => array(
541 'field' => 'uid_local',
542 'width' => '45',
543 'height' => '45c',
544 ),
545 'showPossibleLocalizationRecords' => FALSE,
546 'showRemovedLocalizationRecords' => FALSE,
547 'showSynchronizationLink' => FALSE,
548 'showAllLocalizationLink' => FALSE,
549
550 'enabledControls' => array(
551 'info' => TRUE,
552 'new' => FALSE,
553 'dragdrop' => TRUE,
554 'sort' => FALSE,
555 'hide' => TRUE,
556 'delete' => TRUE,
557 'localize' => TRUE,
558 ),
559 ),
560 'behaviour' => array(
561 'localizationMode' => 'select',
562 'localizeChildrenAtParentLocalization' => TRUE,
563 ),
564 );
565 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($fileFieldTCAConfig, $customSettingOverride);
566 return $fileFieldTCAConfig;
567 }
568
569 /**
570 * Adds a list of new fields to the TYPO3 USER SETTINGS configuration "showitem" list, the array with
571 * the new fields itself needs to be added additionally to show up in the user setup, like
572 * $GLOBALS['TYPO3_USER_SETTINGS']['columns'] += $tempColumns
573 *
574 * @param string $addFields List of fields to be added to the user settings
575 * @param string $insertionPosition Insert fields before (default) or after one
576 * @return void
577 */
578 static public function addFieldsToUserSettings($addFields, $insertionPosition = '') {
579 $GLOBALS['TYPO3_USER_SETTINGS']['showitem'] = self::executePositionedStringInsertion($GLOBALS['TYPO3_USER_SETTINGS']['showitem'], $addFields, $insertionPosition);
580 }
581
582 /**
583 * Inserts as list of data into an existing list.
584 * The insertion position can be defined accordant before of after existing list items.
585 *
586 * Example:
587 * + list: 'field_a, field_b;;;;2-2-2, field_c;;;;3-3-3'
588 * + insertionList: 'field_d, field_e;;;4-4-4'
589 * + insertionPosition: 'after:field_b'
590 * -> 'field_a, field_b;;;;2-2-2, field_d, field_e;;;4-4-4, field_c;;;;3-3-3'
591 *
592 * $insertPosition may contain ; and - characters: after:--palette--;;title
593 *
594 * @param string $list The list of items to be extended
595 * @param string $insertionList The list of items to inserted
596 * @param string $insertionPosition Insert fields before (default) or after one
597 * @return string The extended list
598 */
599 static protected function executePositionedStringInsertion($list, $insertionList, $insertionPosition = '') {
600 $list = $newList = trim($list, ", \t\n\r\0\x0B");
601
602 $insertionList = self::removeDuplicatesForInsertion($insertionList, $list);
603
604 if ($insertionList === '') {
605 return $list;
606 }
607 if ($list === '') {
608 return $insertionList;
609 }
610 if ($insertionPosition === '') {
611 return $list . ', ' . $insertionList;
612 }
613
614 list($location, $positionName) = GeneralUtility::trimExplode(':', $insertionPosition);
615 // The $insertPosition may be a palette: after:--palette--;;title
616 // In the $list the palette may contain a LLL string in between the ;;
617 // Adjust the regex to match that
618 if (strpos($positionName, ';;') !== FALSE) {
619 $positionName = str_replace(';;', ';[^;]*;', $positionName);
620 }
621
622 $pattern = ('/(^|,\\s*)(' . $positionName . ')(;[^,$]+)?(,|$)/');
623 switch ($location) {
624 case 'after':
625 $newList = preg_replace($pattern, '$1$2$3, ' . $insertionList . '$4', $list);
626 break;
627 case 'before':
628 $newList = preg_replace($pattern, '$1' . $insertionList . ', $2$3$4', $list);
629 break;
630 case 'replace':
631 $newList = preg_replace($pattern, '$1' . $insertionList . '$4', $list);
632 break;
633 default:
634 }
635
636 // When preg_replace did not replace anything; append the $insertionList.
637 if ($list === $newList) {
638 return $list . ', ' . $insertionList;
639 }
640 return $newList;
641 }
642
643 /**
644 * Compares an existing list of items and a list of items to be inserted
645 * and returns a duplicate-free variant of that insertion list.
646 *
647 * Example:
648 * + list: 'field_a, field_b;;;;2-2-2, field_c;;;;3-3-3'
649 * + insertion: 'field_b, field_d, field_c;;;4-4-4'
650 * -> new insertion: 'field_d'
651 *
652 * Duplicate values in $insertionList are removed.
653 *
654 * @param string $insertionList The list of items to inserted
655 * @param string $list The list of items to be extended (default: '')
656 * @return string Duplicate-free list of items to be inserted
657 */
658 static protected function removeDuplicatesForInsertion($insertionList, $list = '') {
659 $insertionListParts = preg_split('/\\s*,\\s*/', $insertionList);
660 $insertionList = implode(', ', array_unique($insertionListParts));
661 if ($list === '') {
662 return $insertionList;
663 }
664 // Get a list of fieldNames that are present in the list.
665 preg_match_all('/(?:^|,)\\s*\\b([^;,]+)\\b[^,]*/', $list, $listMatches);
666 // Remove the field names from the insertionlist.
667 $fieldReplacePatterns = array();
668 foreach ($listMatches[1] as $fieldName) {
669 $fieldReplacePatterns[] = '/(?:^|,)\\s*\\b' . preg_quote($fieldName, '/') . '\\b[^,$]*/';
670 }
671 return preg_replace($fieldReplacePatterns, '', $insertionList);
672 }
673
674 /**
675 * Generates search needles that are used for inserting fields/items into an existing list.
676 *
677 * @see executePositionedStringInsertion
678 * @param string $item The name of the field/item
679 * @param array $itemDetails Additional details of the field/item like e.g. palette information
680 * @return array The needled to be used for inserting content before or after existing fields/items
681 * @deprecated since 6.2, will be removed two versions later. This method was only used by executePositionedStringInsertion().
682 */
683 static protected function getInsertionNeedles($item, array $itemDetails) {
684 if (strpos($item, '--') !== FALSE) {
685 // If $item is a separator (--div--) or palette (--palette--) then it may have been appended by a unique number. This must be stripped away here.
686 $item = str_replace(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), '', $item);
687 }
688 $needles = array(
689 'before' => array($item, 'before:' . $item),
690 'after' => array('after:' . $item),
691 'replace' => array('replace:' . $item)
692 );
693 if ($itemDetails['palette']) {
694 $palette = $item . ';;' . $itemDetails['palette'];
695 $needles['before'][] = $palette;
696 $needles['before'][] = 'before:' . $palette;
697 $needles['after'][] = 'after:' . $palette;
698 $needles['replace'][] = 'replace:' . $palette;
699 }
700 return $needles;
701 }
702
703 /**
704 * Generates an array of fields/items with additional information such as e.g. the name of the palette.
705 *
706 * @param string $itemList List of fields/items to be splitted up
707 * @return array An array with the names of the fields/items as keys and additional information
708 */
709 static protected function explodeItemList($itemList) {
710 $items = array();
711 $itemParts = GeneralUtility::trimExplode(',', $itemList, TRUE);
712 foreach ($itemParts as $itemPart) {
713 $itemDetails = GeneralUtility::trimExplode(';', $itemPart, FALSE, 5);
714 $key = $itemDetails[0];
715 if (strpos($key, '--') !== FALSE) {
716 // If $key is a separator (--div--) or palette (--palette--) then it will be appended by a unique number. This must be removed again when using this value!
717 $key .= count($items);
718 }
719 if (!isset($items[$key])) {
720 $items[$key] = array(
721 'rawData' => $itemPart,
722 'details' => array(
723 'field' => $itemDetails[0],
724 'label' => $itemDetails[1],
725 'palette' => $itemDetails[2],
726 'special' => $itemDetails[3],
727 'styles' => $itemDetails[4]
728 )
729 );
730 }
731 }
732 return $items;
733 }
734
735 /**
736 * Generates a list of fields/items out of an array provided by the function getFieldsOfFieldList().
737 *
738 * @see explodeItemList
739 * @param array $items The array of fields/items with optional additional information
740 * @param boolean $useRawData Use raw data instead of building by using the details (default: FALSE)
741 * @return string The list of fields/items which gets used for $GLOBALS['TCA'][<table>]['types'][<type>]['showitem']
742 */
743 static protected function generateItemList(array $items, $useRawData = FALSE) {
744 $itemParts = array();
745 foreach ($items as $item => $itemDetails) {
746 if (strpos($item, '--') !== FALSE) {
747 // If $item is a separator (--div--) or palette (--palette--) then it may have been appended by a unique number. This must be stripped away here.
748 $item = str_replace(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), '', $item);
749 }
750 if ($useRawData) {
751 $itemParts[] = $itemDetails['rawData'];
752 } else {
753 $itemParts[] = count($itemDetails['details']) > 1 ? implode(';', $itemDetails['details']) : $item;
754 }
755 }
756 return implode(', ', $itemParts);
757 }
758
759 /**
760 * Add tablename to default list of allowed tables on pages (in $PAGES_TYPES)
761 * Will add the $table to the list of tables allowed by default on pages as setup by $PAGES_TYPES['default']['allowedTables']
762 * FOR USE IN ext_tables.php FILES
763 *
764 * @param string $table Table name
765 * @return void
766 */
767 static public function allowTableOnStandardPages($table) {
768 $GLOBALS['PAGES_TYPES']['default']['allowedTables'] .= ',' . $table;
769 }
770
771 /**
772 * Adds a ExtJS module (main or sub) to the backend interface
773 * FOR USE IN ext_tables.php FILES
774 *
775 * @static
776 * @param string $extensionName
777 * @param string $mainModuleName Is the main module key
778 * @param string $subModuleName Is the submodule key, if blank a plain main module is generated
779 * @param string $position Passed to \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModule, see reference there
780 * @param array $moduleConfiguration Icon with array keys: access, icon, labels to configure the module
781 * @throws \InvalidArgumentException
782 */
783 static public function addExtJSModule($extensionName, $mainModuleName, $subModuleName = '', $position = '', array $moduleConfiguration = array()) {
784 if (empty($extensionName)) {
785 throw new \InvalidArgumentException('The extension name must not be empty', 1325938973);
786 }
787 $extensionKey = GeneralUtility::camelCaseToLowerCaseUnderscored($extensionName);
788 $extensionName = str_replace(' ', '', ucwords(str_replace('_', ' ', $extensionName)));
789 $defaultModuleConfiguration = array(
790 'access' => 'admin',
791 'icon' => 'gfx/typo3.png',
792 'labels' => '',
793 'extRelPath' => self::extRelPath($extensionKey) . 'Classes/'
794 );
795 // Add mandatory parameter to use new pagetree
796 if ($mainModuleName === 'web') {
797 $defaultModuleConfiguration['navigationComponentId'] = 'typo3-pagetree';
798 }
799 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($defaultModuleConfiguration, $moduleConfiguration);
800 $moduleConfiguration = $defaultModuleConfiguration;
801 if (strlen($subModuleName) > 0) {
802 $moduleSignature = $mainModuleName . '_' . $subModuleName;
803 } else {
804 $moduleSignature = $mainModuleName;
805 }
806 $moduleConfiguration['name'] = $moduleSignature;
807 $moduleConfiguration['script'] = 'extjspaneldummy.html';
808 $moduleConfiguration['extensionName'] = $extensionName;
809 $moduleConfiguration['configureModuleFunction'] = array('TYPO3\\CMS\\Core\\Utility\\ExtensionManagementUtility', 'configureModule');
810 $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature] = $moduleConfiguration;
811 self::addModule($mainModuleName, $subModuleName, $position);
812 }
813
814 /**
815 * This method is called from \TYPO3\CMS\Backend\Module\ModuleLoader::checkMod
816 * and it replaces old conf.php.
817 *
818 * The original function for is called
819 * Tx_Extbase_Utility_Extension::configureModule, the refered function can
820 * be deprecated now
821 *
822 * @param string $moduleSignature The module name
823 * @param string $modulePath Absolute path to module (not used by Extbase currently)
824 * @return array Configuration of the module
825 */
826 static public function configureModule($moduleSignature, $modulePath) {
827 $moduleConfiguration = $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature];
828 $iconPathAndFilename = $moduleConfiguration['icon'];
829 if (substr($iconPathAndFilename, 0, 4) === 'EXT:') {
830 list($extensionKey, $relativePath) = explode('/', substr($iconPathAndFilename, 4), 2);
831 $iconPathAndFilename = self::extPath($extensionKey) . $relativePath;
832 }
833 // TODO: skin support
834 $moduleLabels = array(
835 'tabs_images' => array(
836 'tab' => $iconPathAndFilename
837 ),
838 'labels' => array(
839 'tablabel' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_labels_tablabel'),
840 'tabdescr' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_labels_tabdescr')
841 ),
842 'tabs' => array(
843 'tab' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_tabs_tab')
844 )
845 );
846 $GLOBALS['LANG']->addModuleLabels($moduleLabels, $moduleSignature . '_');
847 return $moduleConfiguration;
848 }
849
850 /**
851 * Adds a module (main or sub) to the backend interface
852 * FOR USE IN ext_tables.php FILES
853 *
854 * @param string $main The main module key, $sub is the submodule key. So $main would be an index in the $TBE_MODULES array and $sub could be an element in the lists there.
855 * @param string $sub The submodule key. If $sub is not set a blank $main module is created.
856 * @param string $position Can be used to set the position of the $sub module within the list of existing submodules for the main module. $position has this syntax: [cmd]:[submodule-key]. cmd can be "after", "before" or "top" (or blank which is default). If "after"/"before" then submodule will be inserted after/before the existing submodule with [submodule-key] if found. If not found, the bottom of list. If "top" the module is inserted in the top of the submodule list.
857 * @param string $path The absolute path to the module. If this value is defined the path is added as an entry in $TBE_MODULES['_PATHS'][ main_sub ] = $path; and thereby tells the backend where the newly added modules is found in the system.
858 * @param array $moduleConfiguration additional configuration, previously put in "conf.php" of the module directory
859 * @return void
860 */
861 static public function addModule($main, $sub = '', $position = '', $path = '', $moduleConfiguration = array()) {
862 // If there is already a main module by this name:
863 // Adding the submodule to the correct position:
864 if (isset($GLOBALS['TBE_MODULES'][$main]) && $sub) {
865 list($place, $modRef) = GeneralUtility::trimExplode(':', $position, TRUE);
866 $modules = ',' . $GLOBALS['TBE_MODULES'][$main] . ',';
867 if ($place === NULL || ($modRef !== NULL && !GeneralUtility::inList($modules, $modRef))) {
868 $place = 'bottom';
869 }
870 $modRef = ',' . $modRef . ',';
871 if (!GeneralUtility::inList($modules, $sub)) {
872 switch (strtolower($place)) {
873 case 'after':
874 $modules = str_replace($modRef, $modRef . $sub . ',', $modules);
875 break;
876 case 'before':
877 $modules = str_replace($modRef, ',' . $sub . $modRef, $modules);
878 break;
879 case 'top':
880 $modules = $sub . $modules;
881 break;
882 case 'bottom':
883 default:
884 $modules = $modules . $sub;
885 }
886 }
887 // Re-inserting the submodule list:
888 $GLOBALS['TBE_MODULES'][$main] = trim($modules, ',');
889 } else {
890 // Create new main modules with only one submodule, $sub (or none if $sub is blank)
891 $GLOBALS['TBE_MODULES'][$main] = $sub;
892 }
893 $fullModuleSignature = $main . ($sub ? '_' . $sub : '');
894 // Adding path:
895 if ($path) {
896 $GLOBALS['TBE_MODULES']['_PATHS'][$fullModuleSignature] = $path;
897 }
898
899 // add additional configuration
900 if (is_array($moduleConfiguration) && count($moduleConfiguration) > 0) {
901 $GLOBALS['TBE_MODULES']['_configuration'][$fullModuleSignature] = $moduleConfiguration;
902 }
903 }
904
905 /**
906 * Registers an Ext.Direct component with access restrictions.
907 *
908 * @param string $endpointName
909 * @param string $callbackClass
910 * @param string $moduleName Optional: must be <mainmodule> or <mainmodule>_<submodule>
911 * @param string $accessLevel Optional: can be 'admin' or 'user,group'
912 * @return void
913 */
914 static public function registerExtDirectComponent($endpointName, $callbackClass, $moduleName = NULL, $accessLevel = NULL) {
915 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ExtDirect'][$endpointName] = array(
916 'callbackClass' => $callbackClass,
917 'moduleName' => $moduleName,
918 'accessLevel' => $accessLevel
919 );
920 }
921
922 /**
923 * Registers an Ajax Handler
924 *
925 * @param string $ajaxId Identifier of the handler, that is used in the request
926 * @param string $callbackMethod TYPO3 callback method (className->methodName).
927 * @param bool $csrfTokenCheck Only set this to FALSE if you are sure that the registered handler does not modify any data!
928 */
929 static public function registerAjaxHandler($ajaxId, $callbackMethod, $csrfTokenCheck = TRUE) {
930 $GLOBALS['TYPO3_CONF_VARS']['BE']['AJAX'][$ajaxId] = array(
931 'callbackMethod' => $callbackMethod,
932 'csrfTokenCheck' => $csrfTokenCheck
933 );
934 }
935
936 /**
937 * Adds a module path to $GLOBALS['TBE_MODULES'] for used with the module dispatcher, mod.php
938 * Used only for modules that are not placed in the main/sub menu hierarchy by the traditional mechanism of addModule()
939 * Examples for this is context menu functionality (like import/export) which runs as an independent module through mod.php
940 * FOR USE IN ext_tables.php FILES
941 * Example: \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModulePath('xMOD_tximpexp', \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY).'app/');
942 *
943 * @param string $name The name of the module, refer to conf.php of the module.
944 * @param string $path The absolute path to the module directory inside of which "index.php" and "conf.php" is found.
945 * @return void
946 */
947 static public function addModulePath($name, $path) {
948 $GLOBALS['TBE_MODULES']['_PATHS'][$name] = $path;
949 }
950
951 /**
952 * Adds a "Function menu module" ('third level module') to an existing function menu for some other backend module
953 * The arguments values are generally determined by which function menu this is supposed to interact with
954 * See Inside TYPO3 for information on how to use this function.
955 * FOR USE IN ext_tables.php FILES
956 *
957 * @param string $modname Module name
958 * @param string $className Class name
959 * @param string $classPath Class path, deprecated since 6.2, use auto-loading instead
960 * @param string $title Title of module
961 * @param string $MM_key Menu array key - default is "function
962 * @param string $WS Workspace conditions. Blank means all workspaces, any other string can be a comma list of "online", "offline" and "custom
963 * @return void
964 * @see \TYPO3\CMS\Backend\Module\BaseScriptClass::mergeExternalItems()
965 */
966 static public function insertModuleFunction($modname, $className, $classPath, $title, $MM_key = 'function', $WS = '') {
967 if (!empty($classPath)) {
968 GeneralUtility::deprecationLog(
969 sprintf('insertModuleFunction(%s, %s, ...): Use auto-loading for the class and pass NULL as $classPath since 6.2.',
970 $modname,
971 $className
972 )
973 );
974 }
975 $GLOBALS['TBE_MODULES_EXT'][$modname]['MOD_MENU'][$MM_key][$className] = array(
976 'name' => $className,
977 'path' => $classPath,
978 'title' => $title,
979 'ws' => $WS
980 );
981 }
982
983 /**
984 * Adds some more content to a key of TYPO3_CONF_VARS array.
985 *
986 * This also tracks which content was added by extensions (in TYPO3_CONF_VARS_extensionAdded)
987 * so that they cannot be editted again through the Install Tool.
988 *
989 * @static
990 * @param string $group The group ('FE', 'BE', 'SYS' ...)
991 * @param string $key The key of this setting within the group
992 * @param string $content The text to add (include leading "\n" in case of multi-line entries)
993 * @return void
994 */
995 static public function appendToTypoConfVars($group, $key, $content) {
996 $GLOBALS['TYPO3_CONF_VARS_extensionAdded'][$group][$key] .= $content;
997 $GLOBALS['TYPO3_CONF_VARS'][$group][$key] .= $content;
998 }
999
1000 /**
1001 * Adds $content to the default Page TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultPageTSconfig']
1002 * Prefixed with a [GLOBAL] line
1003 * FOR USE IN ext_tables.php/ext_localconf.php FILES
1004 *
1005 * @param string $content Page TSconfig content
1006 * @return void
1007 */
1008 static public function addPageTSConfig($content) {
1009 self::appendToTypoConfVars('BE', 'defaultPageTSconfig', '
1010 [GLOBAL]
1011 ' . $content);
1012 }
1013
1014 /**
1015 * Adds $content to the default User TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultUserTSconfig']
1016 * Prefixed with a [GLOBAL] line
1017 * FOR USE IN ext_tables.php/ext_localconf.php FILES
1018 *
1019 * @param string $content User TSconfig content
1020 * @return void
1021 */
1022 static public function addUserTSConfig($content) {
1023 self::appendToTypoConfVars('BE', 'defaultUserTSconfig', '
1024 [GLOBAL]
1025 ' . $content);
1026 }
1027
1028 /**
1029 * Adds a reference to a locallang file with $GLOBALS['TCA_DESCR'] labels
1030 * FOR USE IN ext_tables.php FILES
1031 * eg. \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addLLrefForTCAdescr('pages', 'EXT:lang/locallang_csh_pages.xlf'); for the pages table or \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addLLrefForTCAdescr('_MOD_web_layout', 'EXT:cms/locallang_csh_weblayout.php'); for the Web > Page module.
1032 *
1033 * @param string $tca_descr_key Description key. Typically a database table (like "pages") but for applications can be other strings, but prefixed with "_MOD_")
1034 * @param string $file_ref File reference to locallang file, eg. "EXT:lang/locallang_csh_pages.xlf" (or ".xml")
1035 * @return void
1036 */
1037 static public function addLLrefForTCAdescr($tca_descr_key, $file_ref) {
1038 if ($tca_descr_key) {
1039 if (!is_array($GLOBALS['TCA_DESCR'][$tca_descr_key])) {
1040 $GLOBALS['TCA_DESCR'][$tca_descr_key] = array();
1041 }
1042 if (!is_array($GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'])) {
1043 $GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'] = array();
1044 }
1045 $GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'][] = $file_ref;
1046 }
1047 }
1048
1049 /**
1050 * Registers a navigation component
1051 *
1052 * @param string $module
1053 * @param string $componentId
1054 * @return void
1055 */
1056 static public function addNavigationComponent($module, $componentId) {
1057 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module] = array(
1058 'componentId' => $componentId,
1059 'extKey' => $GLOBALS['_EXTKEY'],
1060 'isCoreComponent' => FALSE
1061 );
1062 }
1063
1064 /**
1065 * Registers a core navigation component
1066 *
1067 * @param string $module
1068 * @param string $componentId
1069 * @return void
1070 */
1071 static public function addCoreNavigationComponent($module, $componentId) {
1072 self::addNavigationComponent($module, $componentId);
1073 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module]['isCoreComponent'] = TRUE;
1074 }
1075
1076 /**************************************
1077 *
1078 * Adding SERVICES features
1079 *
1080 ***************************************/
1081 /**
1082 * Adds a service to the global services array
1083 *
1084 * @param string $extKey Extension key
1085 * @param string $serviceType Service type, must not be prefixed "tx_" or "Tx_
1086 * @param string $serviceKey Service key, must be prefixed "tx_", "Tx_" or "user_
1087 * @param array $info Service description array
1088 * @return void
1089 */
1090 static public function addService($extKey, $serviceType, $serviceKey, $info) {
1091 if ($serviceType && is_array($info)) {
1092 $info['priority'] = max(0, min(100, $info['priority']));
1093 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = $info;
1094 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['extKey'] = $extKey;
1095 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceKey'] = $serviceKey;
1096 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceType'] = $serviceType;
1097 // Change the priority (and other values) from $GLOBALS['TYPO3_CONF_VARS']
1098 // $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]['priority']
1099 // even the activation is possible (a unix service might be possible on windows for some reasons)
1100 if (is_array($GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey])) {
1101 // No check is done here - there might be configuration values only the service type knows about, so
1102 // we pass everything
1103 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = array_merge($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey], $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]);
1104 }
1105 // OS check
1106 // Empty $os means 'not limited to one OS', therefore a check is not needed
1107 if ($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] && $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os'] != '') {
1108 // TYPO3_OS is not yet defined
1109 $os_type = stripos(PHP_OS, 'win') !== FALSE && !stripos(PHP_OS, 'darwin') !== FALSE ? 'WIN' : 'UNIX';
1110 $os = GeneralUtility::trimExplode(',', strtoupper($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os']));
1111 if (!in_array($os_type, $os)) {
1112 self::deactivateService($serviceType, $serviceKey);
1113 }
1114 }
1115 // Convert subtype list to array for quicker access
1116 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'] = array();
1117 $serviceSubTypes = GeneralUtility::trimExplode(',', $info['subtype']);
1118 foreach ($serviceSubTypes as $subtype) {
1119 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'][$subtype] = $subtype;
1120 }
1121 }
1122 }
1123
1124 /**
1125 * Find the available service with highest priority
1126 *
1127 * @param string $serviceType Service type
1128 * @param string $serviceSubType Service sub type
1129 * @param mixed $excludeServiceKeys Service keys that should be excluded in the search for a service. Array or comma list.
1130 * @return mixed Service info array if a service was found, FALSE otherwise
1131 */
1132 static public function findService($serviceType, $serviceSubType = '', $excludeServiceKeys = array()) {
1133 $serviceKey = FALSE;
1134 $serviceInfo = FALSE;
1135 $priority = 0;
1136 $quality = 0;
1137 if (!is_array($excludeServiceKeys)) {
1138 $excludeServiceKeys = GeneralUtility::trimExplode(',', $excludeServiceKeys, TRUE);
1139 }
1140 if (is_array($GLOBALS['T3_SERVICES'][$serviceType])) {
1141 foreach ($GLOBALS['T3_SERVICES'][$serviceType] as $key => $info) {
1142 if (in_array($key, $excludeServiceKeys)) {
1143 continue;
1144 }
1145 // Select a subtype randomly
1146 // Useful to start a service by service key without knowing his subtypes - for testing purposes
1147 if ($serviceSubType == '*') {
1148 $serviceSubType = key($info['serviceSubTypes']);
1149 }
1150 // This matches empty subtype too
1151 if ($info['available'] && ($info['subtype'] == $serviceSubType || $info['serviceSubTypes'][$serviceSubType]) && $info['priority'] >= $priority) {
1152 // Has a lower quality than the already found, therefore we skip this service
1153 if ($info['priority'] == $priority && $info['quality'] < $quality) {
1154 continue;
1155 }
1156 // Check if the service is available
1157 $info['available'] = self::isServiceAvailable($serviceType, $key, $info);
1158 // Still available after exec check?
1159 if ($info['available']) {
1160 $serviceKey = $key;
1161 $priority = $info['priority'];
1162 $quality = $info['quality'];
1163 }
1164 }
1165 }
1166 }
1167 if ($serviceKey) {
1168 $serviceInfo = $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey];
1169 }
1170 return $serviceInfo;
1171 }
1172
1173 /**
1174 * Find a specific service identified by its key
1175 * Note that this completely bypasses the notions of priority and quality
1176 *
1177 * @param string $serviceKey Service key
1178 * @return array Service info array if a service was found
1179 * @throws \TYPO3\CMS\Core\Exception
1180 */
1181 static public function findServiceByKey($serviceKey) {
1182 if (is_array($GLOBALS['T3_SERVICES'])) {
1183 // Loop on all service types
1184 // NOTE: we don't care about the actual type, we are looking for a specific key
1185 foreach ($GLOBALS['T3_SERVICES'] as $serviceType => $servicesPerType) {
1186 if (isset($servicesPerType[$serviceKey])) {
1187 $serviceDetails = $servicesPerType[$serviceKey];
1188 // Test if service is available
1189 if (self::isServiceAvailable($serviceType, $serviceKey, $serviceDetails)) {
1190 // We have found the right service, return its information
1191 return $serviceDetails;
1192 }
1193 }
1194 }
1195 }
1196 throw new \TYPO3\CMS\Core\Exception('Service not found for key: ' . $serviceKey, 1319217244);
1197 }
1198
1199 /**
1200 * Check if a given service is available, based on the executable files it depends on
1201 *
1202 * @param string $serviceType Type of service
1203 * @param string $serviceKey Specific key of the service
1204 * @param array $serviceDetails Information about the service
1205 * @return boolean Service availability
1206 */
1207 static public function isServiceAvailable($serviceType, $serviceKey, $serviceDetails) {
1208 // If the service depends on external programs - check if they exists
1209 if (trim($serviceDetails['exec'])) {
1210 $executables = GeneralUtility::trimExplode(',', $serviceDetails['exec'], TRUE);
1211 foreach ($executables as $executable) {
1212 // If at least one executable file is not available, exit early returning FALSE
1213 if (!\TYPO3\CMS\Core\Utility\CommandUtility::checkCommand($executable)) {
1214 self::deactivateService($serviceType, $serviceKey);
1215 return FALSE;
1216 }
1217 }
1218 }
1219 // The service is available
1220 return TRUE;
1221 }
1222
1223 /**
1224 * Deactivate a service
1225 *
1226 * @param string $serviceType Service type
1227 * @param string $serviceKey Service key
1228 * @return void
1229 */
1230 static public function deactivateService($serviceType, $serviceKey) {
1231 // ... maybe it's better to move non-available services to a different array??
1232 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] = FALSE;
1233 }
1234
1235 /**************************************
1236 *
1237 * Adding FRONTEND features
1238 * (related specifically to "cms" extension)
1239 *
1240 ***************************************/
1241 /**
1242 * Adds an entry to the list of plugins in content elements of type "Insert plugin"
1243 * Takes the $itemArray (label, value[,icon]) and adds to the items-array of $GLOBALS['TCA'][tt_content] elements with CType "listtype" (or another field if $type points to another fieldname)
1244 * If the value (array pos. 1) is already found in that items-array, the entry is substituted, otherwise the input array is added to the bottom.
1245 * Use this function to add a frontend plugin to this list of plugin-types - or more generally use this function to add an entry to any selectorbox/radio-button set in the TCEFORMS
1246 * FOR USE IN ext_tables.php FILES
1247 *
1248 * @param array $itemArray Item Array
1249 * @param string $type Type (eg. "list_type") - basically a field from "tt_content" table
1250 * @return void
1251 */
1252 static public function addPlugin($itemArray, $type = 'list_type') {
1253 $_EXTKEY = $GLOBALS['_EXTKEY'];
1254 if ($_EXTKEY && !$itemArray[2]) {
1255 $itemArray[2] = self::extRelPath($_EXTKEY) . $GLOBALS['TYPO3_LOADED_EXT'][$_EXTKEY]['ext_icon'];
1256 }
1257 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'])) {
1258 foreach ($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'] as $k => $v) {
1259 if ((string)$v[1] === (string)$itemArray[1]) {
1260 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][$k] = $itemArray;
1261 return;
1262 }
1263 }
1264 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][] = $itemArray;
1265 }
1266 }
1267
1268 /**
1269 * Adds an entry to the "ds" array of the tt_content field "pi_flexform".
1270 * This is used by plugins to add a flexform XML reference / content for use when they are selected as plugin or content element.
1271 *
1272 * @param string $piKeyToMatch Plugin key as used in the list_type field. Use the asterisk * to match all list_type values.
1273 * @param string $value Either a reference to a flex-form XML file (eg. "FILE:EXT:newloginbox/flexform_ds.xml") or the XML directly.
1274 * @param string $CTypeToMatch Value of tt_content.CType (Content Type) to match. The default is "list" which corresponds to the "Insert Plugin" content element. Use the asterisk * to match all CType values.
1275 * @return void
1276 * @see addPlugin()
1277 */
1278 static public function addPiFlexFormValue($piKeyToMatch, $value, $CTypeToMatch = 'list') {
1279 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'])) {
1280 $GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'][$piKeyToMatch . ',' . $CTypeToMatch] = $value;
1281 }
1282 }
1283
1284 /**
1285 * Adds the $table tablename to the list of tables allowed to be includes by content element type "Insert records"
1286 * By using $content_table and $content_field you can also use the function for other tables.
1287 * FOR USE IN ext_tables.php FILES
1288 *
1289 * @param string $table Table name to allow for "insert record
1290 * @param string $content_table Table name TO WHICH the $table name is applied. See $content_field as well.
1291 * @param string $content_field Field name in the database $content_table in which $table is allowed to be added as a reference ("Insert Record")
1292 * @return void
1293 */
1294 static public function addToInsertRecords($table, $content_table = 'tt_content', $content_field = 'records') {
1295 if (is_array($GLOBALS['TCA'][$content_table]['columns']) && isset($GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'])) {
1296 $GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'] .= ',' . $table;
1297 }
1298 }
1299
1300 /**
1301 * Add PlugIn to Static Template #43
1302 *
1303 * When adding a frontend plugin you will have to add both an entry to the TCA definition of tt_content table AND to the TypoScript template which must initiate the rendering.
1304 * Since the static template with uid 43 is the "content.default" and practically always used for rendering the content elements it's very useful to have this function automatically adding the necessary TypoScript for calling your plugin. It will also work for the extension "css_styled_content"
1305 * $type determines the type of frontend plugin:
1306 * + list_type (default) - the good old "Insert plugin" entry
1307 * + menu_type - a "Menu/Sitemap" entry
1308 * + CType - a new content element type
1309 * + header_layout - an additional header type (added to the selection of layout1-5)
1310 * + includeLib - just includes the library for manual use somewhere in TypoScript.
1311 * (Remember that your $type definition should correspond to the column/items array in $GLOBALS['TCA'][tt_content] where you added the selector item for the element! See addPlugin() function)
1312 * FOR USE IN ext_localconf.php FILES
1313 *
1314 * @param string $key The extension key
1315 * @param string $classFile The PHP-class filename relative to the extension root directory. If set to blank a default value is chosen according to convensions.
1316 * @param string $prefix Is used as a - yes, suffix - of the class name (fx. "_pi1")
1317 * @param string $type See description above
1318 * @param integer $cached If $cached is set as USER content object (cObject) is created - otherwise a USER_INT object is created.
1319 *
1320 * @return void
1321 */
1322 static public function addPItoST43($key, $classFile = '', $prefix = '', $type = 'list_type', $cached = 0) {
1323 $classFile = $classFile ? $classFile : 'pi/class.tx_' . str_replace('_', '', $key) . $prefix . '.php';
1324 $cN = self::getCN($key);
1325 // General plugin
1326 $pluginContent = trim('
1327 plugin.' . $cN . $prefix . ' = USER' . ($cached ? '' : '_INT') . '
1328 plugin.' . $cN . $prefix . ' {
1329 includeLibs = ' . $GLOBALS['TYPO3_LOADED_EXT'][$key]['siteRelPath'] . $classFile . '
1330 userFunc = ' . $cN . $prefix . '->main
1331 }');
1332 self::addTypoScript($key, 'setup', '
1333 # Setting ' . $key . ' plugin TypoScript
1334 ' . $pluginContent);
1335 // After ST43
1336 switch ($type) {
1337 case 'list_type':
1338 $addLine = 'tt_content.list.20.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1339 break;
1340 case 'menu_type':
1341 $addLine = 'tt_content.menu.20.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1342 break;
1343 case 'CType':
1344 $addLine = trim('
1345 tt_content.' . $key . $prefix . ' = COA
1346 tt_content.' . $key . $prefix . ' {
1347 10 = < lib.stdheader
1348 20 = < plugin.' . $cN . $prefix . '
1349 }
1350 ');
1351 break;
1352 case 'header_layout':
1353 $addLine = 'lib.stdheader.10.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1354 break;
1355 case 'includeLib':
1356 $addLine = 'page.1000 = < plugin.' . $cN . $prefix;
1357 break;
1358 default:
1359 $addLine = '';
1360 }
1361 if ($addLine) {
1362 self::addTypoScript($key, 'setup', '
1363 # Setting ' . $key . ' plugin TypoScript
1364 ' . $addLine . '
1365 ', 43);
1366 }
1367 }
1368
1369 /**
1370 * Call this method to add an entry in the static template list found in sys_templates
1371 * FOR USE IN ext_tables.php FILES
1372 *
1373 * @param string $extKey Is of course the extension key
1374 * @param string $path Is the path where the template files (fixed names) include_static.txt (integer list of uids from the table "static_templates"), constants.txt, setup.txt, and include_static_file.txt is found (relative to extPath, eg. 'static/'). The file include_static_file.txt, allows you to include other static templates defined in files, from your static template, and thus corresponds to the field 'include_static_file' in the sys_template table. The syntax for this is a comma separated list of static templates to include, like: EXT:css_styled_content/static/,EXT:da_newsletter_subscription/static/,EXT:cc_random_image/pi2/static/
1375 * @param string $title Is the title in the selector box.
1376 * @return void
1377 * @see addTypoScript()
1378 */
1379 static public function addStaticFile($extKey, $path, $title) {
1380 if ($extKey && $path && is_array($GLOBALS['TCA']['sys_template']['columns'])) {
1381 $value = str_replace(',', '', 'EXT:' . $extKey . '/' . $path);
1382 $itemArray = array(trim($title . ' (' . $extKey . ')'), $value);
1383 $GLOBALS['TCA']['sys_template']['columns']['include_static_file']['config']['items'][] = $itemArray;
1384 }
1385 }
1386
1387 /**
1388 * Adds $content to the default TypoScript setup code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_setup']
1389 * Prefixed with a [GLOBAL] line
1390 * FOR USE IN ext_localconf.php FILES
1391 *
1392 * @param string $content TypoScript Setup string
1393 * @return void
1394 */
1395 static public function addTypoScriptSetup($content) {
1396 self::appendToTypoConfVars('FE', 'defaultTypoScript_setup', '
1397 [GLOBAL]
1398 ' . $content);
1399 }
1400
1401 /**
1402 * Adds $content to the default TypoScript constants code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_constants']
1403 * Prefixed with a [GLOBAL] line
1404 * FOR USE IN ext_localconf.php FILES
1405 *
1406 * @param string $content TypoScript Constants string
1407 * @return void
1408 */
1409 static public function addTypoScriptConstants($content) {
1410 self::appendToTypoConfVars('FE', 'defaultTypoScript_constants', '
1411 [GLOBAL]
1412 ' . $content);
1413 }
1414
1415 /**
1416 * Adds $content to the default TypoScript code for either setup or constants as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_*']
1417 * (Basically this function can do the same as addTypoScriptSetup and addTypoScriptConstants - just with a little more hazzle, but also with some more options!)
1418 * FOR USE IN ext_localconf.php FILES
1419 * Note: As of TYPO3 CMS 6.2, static template #43 (content: default) was replaced with "defaultContentRendering" which makes it
1420 * possible that a first extension like css_styled_content registers a "contentRendering" template (= a template that defines default content rendering TypoScript)
1421 * by adding itself to $TYPO3_CONF_VARS[FE][contentRenderingTemplates][] = 'myext/Configuration/TypoScript'.
1422 * An extension calling addTypoScript('myext', 'setup', $typoScript, 'defaultContentRendering') will add its TypoScript directly after;
1423 * For now, "43" and "defaultContentRendering" can be used, but defaultContentRendering is more descriptive and should be used in the future
1424 *
1425 * @param string $key Is the extension key (informative only).
1426 * @param string $type Is either "setup" or "constants" and obviously determines which kind of TypoScript code we are adding.
1427 * @param string $content Is the TS content, will be prefixed with a [GLOBAL] line and a comment-header.
1428 * @param int|string $afterStaticUid Is either an integer pointing to a uid of a static_template or a string pointing to the "key" of a static_file template ([reduced extension_key]/[local path]). The points is that the TypoScript you add is included only IF that static template is included (and in that case, right after). So effectively the TypoScript you set can specifically overrule settings from those static templates.
1429 *
1430 * @return void
1431 */
1432 static public function addTypoScript($key, $type, $content, $afterStaticUid = 0) {
1433 if ($type === 'setup' || $type === 'constants') {
1434 $content = '
1435
1436 [GLOBAL]
1437 #############################################
1438 ## TypoScript added by extension "' . $key . '"
1439 #############################################
1440
1441 ' . $content;
1442 if ($afterStaticUid) {
1443 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.'][$afterStaticUid] .= $content;
1444 // If 'content (default)' is targeted (static uid 43),
1445 // the content is added after typoscript of type contentRendering, eg. css_styled_content, see EXT:frontend/TemplateService for that
1446 if ($afterStaticUid == 43 || $afterStaticUid === 'defaultContentRendering') {
1447 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.']['defaultContentRendering'] .= $content;
1448 }
1449 } else {
1450 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type] .= $content;
1451 }
1452 }
1453 }
1454
1455 /***************************************
1456 *
1457 * Internal extension management methods
1458 *
1459 ***************************************/
1460 /**
1461 * Find extension icon
1462 *
1463 * @param string $extensionPath Path to extension directory.
1464 * @param boolean $returnFullPath Return full path of file.
1465 *
1466 * @return string
1467 */
1468 static public function getExtensionIcon($extensionPath, $returnFullPath = FALSE) {
1469 $icon = '';
1470 $iconFileTypesToCheckFor = array('png', 'gif');
1471 foreach ($iconFileTypesToCheckFor as $fileType) {
1472 if (file_exists($extensionPath . 'ext_icon.' . $fileType)) {
1473 $icon = 'ext_icon.' . $fileType;
1474 break;
1475 }
1476 }
1477 return $returnFullPath ? $extensionPath . $icon : $icon;
1478 }
1479
1480 /**
1481 * Execute all ext_localconf.php files of loaded extensions.
1482 * The method implements an optionally used caching mechanism that concatenates all
1483 * ext_localconf.php files in one file.
1484 *
1485 * This is an internal method. It is only used during bootstrap and
1486 * extensions should not use it!
1487 *
1488 * @param boolean $allowCaching Whether or not to load / create concatenated cache file
1489 * @return void
1490 * @access private
1491 */
1492 static public function loadExtLocalconf($allowCaching = TRUE) {
1493 if ($allowCaching) {
1494 $cacheIdentifier = self::getExtLocalconfCacheIdentifier();
1495 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1496 $codeCache = self::getCacheManager()->getCache('cache_core');
1497 if ($codeCache->has($cacheIdentifier)) {
1498 $codeCache->requireOnce($cacheIdentifier);
1499 } else {
1500 self::loadSingleExtLocalconfFiles();
1501 self::createExtLocalconfCacheEntry();
1502 }
1503 } else {
1504 self::loadSingleExtLocalconfFiles();
1505 }
1506 }
1507
1508 /**
1509 * Execute ext_localconf.php files from extensions
1510 *
1511 * @return void
1512 */
1513 static protected function loadSingleExtLocalconfFiles() {
1514 // This is the main array meant to be manipulated in the ext_localconf.php files
1515 // In general it is recommended to not rely on it to be globally defined in that
1516 // scope but to use $GLOBALS['TYPO3_CONF_VARS'] instead.
1517 // Nevertheless we define it here as global for backwards compatibility.
1518 global $TYPO3_CONF_VARS;
1519 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1520 if ((is_array($extensionInformation) || $extensionInformation instanceof \ArrayAccess) && isset($extensionInformation['ext_localconf.php'])) {
1521 // $_EXTKEY and $_EXTCONF are available in ext_localconf.php
1522 // and are explicitly set in cached file as well
1523 $_EXTCONF = isset($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY]) ? $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY] : NULL;
1524 require $extensionInformation['ext_localconf.php'];
1525 }
1526 }
1527 }
1528
1529 /**
1530 * Create cache entry for concatenated ext_localconf.php files
1531 *
1532 * @return void
1533 */
1534 static protected function createExtLocalconfCacheEntry() {
1535 $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1536 $phpCodeToCache = array();
1537 // Set same globals as in loadSingleExtLocalconfFiles()
1538 $phpCodeToCache[] = '/**';
1539 $phpCodeToCache[] = ' * Compiled ext_localconf.php cache file';
1540 $phpCodeToCache[] = ' */';
1541 $phpCodeToCache[] = '';
1542 $phpCodeToCache[] = 'global $TYPO3_CONF_VARS, $T3_SERVICES, $T3_VAR;';
1543 $phpCodeToCache[] = '';
1544 // Iterate through loaded extensions and add ext_localconf content
1545 foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1546 if (isset($extensionDetails['ext_localconf.php']) && $extensionDetails['ext_localconf.php']) {
1547 // Include a header per extension to make the cache file more readable
1548 $phpCodeToCache[] = '/**';
1549 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1550 $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_localconf.php'];
1551 $phpCodeToCache[] = ' */';
1552 $phpCodeToCache[] = '';
1553 // Set $_EXTKEY and $_EXTCONF for this extension
1554 $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1555 $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY];';
1556 $phpCodeToCache[] = '';
1557 // Add ext_localconf.php content of extension
1558 $phpCodeToCache[] = trim(GeneralUtility::getUrl($extensionDetails['ext_localconf.php']));
1559 $phpCodeToCache[] = '';
1560 $phpCodeToCache[] = '';
1561 }
1562 }
1563 $phpCodeToCache = implode(LF, $phpCodeToCache);
1564 // Remove all start and ending php tags from content
1565 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1566 self::getCacheManager()->getCache('cache_core')->set(self::getExtLocalconfCacheIdentifier(), $phpCodeToCache);
1567 }
1568
1569 /**
1570 * Cache identifier of concatenated ext_localconf file
1571 *
1572 * @return string
1573 */
1574 static protected function getExtLocalconfCacheIdentifier() {
1575 return 'ext_localconf_' . sha1((TYPO3_version . PATH_site . 'extLocalconf'));
1576 }
1577
1578 /**
1579 * Wrapper for buildBaseTcaFromSingleFiles handling caching.
1580 *
1581 * This builds 'base' TCA that is later overloaded by ext_tables.php.
1582 *
1583 * Use a cache file if exists and caching is allowed.
1584 *
1585 * This is an internal method. It is only used during bootstrap and
1586 * extensions should not use it!
1587 *
1588 * @param boolean $allowCaching Whether or not to load / create concatenated cache file
1589 * @return void
1590 * @access private
1591 */
1592 static public function loadBaseTca($allowCaching = TRUE) {
1593 if ($allowCaching) {
1594 $cacheIdentifier = static::getBaseTcaCacheIdentifier();
1595 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1596 $codeCache = static::getCacheManager()->getCache('cache_core');
1597 if ($codeCache->has($cacheIdentifier)) {
1598 // substr is necessary, because the php frontend wraps php code around the cache value
1599 $GLOBALS['TCA'] = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
1600 } else {
1601 static::buildBaseTcaFromSingleFiles();
1602 static::emitTcaIsBeingBuiltSignal($GLOBALS['TCA']);
1603 static::createBaseTcaCacheFile();
1604 }
1605 } else {
1606 static::buildBaseTcaFromSingleFiles();
1607 }
1608 }
1609
1610 /**
1611 * Find all Configuration/TCA/* files of extensions and create base TCA from it.
1612 * The filename must be the table name in $GLOBALS['TCA'], and the content of
1613 * the file should return an array with content of a specific table.
1614 *
1615 * @return void
1616 * @see Extension core, cms, extensionmanager and others for examples.
1617 */
1618 static protected function buildBaseTcaFromSingleFiles() {
1619 $GLOBALS['TCA'] = array();
1620 foreach (self::getLoadedExtensionListArray() as $extensionName) {
1621 $tcaConfigurationDirectory = self::extPath($extensionName) . 'Configuration/TCA';
1622 if (is_dir($tcaConfigurationDirectory)) {
1623 $files = scandir($tcaConfigurationDirectory);
1624 foreach ($files as $file) {
1625 if (
1626 is_file($tcaConfigurationDirectory . '/' . $file)
1627 && ($file !== '.')
1628 && ($file !== '..')
1629 && (substr($file, -4, 4) === '.php')
1630 ) {
1631 $tcaOfTable = require($tcaConfigurationDirectory . '/' . $file);
1632 if (is_array($tcaOfTable)) {
1633 // TCA table name is filename without .php suffix, eg 'sys_notes', not 'sys_notes.php'
1634 $tcaTableName = substr($file, 0, -4);
1635 $GLOBALS['TCA'][$tcaTableName] = $tcaOfTable;
1636 }
1637 }
1638 }
1639 }
1640 }
1641 }
1642
1643 /**
1644 * Emits the signal and uses the result of slots for the final TCA
1645 * This means, that *all* slots *must* return the complete TCA to
1646 * be effective. If a slot calls methods that manipulate the global array,
1647 * it needs to return the global array in the end. To be future proof,
1648 * a slot should manipulate the signal argument only and return it
1649 * after manipulation.
1650 *
1651 * @param array $tca
1652 */
1653 static protected function emitTcaIsBeingBuiltSignal(array $tca) {
1654 list($tca) = static::getSignalSlotDispatcher()->dispatch(__CLASS__, 'tcaIsBeingBuilt', array($tca));
1655 $GLOBALS['TCA'] = $tca;
1656 }
1657
1658 /**
1659 * Cache base $GLOBALS['TCA'] to cache file to require the whole thing in one
1660 * file for next access instead of cycling through all extensions again.
1661 *
1662 * @return void
1663 */
1664 static protected function createBaseTcaCacheFile() {
1665 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1666 $codeCache = self::getCacheManager()->getCache('cache_core');
1667 $codeCache->set(static::getBaseTcaCacheIdentifier(), serialize($GLOBALS['TCA']));
1668 }
1669
1670 /**
1671 * Cache identifier of base TCA cache entry.
1672 *
1673 * @return string
1674 */
1675 static protected function getBaseTcaCacheIdentifier() {
1676 return 'tca_base_' . sha1((TYPO3_version . PATH_site . 'tca'));
1677 }
1678
1679 /**
1680 * Execute all ext_tables.php files of loaded extensions.
1681 * The method implements an optionally used caching mechanism that concatenates all
1682 * ext_tables.php files in one file.
1683 *
1684 * This is an internal method. It is only used during bootstrap and
1685 * extensions should not use it!
1686 *
1687 * @param boolean $allowCaching Whether to load / create concatenated cache file
1688 * @return void
1689 * @access private
1690 */
1691 static public function loadExtTables($allowCaching = TRUE) {
1692 if ($allowCaching && !self::$extTablesWasReadFromCacheOnce) {
1693 self::$extTablesWasReadFromCacheOnce = TRUE;
1694 $cacheIdentifier = self::getExtTablesCacheIdentifier();
1695 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1696 $codeCache = self::getCacheManager()->getCache('cache_core');
1697 if ($codeCache->has($cacheIdentifier)) {
1698 $codeCache->requireOnce($cacheIdentifier);
1699 } else {
1700 self::loadSingleExtTablesFiles();
1701 self::createExtTablesCacheEntry();
1702 }
1703 } else {
1704 self::loadSingleExtTablesFiles();
1705 }
1706 }
1707
1708 /**
1709 * Load ext_tables.php as single files
1710 *
1711 * @return void
1712 */
1713 static protected function loadSingleExtTablesFiles() {
1714 // In general it is recommended to not rely on it to be globally defined in that
1715 // scope, but we can not prohibit this without breaking backwards compatibility
1716 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
1717 global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;
1718 global $PAGES_TYPES, $TBE_STYLES, $FILEICONS;
1719 global $_EXTKEY;
1720 // Load each ext_tables.php file of loaded extensions
1721 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1722 if ((is_array($extensionInformation) || $extensionInformation instanceof \ArrayAccess) && $extensionInformation['ext_tables.php']) {
1723 // $_EXTKEY and $_EXTCONF are available in ext_tables.php
1724 // and are explicitly set in cached file as well
1725 $_EXTCONF = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY];
1726 require $extensionInformation['ext_tables.php'];
1727 static::loadNewTcaColumnsConfigFiles();
1728 }
1729 }
1730 }
1731
1732 /**
1733 * Create concatenated ext_tables.php cache file
1734 *
1735 * @return void
1736 */
1737 static protected function createExtTablesCacheEntry() {
1738 $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1739 $phpCodeToCache = array();
1740 // Set same globals as in loadSingleExtTablesFiles()
1741 $phpCodeToCache[] = '/**';
1742 $phpCodeToCache[] = ' * Compiled ext_tables.php cache file';
1743 $phpCodeToCache[] = ' */';
1744 $phpCodeToCache[] = '';
1745 $phpCodeToCache[] = 'global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;';
1746 $phpCodeToCache[] = 'global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;';
1747 $phpCodeToCache[] = 'global $PAGES_TYPES, $TBE_STYLES, $FILEICONS;';
1748 $phpCodeToCache[] = 'global $_EXTKEY;';
1749 $phpCodeToCache[] = '';
1750 // Iterate through loaded extensions and add ext_tables content
1751 foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1752 if (isset($extensionDetails['ext_tables.php']) && $extensionDetails['ext_tables.php']) {
1753 // Include a header per extension to make the cache file more readable
1754 $phpCodeToCache[] = '/**';
1755 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1756 $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_tables.php'];
1757 $phpCodeToCache[] = ' */';
1758 $phpCodeToCache[] = '';
1759 // Set $_EXTKEY and $_EXTCONF for this extension
1760 $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1761 $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY];';
1762 $phpCodeToCache[] = '';
1763 // Add ext_tables.php content of extension
1764 $phpCodeToCache[] = trim(GeneralUtility::getUrl($extensionDetails['ext_tables.php']));
1765 $phpCodeToCache[] = '';
1766 $phpCodeToCache[] = '\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::loadNewTcaColumnsConfigFiles();';
1767 $phpCodeToCache[] = '';
1768 }
1769 }
1770 $phpCodeToCache = implode(LF, $phpCodeToCache);
1771 // Remove all start and ending php tags from content
1772 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1773 self::getCacheManager()->getCache('cache_core')->set(self::getExtTablesCacheIdentifier(), $phpCodeToCache);
1774 }
1775
1776 /**
1777 * Loads "columns" of a $TCA table definition if extracted
1778 * to a "dynamicConfigFile". This method is called after each
1779 * single ext_tables.php files was included to immediately have
1780 * the full $TCA ready for the next extension.
1781 *
1782 * $TCA[$tableName]['ctrl']['dynamicConfigFile'] must be the
1783 * absolute path to a file.
1784 *
1785 * Be aware that 'dynamicConfigFile' is obsolete, and all TCA
1786 * table definitions should be moved to Configuration/TCA/tablename.php
1787 * to be fully loaded automatically.
1788 *
1789 * Example:
1790 * dynamicConfigFile = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY) . 'SysNote.php',
1791 *
1792 * @return void
1793 * @throws \RuntimeException
1794 * @internal Internal use ONLY. It is called by cache files and can not be protected. Do not call yourself!
1795 */
1796 static public function loadNewTcaColumnsConfigFiles() {
1797 global $TCA;
1798
1799 foreach (array_keys($TCA) as $tableName) {
1800 if (!isset($TCA[$tableName]['columns'])) {
1801 $columnsConfigFile = $TCA[$tableName]['ctrl']['dynamicConfigFile'];
1802 if ($columnsConfigFile) {
1803 if (GeneralUtility::isAbsPath($columnsConfigFile)) {
1804 include($columnsConfigFile);
1805 } else {
1806 throw new \RuntimeException(
1807 'Columns configuration file not found',
1808 1341151261
1809 );
1810 }
1811 }
1812 }
1813 }
1814 }
1815
1816 /**
1817 * Cache identifier for concatenated ext_tables.php files
1818 *
1819 * @return string
1820 */
1821 static protected function getExtTablesCacheIdentifier() {
1822 return 'ext_tables_' . sha1((TYPO3_version . PATH_site . 'extTables'));
1823 }
1824
1825 /**
1826 * Returns TRUE if configuration files in typo3conf/ are writable
1827 *
1828 * @return boolean TRUE if at least one configuration file in typo3conf/ is writable
1829 * @internal
1830 * @deprecated since 6.1, will be removed in two versions
1831 */
1832 static public function isLocalconfWritable() {
1833 GeneralUtility::logDeprecatedFunction();
1834 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\ConfigurationManager')
1835 ->canWriteConfiguration();
1836 }
1837
1838 /**
1839 * Remove cache files from php code cache, grouped by 'system'
1840 *
1841 * This removes the following cache entries:
1842 * - autoloader cache registry
1843 * - cache loaded extension array
1844 * - ext_localconf concatenation
1845 * - ext_tables concatenation
1846 *
1847 * This method is usually only used by extension that fiddle
1848 * with the loaded extensions. An example is the extension
1849 * manager and the install tool.
1850 *
1851 * @return void
1852 */
1853 static public function removeCacheFiles() {
1854 self::getCacheManager()->flushCachesInGroup('system');
1855 }
1856
1857 /**
1858 * Gets an array of loaded extension keys
1859 *
1860 * @return array Loaded extensions
1861 */
1862 static public function getLoadedExtensionListArray() {
1863 return array_keys(static::$packageManager->getActivePackages());
1864 }
1865
1866 /**
1867 * Returns REQUIRED_EXTENSIONS constant set by package manager as array.
1868 *
1869 * @return array List of required extensions
1870 * @deprecated since 6,2, will be removed two versions later.
1871 */
1872 static public function getRequiredExtensionListArray() {
1873 GeneralUtility::logDeprecatedFunction();
1874 return GeneralUtility::trimExplode(',', REQUIRED_EXTENSIONS);
1875 }
1876
1877 /**
1878 * Loads given extension
1879 *
1880 * Warning: This method only works if the ugrade wizard to transform
1881 * localconf.php to LocalConfiguration.php was already run
1882 *
1883 * @param string $extensionKey Extension key to load
1884 * @return void
1885 * @throws \RuntimeException
1886 */
1887 static public function loadExtension($extensionKey) {
1888 if (static::$packageManager->isPackageActive($extensionKey)) {
1889 throw new \RuntimeException('Extension already loaded', 1342345486);
1890 }
1891 static::$packageManager->activatePackage($extensionKey);
1892 }
1893
1894 /**
1895 * Unloads given extension
1896 *
1897 * Warning: This method only works if the ugrade wizard to transform
1898 * localconf.php to LocalConfiguration.php was already run
1899 *
1900 * @param string $extensionKey Extension key to remove
1901 * @return void
1902 * @throws \RuntimeException
1903 */
1904 static public function unloadExtension($extensionKey) {
1905 if (!static::$packageManager->isPackageActive($extensionKey)) {
1906 throw new \RuntimeException('Extension not loaded', 1342345487);
1907 }
1908 static::$packageManager->deactivatePackage($extensionKey);
1909 }
1910
1911 /**
1912 * Writes extension list and clear cache files.
1913 *
1914 * @TODO: This method should be protected, but with current em it is hard to do so,
1915 * @TODO: Find out if we may remove this already
1916 * @param array Extension array to load, loader order is kept
1917 * @return void
1918 * @internal
1919 * @deprecated since 6.2, will be removed two versions later
1920 */
1921 static public function writeNewExtensionList(array $newExtensionList) {
1922 GeneralUtility::logDeprecatedFunction();
1923 }
1924
1925 /**
1926 * Makes a table categorizable by adding value into the category registry.
1927 * FOR USE IN ext_localconf.php FILES.
1928 *
1929 * @param string $extensionKey Extension key to be used
1930 * @param string $tableName Name of the table to be categorized
1931 * @param string $fieldName Name of the field to be used to store categories
1932 * @param array $options Additional configuration options
1933 * @see addTCAcolumns
1934 * @see addToAllTCAtypes
1935 */
1936 static public function makeCategorizable($extensionKey, $tableName, $fieldName = 'categories', array $options = array()) {
1937 // Update the category registry
1938 $result = \TYPO3\CMS\Core\Category\CategoryRegistry::getInstance()->add($extensionKey, $tableName, $fieldName, $options);
1939 if ($result === FALSE) {
1940 $message = '\TYPO3\CMS\Core\Category\CategoryRegistry: no category registered for table "%s". Key was already registered.';
1941 /** @var $logger \TYPO3\CMS\Core\Log\Logger */
1942 $logger = GeneralUtility::makeInstance('TYPO3\CMS\Core\Log\LogManager')->getLogger(__CLASS__);
1943 $logger->warning(
1944 sprintf($message, $tableName)
1945 );
1946 }
1947 }
1948
1949 }