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