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