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