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