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