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