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