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