[BUGFIX] Fix several typos in php comments
[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 Symfony\Component\Finder\Finder;
18 use TYPO3\CMS\Backend\Routing\Route;
19 use TYPO3\CMS\Backend\Routing\Router;
20 use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
21 use TYPO3\CMS\Core\Category\CategoryRegistry;
22 use TYPO3\CMS\Core\Core\Environment;
23 use TYPO3\CMS\Core\Imaging\IconRegistry;
24 use TYPO3\CMS\Core\Log\LogManager;
25 use TYPO3\CMS\Core\Migrations\TcaMigration;
26 use TYPO3\CMS\Core\Package\PackageManager;
27 use TYPO3\CMS\Core\Preparations\TcaPreparation;
28
29 /**
30 * Extension Management functions
31 *
32 * This class is never instantiated, rather the methods inside is called as functions like
33 * \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('my_extension');
34 */
35 class ExtensionManagementUtility
36 {
37 /**
38 * TRUE, if ext_tables file was read from cache for this script run.
39 * The frontend tends to do that multiple times, but the caching framework does
40 * not allow this (via a require_once call). This variable is used to track
41 * the access to the cache file to read the single ext_tables.php if it was
42 * already read from cache
43 *
44 * @todo See if we can get rid of the 'load multiple times' scenario in fe
45 * @var bool
46 */
47 protected static $extTablesWasReadFromCacheOnce = false;
48
49 /**
50 * @var PackageManager
51 */
52 protected static $packageManager;
53
54 /**
55 * Sets the package manager for all that backwards compatibility stuff,
56 * so it doesn't have to be fetched through the bootstrap.
57 *
58 * @param PackageManager $packageManager
59 * @internal
60 */
61 public static function setPackageManager(PackageManager $packageManager)
62 {
63 static::$packageManager = $packageManager;
64 }
65
66 /**
67 * @var \TYPO3\CMS\Core\Cache\CacheManager
68 */
69 protected static $cacheManager;
70
71 /**
72 * Getter for the cache manager
73 *
74 * @return \TYPO3\CMS\Core\Cache\CacheManager
75 */
76 protected static function getCacheManager()
77 {
78 if (static::$cacheManager === null) {
79 static::$cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
80 }
81 return static::$cacheManager;
82 }
83
84 /**
85 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
86 */
87 protected static $signalSlotDispatcher;
88
89 /**
90 * Getter for the signal slot dispatcher
91 *
92 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
93 */
94 protected static function getSignalSlotDispatcher()
95 {
96 if (static::$signalSlotDispatcher === null) {
97 static::$signalSlotDispatcher = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class);
98 }
99 return static::$signalSlotDispatcher;
100 }
101
102 /**************************************
103 *
104 * PATHS and other evaluation
105 *
106 ***************************************/
107 /**
108 * Returns TRUE if the extension with extension key $key is loaded.
109 *
110 * @param string $key Extension key to test
111 * @return bool
112 */
113 public static function isLoaded($key)
114 {
115 return static::$packageManager->isPackageActive($key);
116 }
117
118 /**
119 * Returns the absolute path to the extension with extension key $key.
120 *
121 * @param string $key Extension key
122 * @param string $script $script is appended to the output if set.
123 * @throws \BadFunctionCallException
124 * @return string
125 */
126 public static function extPath($key, $script = '')
127 {
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 correct class name prefix for the extension key $key
136 *
137 * @param string $key Extension key
138 * @return string
139 * @internal
140 */
141 public static function getCN($key)
142 {
143 return strpos($key, 'user_') === 0 ? 'user_' . str_replace('_', '', substr($key, 5)) : 'tx_' . str_replace('_', '', $key);
144 }
145
146 /**
147 * Retrieves the version of an installed extension.
148 * If the extension is not installed, this function returns an empty string.
149 *
150 * @param string $key The key of the extension to look up, must not be empty
151 *
152 * @throws \InvalidArgumentException
153 * @throws \TYPO3\CMS\Core\Package\Exception
154 * @return string The extension version as a string in the format "x.y.z",
155 */
156 public static function getExtensionVersion($key)
157 {
158 if (!is_string($key) || empty($key)) {
159 throw new \InvalidArgumentException('Extension key must be a non-empty string.', 1294586096);
160 }
161 if (!static::isLoaded($key)) {
162 return '';
163 }
164 $version = static::$packageManager->getPackage($key)->getPackageMetaData()->getVersion();
165 if (empty($version)) {
166 throw new \TYPO3\CMS\Core\Package\Exception('Version number in composer manifest of package "' . $key . '" is missing or invalid', 1395614959);
167 }
168 return $version;
169 }
170
171 /**************************************
172 *
173 * Adding BACKEND features
174 * (related to core features)
175 *
176 ***************************************/
177 /**
178 * Adding fields to an existing table definition in $GLOBALS['TCA']
179 * Adds an array with $GLOBALS['TCA'] column-configuration to the $GLOBALS['TCA']-entry for that table.
180 * 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!
181 * So to have the fields displayed you must also call fx. addToAllTCAtypes or manually add the fields to the types list.
182 * FOR USE IN files in Configuration/TCA/Overrides/*.php . Use in ext_tables.php FILES may break the frontend.
183 *
184 * @param string $table The table name of a table already present in $GLOBALS['TCA'] with a columns section
185 * @param array $columnArray The array with the additional columns (typical some fields an extension wants to add)
186 */
187 public static function addTCAcolumns($table, $columnArray)
188 {
189 if (is_array($columnArray) && is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'])) {
190 // Candidate for array_merge() if integer-keys will some day make trouble...
191 $GLOBALS['TCA'][$table]['columns'] = array_merge($GLOBALS['TCA'][$table]['columns'], $columnArray);
192 }
193 }
194
195 /**
196 * Makes fields visible in the TCEforms, adding them to the end of (all) "types"-configurations
197 *
198 * Adds a string $string (comma separated list of field names) to all ["types"][xxx]["showitem"] entries for table $table (unless limited by $typeList)
199 * This is needed to have new fields shown automatically in the TCEFORMS of a record from $table.
200 * Typically this function is called after having added new columns (database fields) with the addTCAcolumns function
201 * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
202 *
203 * @param string $table Table name
204 * @param string $newFieldsString Field list to add.
205 * @param string $typeList List of specific types to add the field list to. (If empty, all type entries are affected)
206 * @param string $position Insert fields before (default) or after one, or replace a field
207 */
208 public static function addToAllTCAtypes($table, $newFieldsString, $typeList = '', $position = '')
209 {
210 $newFieldsString = trim($newFieldsString);
211 if ($newFieldsString === '' || !is_array($GLOBALS['TCA'][$table]['types'] ?? false)) {
212 return;
213 }
214 if ($position !== '') {
215 list($positionIdentifier, $entityName) = GeneralUtility::trimExplode(':', $position);
216 } else {
217 $positionIdentifier = '';
218 $entityName = '';
219 }
220 $palettesChanged = [];
221
222 foreach ($GLOBALS['TCA'][$table]['types'] as $type => &$typeDetails) {
223 // skip if we don't want to add the field for this type
224 if ($typeList !== '' && !GeneralUtility::inList($typeList, $type)) {
225 continue;
226 }
227 // skip if fields were already added
228 if (!isset($typeDetails['showitem'])) {
229 continue;
230 }
231
232 $fieldArray = GeneralUtility::trimExplode(',', $typeDetails['showitem'], true);
233 if (in_array($newFieldsString, $fieldArray, true)) {
234 continue;
235 }
236
237 $fieldExists = false;
238 $newPosition = '';
239 if (is_array($GLOBALS['TCA'][$table]['palettes'] ?? false)) {
240 // Get the palette names used in current showitem
241 $paletteCount = preg_match_all('/(?:^|,) # Line start or a comma
242 (?:
243 \\s*\\-\\-palette\\-\\-;[^;]*;([^,$]*)| # --palette--;label;paletteName
244 \\s*\\b[^;,]+\\b(?:;[^;]*;([^;,]+))?[^,]* # field;label;paletteName
245 )/x', $typeDetails['showitem'], $paletteMatches);
246 if ($paletteCount > 0) {
247 $paletteNames = array_filter(array_merge($paletteMatches[1], $paletteMatches[2]));
248 if (!empty($paletteNames)) {
249 foreach ($paletteNames as $paletteName) {
250 if (!isset($GLOBALS['TCA'][$table]['palettes'][$paletteName])) {
251 continue;
252 }
253 $palette = $GLOBALS['TCA'][$table]['palettes'][$paletteName];
254 switch ($positionIdentifier) {
255 case 'after':
256 case 'before':
257 if (preg_match('/\\b' . $entityName . '\\b/', $palette['showitem']) > 0) {
258 $newPosition = $positionIdentifier . ':--palette--;;' . $paletteName;
259 }
260 break;
261 case 'replace':
262 // check if fields have been added to palette before
263 if (isset($palettesChanged[$paletteName])) {
264 $fieldExists = true;
265 continue 2;
266 }
267 if (preg_match('/\\b' . $entityName . '\\b/', $palette['showitem']) > 0) {
268 self::addFieldsToPalette($table, $paletteName, $newFieldsString, $position);
269 // Memorize that we already changed this palette, in case other types also use it
270 $palettesChanged[$paletteName] = true;
271 $fieldExists = true;
272 continue 2;
273 }
274 break;
275 default:
276 // Intentionally left blank
277 }
278 }
279 }
280 }
281 }
282 if ($fieldExists === false) {
283 $typeDetails['showitem'] = self::executePositionedStringInsertion(
284 $typeDetails['showitem'],
285 $newFieldsString,
286 $newPosition !== '' ? $newPosition : $position
287 );
288 }
289 }
290 unset($typeDetails);
291 }
292
293 /**
294 * Adds new fields to all palettes that is defined after an existing field.
295 * If the field does not have a following palette yet, it's created automatically
296 * and gets called "generatedFor-$field".
297 * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
298 *
299 * See unit tests for more examples and edge cases.
300 *
301 * Example:
302 *
303 * 'aTable' => array(
304 * 'types' => array(
305 * 'aType' => array(
306 * 'showitem' => 'aField, --palette--;;aPalette',
307 * ),
308 * ),
309 * 'palettes' => array(
310 * 'aPalette' => array(
311 * 'showitem' => 'fieldB, fieldC',
312 * ),
313 * ),
314 * ),
315 *
316 * Calling addFieldsToAllPalettesOfField('aTable', 'aField', 'newA', 'before: fieldC') results in:
317 *
318 * 'aTable' => array(
319 * 'types' => array(
320 * 'aType' => array(
321 * 'showitem' => 'aField, --palette--;;aPalette',
322 * ),
323 * ),
324 * 'palettes' => array(
325 * 'aPalette' => array(
326 * 'showitem' => 'fieldB, newA, fieldC',
327 * ),
328 * ),
329 * ),
330 *
331 * @param string $table Name of the table
332 * @param string $field Name of the field that has the palette to be extended
333 * @param string $addFields List of fields to be added to the palette
334 * @param string $insertionPosition Insert fields before (default) or after one
335 */
336 public static function addFieldsToAllPalettesOfField($table, $field, $addFields, $insertionPosition = '')
337 {
338 if (!isset($GLOBALS['TCA'][$table]['columns'][$field])) {
339 return;
340 }
341 if (!is_array($GLOBALS['TCA'][$table]['types'])) {
342 return;
343 }
344
345 // Iterate through all types and search for the field that defines the palette to be extended
346 foreach ($GLOBALS['TCA'][$table]['types'] as $typeName => $typeArray) {
347 // Continue if types has no showitem at all or if requested field is not in it
348 if (!isset($typeArray['showitem']) || strpos($typeArray['showitem'], $field) === false) {
349 continue;
350 }
351 $fieldArrayWithOptions = GeneralUtility::trimExplode(',', $typeArray['showitem']);
352 // Find the field we're handling
353 $newFieldStringArray = [];
354 foreach ($fieldArrayWithOptions as $fieldNumber => $fieldString) {
355 $newFieldStringArray[] = $fieldString;
356 $fieldArray = GeneralUtility::trimExplode(';', $fieldString);
357 if ($fieldArray[0] !== $field) {
358 continue;
359 }
360 if (
361 isset($fieldArrayWithOptions[$fieldNumber + 1])
362 && strpos($fieldArrayWithOptions[$fieldNumber + 1], '--palette--') === 0
363 ) {
364 // Match for $field and next field is a palette - add fields to this one
365 $paletteName = GeneralUtility::trimExplode(';', $fieldArrayWithOptions[$fieldNumber + 1]);
366 $paletteName = $paletteName[2];
367 self::addFieldsToPalette($table, $paletteName, $addFields, $insertionPosition);
368 } else {
369 // Match for $field but next field is no palette - create a new one
370 $newPaletteName = 'generatedFor-' . $field;
371 self::addFieldsToPalette($table, 'generatedFor-' . $field, $addFields, $insertionPosition);
372 $newFieldStringArray[] = '--palette--;;' . $newPaletteName;
373 }
374 }
375 $GLOBALS['TCA'][$table]['types'][$typeName]['showitem'] = implode(', ', $newFieldStringArray);
376 }
377 }
378
379 /**
380 * Adds new fields to a palette.
381 * If the palette does not exist yet, it's created automatically.
382 * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
383 *
384 * @param string $table Name of the table
385 * @param string $palette Name of the palette to be extended
386 * @param string $addFields List of fields to be added to the palette
387 * @param string $insertionPosition Insert fields before (default) or after one
388 */
389 public static function addFieldsToPalette($table, $palette, $addFields, $insertionPosition = '')
390 {
391 if (isset($GLOBALS['TCA'][$table])) {
392 $paletteData = &$GLOBALS['TCA'][$table]['palettes'][$palette];
393 // If palette already exists, merge the data:
394 if (is_array($paletteData)) {
395 $paletteData['showitem'] = self::executePositionedStringInsertion($paletteData['showitem'], $addFields, $insertionPosition);
396 } else {
397 $paletteData['showitem'] = self::removeDuplicatesForInsertion($addFields);
398 }
399 }
400 }
401
402 /**
403 * Add an item to a select field item list.
404 *
405 * Warning: Do not use this method for radio or check types, especially not
406 * with $relativeToField and $relativePosition parameters. This would shift
407 * existing database data 'off by one'.
408 * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
409 *
410 * As an example, this can be used to add an item to tt_content CType select
411 * drop-down after the existing 'mailform' field with these parameters:
412 * - $table = 'tt_content'
413 * - $field = 'CType'
414 * - $item = array(
415 * 'LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:CType.I.10',
416 * 'login',
417 * 'i/imagename.gif',
418 * ),
419 * - $relativeToField = mailform
420 * - $relativePosition = after
421 *
422 * @throws \InvalidArgumentException If given parameters are not of correct
423 * @throws \RuntimeException If reference to related position fields can not
424 * @param string $table Name of TCA table
425 * @param string $field Name of TCA field
426 * @param array $item New item to add
427 * @param string $relativeToField Add item relative to existing field
428 * @param string $relativePosition Valid keywords: 'before', 'after'
429 */
430 public static function addTcaSelectItem($table, $field, array $item, $relativeToField = '', $relativePosition = '')
431 {
432 if (!is_string($table)) {
433 throw new \InvalidArgumentException('Given table is of type "' . gettype($table) . '" but a string is expected.', 1303236963);
434 }
435 if (!is_string($field)) {
436 throw new \InvalidArgumentException('Given field is of type "' . gettype($field) . '" but a string is expected.', 1303236964);
437 }
438 if (!is_string($relativeToField)) {
439 throw new \InvalidArgumentException('Given relative field is of type "' . gettype($relativeToField) . '" but a string is expected.', 1303236965);
440 }
441 if (!is_string($relativePosition)) {
442 throw new \InvalidArgumentException('Given relative position is of type "' . gettype($relativePosition) . '" but a string is expected.', 1303236966);
443 }
444 if ($relativePosition !== '' && $relativePosition !== 'before' && $relativePosition !== 'after' && $relativePosition !== 'replace') {
445 throw new \InvalidArgumentException('Relative position must be either empty or one of "before", "after", "replace".', 1303236967);
446 }
447 if (!isset($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'])
448 || !is_array($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'])
449 ) {
450 throw new \RuntimeException('Given select field item list was not found.', 1303237468);
451 }
452 // Make sure item keys are integers
453 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'] = array_values($GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
454 if ($relativePosition !== '') {
455 // Insert at specified position
456 $matchedPosition = ArrayUtility::filterByValueRecursive($relativeToField, $GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
457 if (!empty($matchedPosition)) {
458 $relativeItemKey = key($matchedPosition);
459 if ($relativePosition === 'replace') {
460 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][$relativeItemKey] = $item;
461 } else {
462 if ($relativePosition === 'before') {
463 $offset = $relativeItemKey;
464 } else {
465 $offset = $relativeItemKey + 1;
466 }
467 array_splice($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'], $offset, 0, [0 => $item]);
468 }
469 } else {
470 // Insert at new item at the end of the array if relative position was not found
471 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
472 }
473 } else {
474 // Insert at new item at the end of the array
475 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
476 }
477 }
478
479 /**
480 * Gets the TCA configuration for a field handling (FAL) files.
481 *
482 * @param string $fieldName Name of the field to be used
483 * @param array $customSettingOverride Custom field settings overriding the basics
484 * @param string $allowedFileExtensions Comma list of allowed file extensions (e.g. "jpg,gif,pdf")
485 * @param string $disallowedFileExtensions
486 *
487 * @return array
488 */
489 public static function getFileFieldTCAConfig($fieldName, array $customSettingOverride = [], $allowedFileExtensions = '', $disallowedFileExtensions = '')
490 {
491 $fileFieldTCAConfig = [
492 'type' => 'inline',
493 'foreign_table' => 'sys_file_reference',
494 'foreign_field' => 'uid_foreign',
495 'foreign_sortby' => 'sorting_foreign',
496 'foreign_table_field' => 'tablenames',
497 'foreign_match_fields' => [
498 'fieldname' => $fieldName
499 ],
500 'foreign_label' => 'uid_local',
501 'foreign_selector' => 'uid_local',
502 'overrideChildTca' => [
503 'columns' => [
504 'uid_local' => [
505 'config' => [
506 'appearance' => [
507 'elementBrowserType' => 'file',
508 'elementBrowserAllowed' => $allowedFileExtensions
509 ],
510 ],
511 ],
512 ],
513 ],
514 'filter' => [
515 [
516 'userFunc' => \TYPO3\CMS\Core\Resource\Filter\FileExtensionFilter::class . '->filterInlineChildren',
517 'parameters' => [
518 'allowedFileExtensions' => $allowedFileExtensions,
519 'disallowedFileExtensions' => $disallowedFileExtensions
520 ]
521 ]
522 ],
523 'appearance' => [
524 'useSortable' => true,
525 'headerThumbnail' => [
526 'field' => 'uid_local',
527 'width' => '45',
528 'height' => '45c',
529 ],
530
531 'enabledControls' => [
532 'info' => true,
533 'new' => false,
534 'dragdrop' => true,
535 'sort' => false,
536 'hide' => true,
537 'delete' => true,
538 ],
539 ]
540 ];
541 ArrayUtility::mergeRecursiveWithOverrule($fileFieldTCAConfig, $customSettingOverride);
542 return $fileFieldTCAConfig;
543 }
544
545 /**
546 * Adds a list of new fields to the TYPO3 USER SETTINGS configuration "showitem" list, the array with
547 * the new fields itself needs to be added additionally to show up in the user setup, like
548 * $GLOBALS['TYPO3_USER_SETTINGS']['columns'] += $tempColumns
549 *
550 * @param string $addFields List of fields to be added to the user settings
551 * @param string $insertionPosition Insert fields before (default) or after one
552 */
553 public static function addFieldsToUserSettings($addFields, $insertionPosition = '')
554 {
555 $GLOBALS['TYPO3_USER_SETTINGS']['showitem'] = self::executePositionedStringInsertion($GLOBALS['TYPO3_USER_SETTINGS']['showitem'], $addFields, $insertionPosition);
556 }
557
558 /**
559 * Inserts as list of data into an existing list.
560 * The insertion position can be defined accordant before of after existing list items.
561 *
562 * Example:
563 * + list: 'field_a, field_b, field_c'
564 * + insertionList: 'field_d, field_e'
565 * + insertionPosition: 'after:field_b'
566 * -> 'field_a, field_b, field_d, field_e, field_c'
567 *
568 * $insertPosition may contain ; and - characters: after:--palette--;;title
569 *
570 * @param string $list The list of items to be extended
571 * @param string $insertionList The list of items to inserted
572 * @param string $insertionPosition Insert fields before (default) or after one
573 * @return string The extended list
574 */
575 protected static function executePositionedStringInsertion($list, $insertionList, $insertionPosition = '')
576 {
577 $list = $newList = trim($list, ", \t\n\r\0\x0B");
578
579 if ($insertionPosition !== '') {
580 list($location, $positionName) = GeneralUtility::trimExplode(':', $insertionPosition, false, 2);
581 } else {
582 $location = '';
583 $positionName = '';
584 }
585
586 if ($location !== 'replace') {
587 $insertionList = self::removeDuplicatesForInsertion($insertionList, $list);
588 }
589
590 if ($insertionList === '') {
591 return $list;
592 }
593 if ($list === '') {
594 return $insertionList;
595 }
596 if ($insertionPosition === '') {
597 return $list . ', ' . $insertionList;
598 }
599
600 // The $insertPosition may be a palette: after:--palette--;;title
601 // In the $list the palette may contain a LLL string in between the ;;
602 // Adjust the regex to match that
603 $positionName = preg_quote($positionName, '/');
604 if (strpos($positionName, ';;') !== false) {
605 $positionName = str_replace(';;', ';[^;]*;', $positionName);
606 }
607
608 $pattern = ('/(^|,\\s*)(' . $positionName . ')(;[^,$]+)?(,|$)/');
609 switch ($location) {
610 case 'after':
611 $newList = preg_replace($pattern, '$1$2$3, ' . $insertionList . '$4', $list);
612 break;
613 case 'before':
614 $newList = preg_replace($pattern, '$1' . $insertionList . ', $2$3$4', $list);
615 break;
616 case 'replace':
617 $newList = preg_replace($pattern, '$1' . $insertionList . '$4', $list);
618 break;
619 default:
620 }
621
622 // When preg_replace did not replace anything; append the $insertionList.
623 if ($list === $newList) {
624 return $list . ', ' . $insertionList;
625 }
626 return $newList;
627 }
628
629 /**
630 * Compares an existing list of items and a list of items to be inserted
631 * and returns a duplicate-free variant of that insertion list.
632 *
633 * Example:
634 * + list: 'field_a, field_b, field_c'
635 * + insertion: 'field_b, field_d, field_c'
636 * -> new insertion: 'field_d'
637 *
638 * Duplicate values in $insertionList are removed.
639 *
640 * @param string $insertionList The list of items to inserted
641 * @param string $list The list of items to be extended (default: '')
642 * @return string Duplicate-free list of items to be inserted
643 */
644 protected static function removeDuplicatesForInsertion($insertionList, $list = '')
645 {
646 $insertionListParts = preg_split('/\\s*,\\s*/', $insertionList);
647 $listMatches = [];
648 if ($list !== '') {
649 preg_match_all('/(?:^|,)\\s*\\b([^;,]+)\\b[^,]*/', $list, $listMatches);
650 $listMatches = $listMatches[1];
651 }
652
653 $cleanInsertionListParts = [];
654 foreach ($insertionListParts as $fieldName) {
655 $fieldNameParts = explode(';', $fieldName, 2);
656 $cleanFieldName = $fieldNameParts[0];
657 if (
658 $cleanFieldName === '--linebreak--'
659 || (
660 !in_array($cleanFieldName, $cleanInsertionListParts, true)
661 && !in_array($cleanFieldName, $listMatches, true)
662 )
663 ) {
664 $cleanInsertionListParts[] = $fieldName;
665 }
666 }
667 return implode(', ', $cleanInsertionListParts);
668 }
669
670 /**
671 * Generates an array of fields/items with additional information such as e.g. the name of the palette.
672 *
673 * @param string $itemList List of fields/items to be splitted up
674 * @return array An array with the names of the fields/items as keys and additional information
675 */
676 protected static function explodeItemList($itemList)
677 {
678 $items = [];
679 $itemParts = GeneralUtility::trimExplode(',', $itemList, true);
680 foreach ($itemParts as $itemPart) {
681 $itemDetails = GeneralUtility::trimExplode(';', $itemPart, false, 5);
682 $key = $itemDetails[0];
683 if (strpos($key, '--') !== false) {
684 // 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!
685 $key .= count($items);
686 }
687 if (!isset($items[$key])) {
688 $items[$key] = [
689 'rawData' => $itemPart,
690 'details' => []
691 ];
692 $details = [0 => 'field', 1 => 'label', 2 => 'palette'];
693 foreach ($details as $id => $property) {
694 $items[$key]['details'][$property] = $itemDetails[$id] ?? '';
695 }
696 }
697 }
698 return $items;
699 }
700
701 /**
702 * Generates a list of fields/items out of an array provided by the function getFieldsOfFieldList().
703 *
704 * @see explodeItemList
705 * @param array $items The array of fields/items with optional additional information
706 * @param bool $useRawData Use raw data instead of building by using the details (default: FALSE)
707 * @return string The list of fields/items which gets used for $GLOBALS['TCA'][<table>]['types'][<type>]['showitem']
708 */
709 protected static function generateItemList(array $items, $useRawData = false)
710 {
711 $itemParts = [];
712 foreach ($items as $item => $itemDetails) {
713 if (strpos($item, '--') !== false) {
714 // 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.
715 $item = str_replace([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], '', $item);
716 }
717 if ($useRawData) {
718 $itemParts[] = $itemDetails['rawData'];
719 } else {
720 if (count($itemDetails['details']) > 1) {
721 $details = ['palette', 'label', 'field'];
722 $elements = [];
723 $addEmpty = false;
724 foreach ($details as $property) {
725 if ($itemDetails['details'][$property] !== '' || $addEmpty) {
726 $addEmpty = true;
727 array_unshift($elements, $itemDetails['details'][$property]);
728 }
729 }
730 $item = implode(';', $elements);
731 }
732 $itemParts[] = $item;
733 }
734 }
735 return implode(', ', $itemParts);
736 }
737
738 /**
739 * Add tablename to default list of allowed tables on pages (in $PAGES_TYPES)
740 * Will add the $table to the list of tables allowed by default on pages as setup by $PAGES_TYPES['default']['allowedTables']
741 * FOR USE IN ext_tables.php FILES
742 *
743 * @param string $table Table name
744 */
745 public static function allowTableOnStandardPages($table)
746 {
747 $GLOBALS['PAGES_TYPES']['default']['allowedTables'] .= ',' . $table;
748 }
749
750 /**
751 * Adds a module (main or sub) to the backend interface
752 * FOR USE IN ext_tables.php FILES
753 *
754 * @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.
755 * @param string $sub The submodule key. If $sub is not set a blank $main module is created.
756 * @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.
757 * @param string $path The absolute path to the module. Was used prior to TYPO3 v8, use $moduleConfiguration[routeTarget] now
758 * @param array $moduleConfiguration additional configuration, previously put in "conf.php" of the module directory
759 */
760 public static function addModule($main, $sub = '', $position = '', $path = null, $moduleConfiguration = [])
761 {
762 // If there is already a main module by this name:
763 // Adding the submodule to the correct position:
764 if (isset($GLOBALS['TBE_MODULES'][$main]) && $sub) {
765 list($place, $modRef) = array_pad(GeneralUtility::trimExplode(':', $position, true), 2, null);
766 $modules = ',' . $GLOBALS['TBE_MODULES'][$main] . ',';
767 if ($place === null || ($modRef !== null && !GeneralUtility::inList($modules, $modRef))) {
768 $place = 'bottom';
769 }
770 $modRef = ',' . $modRef . ',';
771 if (!GeneralUtility::inList($modules, $sub)) {
772 switch (strtolower($place)) {
773 case 'after':
774 $modules = str_replace($modRef, $modRef . $sub . ',', $modules);
775 break;
776 case 'before':
777 $modules = str_replace($modRef, ',' . $sub . $modRef, $modules);
778 break;
779 case 'top':
780 $modules = $sub . $modules;
781 break;
782 case 'bottom':
783 default:
784 $modules = $modules . $sub;
785 }
786 }
787 // Re-inserting the submodule list:
788 $GLOBALS['TBE_MODULES'][$main] = trim($modules, ',');
789 } else {
790 // Create new main modules with only one submodule, $sub (or none if $sub is blank)
791 $GLOBALS['TBE_MODULES'][$main] = $sub;
792 }
793
794 // add additional configuration
795 $fullModuleSignature = $main . ($sub ? '_' . $sub : '');
796 if (is_array($moduleConfiguration) && !empty($moduleConfiguration)) {
797 if (!empty($moduleConfiguration['icon'])) {
798 $iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
799 $iconIdentifier = 'module-' . $fullModuleSignature;
800 $iconProvider = $iconRegistry->detectIconProvider($moduleConfiguration['icon']);
801 $iconRegistry->registerIcon(
802 $iconIdentifier,
803 $iconProvider,
804 ['source' => GeneralUtility::getFileAbsFileName($moduleConfiguration['icon'])]
805 );
806 $moduleConfiguration['iconIdentifier'] = $iconIdentifier;
807 unset($moduleConfiguration['icon']);
808 }
809
810 $GLOBALS['TBE_MODULES']['_configuration'][$fullModuleSignature] = $moduleConfiguration;
811 }
812
813 // Also register the module as regular route
814 $routeName = $moduleConfiguration['id'] ?? $fullModuleSignature;
815 // Build Route objects from the data
816 if (!empty($moduleConfiguration['path'])) {
817 $path = $moduleConfiguration['path'];
818 $path = '/' . ltrim($path, '/');
819 } else {
820 $path = str_replace('_', '/', $fullModuleSignature);
821 $path = trim($path, '/');
822 $legacyPath = '/' . $path . '/';
823 $path = '/module/' . $path;
824 }
825
826 $options = [
827 'module' => true,
828 'moduleName' => $fullModuleSignature,
829 'access' => !empty($moduleConfiguration['access']) ? $moduleConfiguration['access'] : 'user,group'
830 ];
831 if (!empty($moduleConfiguration['routeTarget'])) {
832 $options['target'] = $moduleConfiguration['routeTarget'];
833 }
834
835 $router = GeneralUtility::makeInstance(Router::class);
836 $router->addRoute($routeName, GeneralUtility::makeInstance(Route::class, $path, $options));
837 // bridge to allow to access old name like "/web/ts/" instead of "/module/web/ts/"
838 // @deprecated since TYPO3 v10.0, will be removed in TYPO3 v11.0.
839 if (!empty($legacyPath)) {
840 $router->addRoute('_legacyroutetomodule_' . $routeName, GeneralUtility::makeInstance(Route::class, $legacyPath, $options));
841 }
842 }
843
844 /**
845 * Adds a "Function menu module" ('third level module') to an existing function menu for some other backend module
846 * The arguments values are generally determined by which function menu this is supposed to interact with
847 * See Inside TYPO3 for information on how to use this function.
848 * FOR USE IN ext_tables.php FILES
849 *
850 * @param string $modname Module name
851 * @param string $className Class name
852 * @param string $_ unused
853 * @param string $title Title of module
854 * @param string $MM_key Menu array key - default is "function
855 * @param string $WS Workspace conditions. Blank means all workspaces, any other string can be a comma list of "online", "offline" and "custom
856 */
857 public static function insertModuleFunction($modname, $className, $_ = null, $title, $MM_key = 'function', $WS = '')
858 {
859 $GLOBALS['TBE_MODULES_EXT'][$modname]['MOD_MENU'][$MM_key][$className] = [
860 'name' => $className,
861 'title' => $title,
862 'ws' => $WS
863 ];
864 }
865
866 /**
867 * Adds $content to the default Page TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultPageTSconfig']
868 * Prefixed with a [GLOBAL] line
869 * FOR USE IN ext_localconf.php FILE
870 *
871 * @param string $content Page TSconfig content
872 */
873 public static function addPageTSConfig($content)
874 {
875 $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'] .= '
876 [GLOBAL]
877 ' . $content;
878 }
879
880 /**
881 * Adds $content to the default User TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultUserTSconfig']
882 * Prefixed with a [GLOBAL] line
883 * FOR USE IN ext_localconf.php FILE
884 *
885 * @param string $content User TSconfig content
886 */
887 public static function addUserTSConfig($content)
888 {
889 $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'] .= '
890 [GLOBAL]
891 ' . $content;
892 }
893
894 /**
895 * Adds a reference to a locallang file with $GLOBALS['TCA_DESCR'] labels
896 * FOR USE IN ext_tables.php FILES
897 * eg. \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addLLrefForTCAdescr('pages', 'EXT:core/Resources/Private/Language/locallang_csh_pages.xlf'); for the pages table or \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addLLrefForTCAdescr('_MOD_web_layout', 'EXT:frontend/Resources/Private/Language/locallang_csh_weblayout.xlf'); for the Web > Page module.
898 *
899 * @param string $key Description key. Typically a database table (like "pages") but for applications can be other strings, but prefixed with "_MOD_")
900 * @param string $file File reference to locallang file, eg. "EXT:core/Resources/Private/Language/locallang_csh_pages.xlf" (or ".xml")
901 */
902 public static function addLLrefForTCAdescr($key, $file)
903 {
904 if (empty($key)) {
905 throw new \RuntimeException('No description key set in addLLrefForTCAdescr(). Provide it as first parameter', 1507321596);
906 }
907 if (!is_array($GLOBALS['TCA_DESCR'][$key] ?? false)) {
908 $GLOBALS['TCA_DESCR'][$key] = [];
909 }
910 if (!is_array($GLOBALS['TCA_DESCR'][$key]['refs'] ?? false)) {
911 $GLOBALS['TCA_DESCR'][$key]['refs'] = [];
912 }
913 $GLOBALS['TCA_DESCR'][$key]['refs'][] = $file;
914 }
915
916 /**
917 * Registers a navigation component e.g. page tree
918 *
919 * @param string $module
920 * @param string $componentId componentId is also a RequireJS module name e.g. 'TYPO3/CMS/MyExt/MyNavComponent'
921 * @param string $extensionKey
922 * @throws \RuntimeException
923 */
924 public static function addNavigationComponent($module, $componentId, $extensionKey)
925 {
926 if (empty($extensionKey)) {
927 throw new \RuntimeException('No extensionKey set in addNavigationComponent(). Provide it as third parameter', 1404068039);
928 }
929 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module] = [
930 'componentId' => $componentId,
931 'extKey' => $extensionKey,
932 'isCoreComponent' => false
933 ];
934 }
935
936 /**
937 * Registers a core navigation component
938 *
939 * @param string $module
940 * @param string $componentId
941 */
942 public static function addCoreNavigationComponent($module, $componentId)
943 {
944 self::addNavigationComponent($module, $componentId, 'core');
945 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module]['isCoreComponent'] = true;
946 }
947
948 /**************************************
949 *
950 * Adding SERVICES features
951 *
952 ***************************************/
953 /**
954 * Adds a service to the global services array
955 *
956 * @param string $extKey Extension key
957 * @param string $serviceType Service type, must not be prefixed "tx_" or "Tx_"
958 * @param string $serviceKey Service key, must be prefixed "tx_", "Tx_" or "user_"
959 * @param array $info Service description array
960 */
961 public static function addService($extKey, $serviceType, $serviceKey, $info)
962 {
963 if (!$serviceType) {
964 throw new \InvalidArgumentException('No serviceType given.', 1507321535);
965 }
966 if (!is_array($info)) {
967 throw new \InvalidArgumentException('No information array given.', 1507321542);
968 }
969 $info['priority'] = max(0, min(100, $info['priority']));
970 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = $info;
971 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['extKey'] = $extKey;
972 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceKey'] = $serviceKey;
973 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceType'] = $serviceType;
974 // Change the priority (and other values) from $GLOBALS['TYPO3_CONF_VARS']
975 // $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]['priority']
976 // even the activation is possible (a unix service might be possible on windows for some reasons)
977 if (is_array($GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey] ?? false)) {
978 // No check is done here - there might be configuration values only the service type knows about, so
979 // we pass everything
980 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = array_merge($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey], $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]);
981 }
982 // OS check
983 // Empty $os means 'not limited to one OS', therefore a check is not needed
984 if ($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] && $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os'] != '') {
985 $os_type = Environment::isWindows() ? 'WIN' : 'UNIX';
986 $os = GeneralUtility::trimExplode(',', strtoupper($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os']));
987 if (!in_array($os_type, $os, true)) {
988 self::deactivateService($serviceType, $serviceKey);
989 }
990 }
991 // Convert subtype list to array for quicker access
992 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'] = [];
993 $serviceSubTypes = GeneralUtility::trimExplode(',', $info['subtype']);
994 foreach ($serviceSubTypes as $subtype) {
995 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'][$subtype] = $subtype;
996 }
997 }
998
999 /**
1000 * Find the available service with highest priority
1001 *
1002 * @param string $serviceType Service type
1003 * @param string $serviceSubType Service sub type
1004 * @param mixed $excludeServiceKeys Service keys that should be excluded in the search for a service. Array or comma list.
1005 * @return mixed Service info array if a service was found, FALSE otherwise
1006 */
1007 public static function findService($serviceType, $serviceSubType = '', $excludeServiceKeys = [])
1008 {
1009 $serviceKey = false;
1010 $serviceInfo = false;
1011 $priority = 0;
1012 $quality = 0;
1013 if (!is_array($excludeServiceKeys)) {
1014 $excludeServiceKeys = GeneralUtility::trimExplode(',', $excludeServiceKeys, true);
1015 }
1016 if (is_array($GLOBALS['T3_SERVICES'][$serviceType])) {
1017 foreach ($GLOBALS['T3_SERVICES'][$serviceType] as $key => $info) {
1018 if (in_array($key, $excludeServiceKeys)) {
1019 continue;
1020 }
1021 // Select a subtype randomly
1022 // Useful to start a service by service key without knowing his subtypes - for testing purposes
1023 if ($serviceSubType === '*') {
1024 $serviceSubType = key($info['serviceSubTypes']);
1025 }
1026 // This matches empty subtype too
1027 if ($info['available'] && ($info['subtype'] == $serviceSubType || $info['serviceSubTypes'][$serviceSubType]) && $info['priority'] >= $priority) {
1028 // Has a lower quality than the already found, therefore we skip this service
1029 if ($info['priority'] == $priority && $info['quality'] < $quality) {
1030 continue;
1031 }
1032 // Check if the service is available
1033 $info['available'] = self::isServiceAvailable($serviceType, $key, $info);
1034 // Still available after exec check?
1035 if ($info['available']) {
1036 $serviceKey = $key;
1037 $priority = $info['priority'];
1038 $quality = $info['quality'];
1039 }
1040 }
1041 }
1042 }
1043 if ($serviceKey) {
1044 $serviceInfo = $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey];
1045 }
1046 return $serviceInfo;
1047 }
1048
1049 /**
1050 * Find a specific service identified by its key
1051 * Note that this completely bypasses the notions of priority and quality
1052 *
1053 * @param string $serviceKey Service key
1054 * @return array Service info array if a service was found
1055 * @throws \TYPO3\CMS\Core\Exception
1056 */
1057 public static function findServiceByKey($serviceKey)
1058 {
1059 if (is_array($GLOBALS['T3_SERVICES'])) {
1060 // Loop on all service types
1061 // NOTE: we don't care about the actual type, we are looking for a specific key
1062 foreach ($GLOBALS['T3_SERVICES'] as $serviceType => $servicesPerType) {
1063 if (isset($servicesPerType[$serviceKey])) {
1064 $serviceDetails = $servicesPerType[$serviceKey];
1065 // Test if service is available
1066 if (self::isServiceAvailable($serviceType, $serviceKey, $serviceDetails)) {
1067 // We have found the right service, return its information
1068 return $serviceDetails;
1069 }
1070 }
1071 }
1072 }
1073 throw new \TYPO3\CMS\Core\Exception('Service not found for key: ' . $serviceKey, 1319217244);
1074 }
1075
1076 /**
1077 * Check if a given service is available, based on the executable files it depends on
1078 *
1079 * @param string $serviceType Type of service
1080 * @param string $serviceKey Specific key of the service
1081 * @param array $serviceDetails Information about the service
1082 * @return bool Service availability
1083 */
1084 public static function isServiceAvailable($serviceType, $serviceKey, $serviceDetails)
1085 {
1086 // If the service depends on external programs - check if they exists
1087 if (trim($serviceDetails['exec'])) {
1088 $executables = GeneralUtility::trimExplode(',', $serviceDetails['exec'], true);
1089 foreach ($executables as $executable) {
1090 // If at least one executable file is not available, exit early returning FALSE
1091 if (!CommandUtility::checkCommand($executable)) {
1092 self::deactivateService($serviceType, $serviceKey);
1093 return false;
1094 }
1095 }
1096 }
1097 // The service is available
1098 return true;
1099 }
1100
1101 /**
1102 * Deactivate a service
1103 *
1104 * @param string $serviceType Service type
1105 * @param string $serviceKey Service key
1106 */
1107 public static function deactivateService($serviceType, $serviceKey)
1108 {
1109 // ... maybe it's better to move non-available services to a different array??
1110 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] = false;
1111 }
1112
1113 /**************************************
1114 *
1115 * Adding FRONTEND features
1116 *
1117 ***************************************/
1118 /**
1119 * Adds an entry to the list of plugins in content elements of type "Insert plugin"
1120 * 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)
1121 * 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.
1122 * 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
1123 * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
1124 *
1125 * @param array $itemArray Numerical array: [0] => Plugin label, [1] => Underscored extension key, [2] => Path to plugin icon relative to TYPO3_mainDir
1126 * @param string $type Type (eg. "list_type") - basically a field from "tt_content" table
1127 * @param string $extensionKey The extension key
1128 * @throws \RuntimeException
1129 */
1130 public static function addPlugin($itemArray, $type = 'list_type', $extensionKey = null)
1131 {
1132 if (!isset($extensionKey)) {
1133 throw new \InvalidArgumentException(
1134 'No extension key could be determined when calling addPlugin()!'
1135 . LF
1136 . 'This method is meant to be called from Configuration/TCA/Overrides files. '
1137 . 'The extension key needs to be specified as third parameter. '
1138 . 'Calling it from any other place e.g. ext_localconf.php does not work and is not supported.',
1139 1404068038
1140 );
1141 }
1142 if (!isset($itemArray[2]) || !$itemArray[2]) {
1143 // @todo do we really set $itemArray[2], even if we cannot find an icon? (as that means it's set to 'EXT:foobar/')
1144 $itemArray[2] = 'EXT:' . $extensionKey . '/' . static::getExtensionIcon(static::$packageManager->getPackage($extensionKey)->getPackagePath());
1145 }
1146 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'])) {
1147 foreach ($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'] as $k => $v) {
1148 if ((string)$v[1] === (string)$itemArray[1]) {
1149 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][$k] = $itemArray;
1150 return;
1151 }
1152 }
1153 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][] = $itemArray;
1154 }
1155 }
1156
1157 /**
1158 * Adds an entry to the "ds" array of the tt_content field "pi_flexform".
1159 * This is used by plugins to add a flexform XML reference / content for use when they are selected as plugin or content element.
1160 * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
1161 *
1162 * @param string $piKeyToMatch Plugin key as used in the list_type field. Use the asterisk * to match all list_type values.
1163 * @param string $value Either a reference to a flex-form XML file (eg. "FILE:EXT:newloginbox/flexform_ds.xml") or the XML directly.
1164 * @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.
1165 * @see addPlugin()
1166 */
1167 public static function addPiFlexFormValue($piKeyToMatch, $value, $CTypeToMatch = 'list')
1168 {
1169 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'])) {
1170 $GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'][$piKeyToMatch . ',' . $CTypeToMatch] = $value;
1171 }
1172 }
1173
1174 /**
1175 * Adds the $table tablename to the list of tables allowed to be includes by content element type "Insert records"
1176 * By using $content_table and $content_field you can also use the function for other tables.
1177 * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
1178 *
1179 * @param string $table Table name to allow for "insert record
1180 * @param string $content_table Table name TO WHICH the $table name is applied. See $content_field as well.
1181 * @param string $content_field Field name in the database $content_table in which $table is allowed to be added as a reference ("Insert Record")
1182 */
1183 public static function addToInsertRecords($table, $content_table = 'tt_content', $content_field = 'records')
1184 {
1185 if (is_array($GLOBALS['TCA'][$content_table]['columns']) && isset($GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'])) {
1186 $GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'] .= ',' . $table;
1187 }
1188 }
1189
1190 /**
1191 * Add PlugIn to the default template rendering (previously called "Static Template #43")
1192 *
1193 * 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.
1194 *
1195 * The naming of #43 has historic reason and is rooted inside code which is now put into a TER extension called
1196 * "statictemplates". Since the static template with uid 43 is the "content.default" and practically always used
1197 * for rendering the content elements it's very useful to have this function automatically adding the necessary
1198 * TypoScript for calling your plugin.
1199 * The logic is now generalized and called "defaultContentRendering", see addTypoScript() as well.
1200 *
1201 * $type determines the type of frontend plugin:
1202 * + list_type (default) - the good old "Insert plugin" entry
1203 * + menu_type - a "Menu/Sitemap" entry
1204 * + CType - a new content element type
1205 * + header_layout - an additional header type (added to the selection of layout1-5)
1206 * + includeLib - just includes the library for manual use somewhere in TypoScript.
1207 * (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)
1208 * FOR USE IN ext_localconf.php FILES
1209 *
1210 * @param string $key The extension key
1211 * @param string $_ unused since TYPO3 CMS 8
1212 * @param string $suffix Is used as a suffix of the class name (e.g. "_pi1")
1213 * @param string $type See description above
1214 * @param bool $cacheable If $cached is set as USER content object (cObject) is created - otherwise a USER_INT object is created.
1215 */
1216 public static function addPItoST43($key, $_ = '', $suffix = '', $type = 'list_type', $cacheable = false)
1217 {
1218 $cN = self::getCN($key);
1219 // General plugin
1220 $pluginContent = trim('
1221 plugin.' . $cN . $suffix . ' = USER' . ($cacheable ? '' : '_INT') . '
1222 plugin.' . $cN . $suffix . '.userFunc = ' . $cN . $suffix . '->main
1223 ');
1224 self::addTypoScript($key, 'setup', '
1225 # Setting ' . $key . ' plugin TypoScript
1226 ' . $pluginContent);
1227 // Add after defaultContentRendering
1228 switch ($type) {
1229 case 'list_type':
1230 $addLine = 'tt_content.list.20.' . $key . $suffix . ' = < plugin.' . $cN . $suffix;
1231 break;
1232 case 'menu_type':
1233 $addLine = 'tt_content.menu.20.' . $key . $suffix . ' = < plugin.' . $cN . $suffix;
1234 break;
1235 case 'CType':
1236 $addLine = trim('
1237 tt_content.' . $key . $suffix . ' =< lib.contentElement
1238 tt_content.' . $key . $suffix . ' {
1239 templateName = Generic
1240 20 =< plugin.' . $cN . $suffix . '
1241 }
1242 ');
1243 break;
1244 case 'header_layout':
1245 $addLine = 'lib.stdheader.10.' . $key . $suffix . ' = < plugin.' . $cN . $suffix;
1246 break;
1247 case 'includeLib':
1248 $addLine = 'page.1000 = < plugin.' . $cN . $suffix;
1249 break;
1250 default:
1251 $addLine = '';
1252 }
1253 if ($addLine) {
1254 self::addTypoScript($key, 'setup', '
1255 # Setting ' . $key . ' plugin TypoScript
1256 ' . $addLine . '
1257 ', 'defaultContentRendering');
1258 }
1259 }
1260
1261 /**
1262 * Call this method to add an entry in the static template list found in sys_templates
1263 * FOR USE IN Configuration/TCA/Overrides/sys_template.php Use in ext_tables.php may break the frontend.
1264 *
1265 * @param string $extKey Is of course the extension key
1266 * @param string $path Is the path where the template files (fixed names) include_static.txt, 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:fluid_styled_content/Configuration/TypoScript/,EXT:da_newsletter_subscription/static/,EXT:cc_random_image/pi2/static/
1267 * @param string $title Is the title in the selector box.
1268 * @throws \InvalidArgumentException
1269 * @see addTypoScript()
1270 */
1271 public static function addStaticFile($extKey, $path, $title)
1272 {
1273 if (!$extKey) {
1274 throw new \InvalidArgumentException('No extension key given.', 1507321291);
1275 }
1276 if (!$path) {
1277 throw new \InvalidArgumentException('No file path given.', 1507321297);
1278 }
1279 if (is_array($GLOBALS['TCA']['sys_template']['columns'])) {
1280 $value = str_replace(',', '', 'EXT:' . $extKey . '/' . $path);
1281 $itemArray = [trim($title . ' (' . $extKey . ')'), $value];
1282 $GLOBALS['TCA']['sys_template']['columns']['include_static_file']['config']['items'][] = $itemArray;
1283 }
1284 }
1285
1286 /**
1287 * Call this method to add an entry in the pageTSconfig list found in pages
1288 * FOR USE in Configuration/TCA/Overrides/pages.php
1289 *
1290 * @param string $extKey The extension key
1291 * @param string $filePath The path where the TSconfig file is located
1292 * @param string $title The title in the selector box
1293 * @throws \InvalidArgumentException
1294 */
1295 public static function registerPageTSConfigFile($extKey, $filePath, $title)
1296 {
1297 if (!$extKey) {
1298 throw new \InvalidArgumentException('No extension key given.', 1447789490);
1299 }
1300 if (!$filePath) {
1301 throw new \InvalidArgumentException('No file path given.', 1447789491);
1302 }
1303 if (!isset($GLOBALS['TCA']['pages']['columns']) || !is_array($GLOBALS['TCA']['pages']['columns'])) {
1304 throw new \InvalidArgumentException('No TCA definition for table "pages".', 1447789492);
1305 }
1306
1307 $value = str_replace(',', '', 'EXT:' . $extKey . '/' . $filePath);
1308 $itemArray = [trim($title . ' (' . $extKey . ')'), $value];
1309 $GLOBALS['TCA']['pages']['columns']['tsconfig_includes']['config']['items'][] = $itemArray;
1310 }
1311
1312 /**
1313 * Adds $content to the default TypoScript setup code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_setup']
1314 * Prefixed with a [GLOBAL] line
1315 * FOR USE IN ext_localconf.php FILES
1316 *
1317 * @param string $content TypoScript Setup string
1318 */
1319 public static function addTypoScriptSetup($content)
1320 {
1321 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'] .= '
1322 [GLOBAL]
1323 ' . $content;
1324 }
1325
1326 /**
1327 * Adds $content to the default TypoScript constants code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_constants']
1328 * Prefixed with a [GLOBAL] line
1329 * FOR USE IN ext_localconf.php FILES
1330 *
1331 * @param string $content TypoScript Constants string
1332 */
1333 public static function addTypoScriptConstants($content)
1334 {
1335 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants'] .= '
1336 [GLOBAL]
1337 ' . $content;
1338 }
1339
1340 /**
1341 * Adds $content to the default TypoScript code for either setup or constants as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_*']
1342 * (Basically this function can do the same as addTypoScriptSetup and addTypoScriptConstants - just with a little more hazzle, but also with some more options!)
1343 * FOR USE IN ext_localconf.php FILES
1344 * Note: As of TYPO3 CMS 6.2, static template #43 (content: default) was replaced with "defaultContentRendering" which makes it
1345 * possible that a first extension like fluid_styled_content registers a "contentRendering" template (= a template that defines default content rendering TypoScript)
1346 * by adding itself to $TYPO3_CONF_VARS[FE][contentRenderingTemplates][] = 'myext/Configuration/TypoScript'.
1347 * An extension calling addTypoScript('myext', 'setup', $typoScript, 'defaultContentRendering') will add its TypoScript directly after;
1348 * For now, "43" and "defaultContentRendering" can be used, but "defaultContentRendering" is more descriptive and
1349 * should be used in the future.
1350 *
1351 * @param string $key Is the extension key (informative only).
1352 * @param string $type Is either "setup" or "constants" and obviously determines which kind of TypoScript code we are adding.
1353 * @param string $content Is the TS content, will be prefixed with a [GLOBAL] line and a comment-header.
1354 * @param int|string 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.
1355 * @throws \InvalidArgumentException
1356 */
1357 public static function addTypoScript(string $key, string $type, string $content, $afterStaticUid = 0)
1358 {
1359 if ($type !== 'setup' && $type !== 'constants') {
1360 throw new \InvalidArgumentException('Argument $type must be set to either "setup" or "constants" when calling addTypoScript from extension "' . $key . '"', 1507321200);
1361 }
1362 $content = '
1363
1364 [GLOBAL]
1365 #############################################
1366 ## TypoScript added by extension "' . $key . '"
1367 #############################################
1368
1369 ' . $content;
1370 if ($afterStaticUid) {
1371 // If 'content (default)' is targeted (static uid 43),
1372 // the content is added after typoscript of type contentRendering, eg. fluid_styled_content, see EXT:frontend/TemplateService for more information on how the code is parsed
1373 if ($afterStaticUid === 'defaultContentRendering' || $afterStaticUid == 43) {
1374 if (!isset($GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.']['defaultContentRendering'])) {
1375 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.']['defaultContentRendering'] = '';
1376 }
1377 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.']['defaultContentRendering'] .= $content;
1378 } else {
1379 if (!isset($GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.'][$afterStaticUid])) {
1380 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.'][$afterStaticUid] = '';
1381 }
1382 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.'][$afterStaticUid] .= $content;
1383 }
1384 } else {
1385 if (!isset($GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type])) {
1386 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type] = '';
1387 }
1388 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type] .= $content;
1389 }
1390 }
1391
1392 /***************************************
1393 *
1394 * Internal extension management methods
1395 *
1396 ***************************************/
1397 /**
1398 * Find extension icon
1399 *
1400 * @param string $extensionPath Path to extension directory.
1401 * @param bool $returnFullPath Return full path of file.
1402 *
1403 * @return string
1404 */
1405 public static function getExtensionIcon($extensionPath, $returnFullPath = false)
1406 {
1407 $icon = '';
1408 $locationsToCheckFor = [
1409 'Resources/Public/Icons/Extension.svg',
1410 'Resources/Public/Icons/Extension.png',
1411 'Resources/Public/Icons/Extension.gif',
1412 'ext_icon.svg',
1413 'ext_icon.png',
1414 'ext_icon.gif',
1415 ];
1416 foreach ($locationsToCheckFor as $fileLocation) {
1417 if (file_exists($extensionPath . $fileLocation)) {
1418 $icon = $fileLocation;
1419 break;
1420 }
1421 }
1422 return $returnFullPath ? $extensionPath . $icon : $icon;
1423 }
1424
1425 /**
1426 * Execute all ext_localconf.php files of loaded extensions.
1427 * The method implements an optionally used caching mechanism that concatenates all
1428 * ext_localconf.php files in one file.
1429 *
1430 * This is an internal method. It is only used during bootstrap and
1431 * extensions should not use it!
1432 *
1433 * @param bool $allowCaching Whether or not to load / create concatenated cache file
1434 * @param FrontendInterface $codeCache
1435 * @internal
1436 */
1437 public static function loadExtLocalconf($allowCaching = true, FrontendInterface $codeCache = null)
1438 {
1439 if ($allowCaching) {
1440 $codeCache = $codeCache ?? self::getCacheManager()->getCache('core');
1441 $cacheIdentifier = self::getExtLocalconfCacheIdentifier();
1442 if ($codeCache->has($cacheIdentifier)) {
1443 $codeCache->require($cacheIdentifier);
1444 } else {
1445 self::loadSingleExtLocalconfFiles();
1446 self::createExtLocalconfCacheEntry($codeCache);
1447 }
1448 } else {
1449 self::loadSingleExtLocalconfFiles();
1450 }
1451 }
1452
1453 /**
1454 * Execute ext_localconf.php files from extensions
1455 */
1456 protected static function loadSingleExtLocalconfFiles()
1457 {
1458 foreach (static::$packageManager->getActivePackages() as $package) {
1459 $extLocalconfPath = $package->getPackagePath() . 'ext_localconf.php';
1460 if (@file_exists($extLocalconfPath)) {
1461 require $extLocalconfPath;
1462 }
1463 }
1464 }
1465
1466 /**
1467 * Create cache entry for concatenated ext_localconf.php files
1468 *
1469 * @param FrontendInterface $codeCache
1470 */
1471 protected static function createExtLocalconfCacheEntry(FrontendInterface $codeCache)
1472 {
1473 $phpCodeToCache = [];
1474 // Set same globals as in loadSingleExtLocalconfFiles()
1475 $phpCodeToCache[] = '/**';
1476 $phpCodeToCache[] = ' * Compiled ext_localconf.php cache file';
1477 $phpCodeToCache[] = ' */';
1478 $phpCodeToCache[] = '';
1479 // Iterate through loaded extensions and add ext_localconf content
1480 foreach (static::$packageManager->getActivePackages() as $package) {
1481 $extensionKey = $package->getPackageKey();
1482 $extLocalconfPath = $package->getPackagePath() . 'ext_localconf.php';
1483 if (@file_exists($extLocalconfPath)) {
1484 // Include a header per extension to make the cache file more readable
1485 $phpCodeToCache[] = '/**';
1486 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1487 $phpCodeToCache[] = ' * File: ' . $extLocalconfPath;
1488 $phpCodeToCache[] = ' */';
1489 $phpCodeToCache[] = '';
1490 // Add ext_localconf.php content of extension
1491 $phpCodeToCache[] = trim(file_get_contents($extLocalconfPath));
1492 $phpCodeToCache[] = '';
1493 $phpCodeToCache[] = '';
1494 }
1495 }
1496 $phpCodeToCache = implode(LF, $phpCodeToCache);
1497 // Remove all start and ending php tags from content
1498 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1499 $codeCache->set(self::getExtLocalconfCacheIdentifier(), $phpCodeToCache);
1500 }
1501
1502 /**
1503 * Cache identifier of concatenated ext_localconf file
1504 *
1505 * @return string
1506 */
1507 protected static function getExtLocalconfCacheIdentifier()
1508 {
1509 return 'ext_localconf_' . sha1(TYPO3_version . Environment::getProjectPath() . 'extLocalconf' . serialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']));
1510 }
1511
1512 /**
1513 * Wrapper for buildBaseTcaFromSingleFiles handling caching.
1514 *
1515 * This builds 'base' TCA that is later overloaded by ext_tables.php.
1516 *
1517 * Use a cache file if exists and caching is allowed.
1518 *
1519 * This is an internal method. It is only used during bootstrap and
1520 * extensions should not use it!
1521 *
1522 * @param bool $allowCaching Whether or not to load / create concatenated cache file
1523 * @internal
1524 */
1525 public static function loadBaseTca($allowCaching = true, FrontendInterface $codeCache = null)
1526 {
1527 if ($allowCaching) {
1528 $codeCache = $codeCache ?? self::getCacheManager()->getCache('core');
1529 $cacheIdentifier = static::getBaseTcaCacheIdentifier();
1530 $cacheData = $codeCache->require($cacheIdentifier);
1531 if ($cacheData) {
1532 $GLOBALS['TCA'] = $cacheData['tca'];
1533 GeneralUtility::setSingletonInstance(
1534 CategoryRegistry::class,
1535 unserialize(
1536 $cacheData['categoryRegistry'],
1537 ['allowed_classes' => [CategoryRegistry::class]]
1538 )
1539 );
1540 } else {
1541 static::buildBaseTcaFromSingleFiles();
1542 static::createBaseTcaCacheFile($codeCache);
1543 }
1544 } else {
1545 static::buildBaseTcaFromSingleFiles();
1546 }
1547 }
1548
1549 /**
1550 * Find all Configuration/TCA/* files of extensions and create base TCA from it.
1551 * The filename must be the table name in $GLOBALS['TCA'], and the content of
1552 * the file should return an array with content of a specific table.
1553 *
1554 * @see Extension core, extensionmanager and others for examples.
1555 */
1556 protected static function buildBaseTcaFromSingleFiles()
1557 {
1558 $GLOBALS['TCA'] = [];
1559
1560 $activePackages = static::$packageManager->getActivePackages();
1561
1562 // First load "full table" files from Configuration/TCA
1563 foreach ($activePackages as $package) {
1564 try {
1565 $finder = Finder::create()->files()->sortByName()->depth(0)->name('*.php')->in($package->getPackagePath() . 'Configuration/TCA');
1566 } catch (\InvalidArgumentException $e) {
1567 // No such directory in this package
1568 continue;
1569 }
1570 foreach ($finder as $fileInfo) {
1571 $tcaOfTable = require $fileInfo->getPathname();
1572 if (is_array($tcaOfTable)) {
1573 $tcaTableName = substr($fileInfo->getBasename(), 0, -4);
1574 $GLOBALS['TCA'][$tcaTableName] = $tcaOfTable;
1575 }
1576 }
1577 }
1578
1579 // Apply category stuff
1580 CategoryRegistry::getInstance()->applyTcaForPreRegisteredTables();
1581
1582 // Execute override files from Configuration/TCA/Overrides
1583 foreach ($activePackages as $package) {
1584 try {
1585 $finder = Finder::create()->files()->sortByName()->depth(0)->name('*.php')->in($package->getPackagePath() . 'Configuration/TCA/Overrides');
1586 } catch (\InvalidArgumentException $e) {
1587 // No such directory in this package
1588 continue;
1589 }
1590 foreach ($finder as $fileInfo) {
1591 require $fileInfo->getPathname();
1592 }
1593 }
1594
1595 // Call the TcaMigration and log any deprecations.
1596 $tcaMigration = GeneralUtility::makeInstance(TcaMigration::class);
1597 $GLOBALS['TCA'] = $tcaMigration->migrate($GLOBALS['TCA']);
1598 $messages = $tcaMigration->getMessages();
1599 if (!empty($messages)) {
1600 $context = 'Automatic TCA migration done during bootstrap. Please adapt TCA accordingly, these migrations'
1601 . ' will be removed. The backend module "Configuration -> TCA" shows the modified values.'
1602 . ' Please adapt these areas:';
1603 array_unshift($messages, $context);
1604 trigger_error(implode(LF, $messages), E_USER_DEPRECATED);
1605 }
1606
1607 // TCA preparation
1608 $tcaPreparation = GeneralUtility::makeInstance(TcaPreparation::class);
1609 $GLOBALS['TCA'] = $tcaPreparation->prepare($GLOBALS['TCA']);
1610
1611 static::emitTcaIsBeingBuiltSignal($GLOBALS['TCA']);
1612 }
1613
1614 /**
1615 * Emits the signal and uses the result of slots for the final TCA
1616 * This means, that *all* slots *must* return the complete TCA to
1617 * be effective. If a slot calls methods that manipulate the global array,
1618 * it needs to return the global array in the end. To be future proof,
1619 * a slot should manipulate the signal argument only and return it
1620 * after manipulation.
1621 *
1622 * @param array $tca
1623 */
1624 protected static function emitTcaIsBeingBuiltSignal(array $tca)
1625 {
1626 list($tca) = static::getSignalSlotDispatcher()->dispatch(__CLASS__, 'tcaIsBeingBuilt', [$tca]);
1627 $GLOBALS['TCA'] = $tca;
1628 }
1629
1630 /**
1631 * Cache base $GLOBALS['TCA'] to cache file to require the whole thing in one
1632 * file for next access instead of cycling through all extensions again.
1633 *
1634 * @param FrontendInterface $codeCache
1635 */
1636 protected static function createBaseTcaCacheFile(FrontendInterface $codeCache)
1637 {
1638 $codeCache->set(
1639 static::getBaseTcaCacheIdentifier(),
1640 'return '
1641 . var_export(['tca' => $GLOBALS['TCA'], 'categoryRegistry' => serialize(CategoryRegistry::getInstance())], true)
1642 . ';'
1643 );
1644 }
1645
1646 /**
1647 * Cache identifier of base TCA cache entry.
1648 *
1649 * @return string
1650 */
1651 protected static function getBaseTcaCacheIdentifier()
1652 {
1653 return 'tca_base_' . sha1(TYPO3_version . Environment::getProjectPath() . 'tca_code' . serialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']));
1654 }
1655
1656 /**
1657 * Execute all ext_tables.php files of loaded extensions.
1658 * The method implements an optionally used caching mechanism that concatenates all
1659 * ext_tables.php files in one file.
1660 *
1661 * This is an internal method. It is only used during bootstrap and
1662 * extensions should not use it!
1663 *
1664 * @param bool $allowCaching Whether to load / create concatenated cache file
1665 * @internal
1666 */
1667 public static function loadExtTables($allowCaching = true)
1668 {
1669 if ($allowCaching && !self::$extTablesWasReadFromCacheOnce) {
1670 self::$extTablesWasReadFromCacheOnce = true;
1671 $cacheIdentifier = self::getExtTablesCacheIdentifier();
1672 /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $codeCache */
1673 $codeCache = self::getCacheManager()->getCache('core');
1674 if ($codeCache->has($cacheIdentifier)) {
1675 $codeCache->require($cacheIdentifier);
1676 } else {
1677 self::loadSingleExtTablesFiles();
1678 self::createExtTablesCacheEntry();
1679 }
1680 } else {
1681 self::loadSingleExtTablesFiles();
1682 }
1683 }
1684
1685 /**
1686 * Load ext_tables.php as single files
1687 */
1688 protected static function loadSingleExtTablesFiles()
1689 {
1690 // Load each ext_tables.php file of loaded extensions
1691 foreach (static::$packageManager->getActivePackages() as $package) {
1692 $extTablesPath = $package->getPackagePath() . 'ext_tables.php';
1693 if (@file_exists($extTablesPath)) {
1694 require $extTablesPath;
1695 }
1696 }
1697 }
1698
1699 /**
1700 * Create concatenated ext_tables.php cache file
1701 */
1702 protected static function createExtTablesCacheEntry()
1703 {
1704 $phpCodeToCache = [];
1705 // Set same globals as in loadSingleExtTablesFiles()
1706 $phpCodeToCache[] = '/**';
1707 $phpCodeToCache[] = ' * Compiled ext_tables.php cache file';
1708 $phpCodeToCache[] = ' */';
1709 $phpCodeToCache[] = '';
1710 // Iterate through loaded extensions and add ext_tables content
1711 foreach (static::$packageManager->getActivePackages() as $package) {
1712 $extensionKey = $package->getPackageKey();
1713 $extTablesPath = $package->getPackagePath() . 'ext_tables.php';
1714 if (@file_exists($extTablesPath)) {
1715 // Include a header per extension to make the cache file more readable
1716 $phpCodeToCache[] = '/**';
1717 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1718 $phpCodeToCache[] = ' * File: ' . $extTablesPath;
1719 $phpCodeToCache[] = ' */';
1720 $phpCodeToCache[] = '';
1721 // Add ext_tables.php content of extension
1722 $phpCodeToCache[] = trim(file_get_contents($extTablesPath));
1723 $phpCodeToCache[] = '';
1724 }
1725 }
1726 $phpCodeToCache = implode(LF, $phpCodeToCache);
1727 // Remove all start and ending php tags from content
1728 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1729 self::getCacheManager()->getCache('core')->set(self::getExtTablesCacheIdentifier(), $phpCodeToCache);
1730 }
1731
1732 /**
1733 * Cache identifier for concatenated ext_tables.php files
1734 *
1735 * @return string
1736 */
1737 protected static function getExtTablesCacheIdentifier()
1738 {
1739 return 'ext_tables_' . sha1(TYPO3_version . Environment::getProjectPath() . 'extTables' . serialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']));
1740 }
1741
1742 /**
1743 * Gets an array of loaded extension keys
1744 *
1745 * @return array Loaded extensions
1746 */
1747 public static function getLoadedExtensionListArray()
1748 {
1749 return array_keys(static::$packageManager->getActivePackages());
1750 }
1751
1752 /**
1753 * Loads given extension
1754 *
1755 * Warning: This method only works if the upgrade wizard to transform
1756 * localconf.php to LocalConfiguration.php was already run
1757 *
1758 * @param string $extensionKey Extension key to load
1759 * @throws \RuntimeException
1760 */
1761 public static function loadExtension($extensionKey)
1762 {
1763 if (static::$packageManager->isPackageActive($extensionKey)) {
1764 throw new \RuntimeException('Extension already loaded', 1342345486);
1765 }
1766 static::$packageManager->activatePackage($extensionKey);
1767 }
1768
1769 /**
1770 * Unloads given extension
1771 *
1772 * Warning: This method only works if the upgrade wizard to transform
1773 * localconf.php to LocalConfiguration.php was already run
1774 *
1775 * @param string $extensionKey Extension key to remove
1776 * @throws \RuntimeException
1777 */
1778 public static function unloadExtension($extensionKey)
1779 {
1780 if (!static::$packageManager->isPackageActive($extensionKey)) {
1781 throw new \RuntimeException('Extension not loaded', 1342345487);
1782 }
1783 static::$packageManager->deactivatePackage($extensionKey);
1784 }
1785
1786 /**
1787 * Makes a table categorizable by adding value into the category registry.
1788 * FOR USE IN ext_localconf.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1789 *
1790 * @param string $extensionKey Extension key to be used
1791 * @param string $tableName Name of the table to be categorized
1792 * @param string $fieldName Name of the field to be used to store categories
1793 * @param array $options Additional configuration options
1794 * @param bool $override If TRUE, any category configuration for the same table / field is removed before the new configuration is added
1795 * @see addTCAcolumns
1796 * @see addToAllTCAtypes
1797 */
1798 public static function makeCategorizable($extensionKey, $tableName, $fieldName = 'categories', array $options = [], $override = false)
1799 {
1800 // Update the category registry
1801 $result = CategoryRegistry::getInstance()->add($extensionKey, $tableName, $fieldName, $options, $override);
1802 if ($result === false) {
1803 GeneralUtility::makeInstance(LogManager::class)
1804 ->getLogger(__CLASS__)
1805 ->warning(sprintf(
1806 CategoryRegistry::class . ': no category registered for table "%s". Key was already registered.',
1807 $tableName
1808 ));
1809 }
1810 }
1811 }