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