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