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