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