Test Failed
Branch master (7b1793)
by Tymoteusz
15:35
created

removeDuplicatesForInsertion()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 16
nc 6
nop 2
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
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
use TYPO3\CMS\Core\Preparations\TcaPreparation;
22
23
/**
24
 * Extension Management functions
25
 *
26
 * This class is never instantiated, rather the methods inside is called as functions like
27
 * \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('my_extension');
28
 */
29
class ExtensionManagementUtility
30
{
31
    /**
32
     * @var array
33
     */
34
    protected static $extensionKeyMap;
35
36
    /**
37
     * TRUE, if ext_tables file was read from cache for this script run.
38
     * The frontend tends to do that multiple times, but the caching framework does
39
     * not allow this (via a require_once call). This variable is used to track
40
     * the access to the cache file to read the single ext_tables.php if it was
41
     * already read from cache
42
     *
43
     * @todo See if we can get rid of the 'load multiple times' scenario in fe
44
     * @var bool
45
     */
46
    protected static $extTablesWasReadFromCacheOnce = false;
47
48
    /**
49
     * @var PackageManager
50
     */
51
    protected static $packageManager;
52
53
    /**
54
     * Sets the package manager for all that backwards compatibility stuff,
55
     * so it doesn't have to be fetched through the bootstap.
56
     *
57
     * @param PackageManager $packageManager
58
     * @internal
59
     */
60
    public static function setPackageManager(PackageManager $packageManager)
61
    {
62
        static::$packageManager = $packageManager;
63
    }
64
65
    /**
66
     * @var \TYPO3\CMS\Core\Cache\CacheManager
67
     */
68
    protected static $cacheManager;
69
70
    /**
71
     * Getter for the cache manager
72
     *
73
     * @return \TYPO3\CMS\Core\Cache\CacheManager
74
     */
75
    protected static function getCacheManager()
76
    {
77
        if (static::$cacheManager === null) {
78
            static::$cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
79
        }
80
        return static::$cacheManager;
81
    }
82
83
    /**
84
     * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
85
     */
86
    protected static $signalSlotDispatcher;
87
88
    /**
89
     * Getter for the signal slot dispatcher
90
     *
91
     * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
92
     */
93
    protected static function getSignalSlotDispatcher()
94
    {
95
        if (static::$signalSlotDispatcher === null) {
96
            static::$signalSlotDispatcher = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class);
97
        }
98
        return static::$signalSlotDispatcher;
99
    }
100
101
    /**************************************
102
     *
103
     * PATHS and other evaluation
104
     *
105
     ***************************************/
106
    /**
107
     * Returns TRUE if the extension with extension key $key is loaded.
108
     *
109
     * @param string $key Extension key to test
110
     * @param bool $exitOnError If $exitOnError is TRUE and the extension is not loaded the function will die with an error message, this is deprecated and will be removed in TYPO3 v10
111
     * @return bool
112
     * @throws \BadFunctionCallException
113
     */
114
    public static function isLoaded($key, $exitOnError = null)
115
    {
116
        // safety net for extensions checking for "EXT:version", can be removed in TYPO3 v10.
117
        if ($key === 'version') {
118
            trigger_error('EXT:version has been moved into EXT:workspaces, you should check against "workspaces", as this might lead to unexpected behaviour in the future.', E_USER_DEPRECATED);
119
            $key = 'workspaces';
120
        }
121
        if ($exitOnError !== null) {
122
            trigger_error('Calling isLoaded() with a second argument via "exitOnError" will be removed in TYPO3 v10, handle an unloaded package yourself in the future.', E_USER_DEPRECATED);
123
        }
124
        $isLoaded = static::$packageManager->isPackageActive($key);
125
        if ($exitOnError && !$isLoaded) {
126
            // @deprecated, once $existOnError is gone, this check can be removed.
127
            throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension "' . $key . '" is not loaded!', 1270853910);
128
        }
129
        return $isLoaded;
130
    }
131
132
    /**
133
     * Returns the absolute path to the extension with extension key $key.
134
     *
135
     * @param $key string Extension key
136
     * @param $script string $script is appended to the output if set.
137
     * @throws \BadFunctionCallException
138
     * @return string
139
     */
140
    public static function extPath($key, $script = '')
141
    {
142
        if (!static::$packageManager->isPackageActive($key)) {
143
            throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension key "' . $key . '" is NOT loaded!', 1365429656);
144
        }
145
        return static::$packageManager->getPackage($key)->getPackagePath() . $script;
146
    }
147
148
    /**
149
     * Returns the relative path to the extension as measured from the PATH_site (frontend)
150
     * If the extension is not loaded the function will die with an error message
151
     * Useful for images and links from the frontend
152
     *
153
     * @param string $key Extension key
154
     * @return string
155
     * @deprecated use extPath() or GeneralUtility::getFileAbsFileName() together with PathUtility::getAbsoluteWebPath() instead.
156
     */
157
    public static function siteRelPath($key)
158
    {
159
        trigger_error('Calling siteRelPath() is deprecated. This method will be removed in TYPO3 v10, use extPath() in conjunction with PathUtility::getAbsoluteWebPath() instead.', E_USER_DEPRECATED);
160
        return PathUtility::stripPathSitePrefix(self::extPath($key));
161
    }
162
163
    /**
164
     * Returns the correct class name prefix for the extension key $key
165
     *
166
     * @param string $key Extension key
167
     * @return string
168
     * @internal
169
     */
170
    public static function getCN($key)
171
    {
172
        return strpos($key, 'user_') === 0 ? 'user_' . str_replace('_', '', substr($key, 5)) : 'tx_' . str_replace('_', '', $key);
173
    }
174
175
    /**
176
     * Returns the real extension key like 'tt_news' from an extension prefix like 'tx_ttnews'.
177
     *
178
     * @param string $prefix The extension prefix (e.g. 'tx_ttnews')
179
     * @return mixed Real extension key (string)or FALSE (bool) if something went wrong
180
     * @deprecated since TYPO3 v9, just use the proper extension key directly
181
     */
182
    public static function getExtensionKeyByPrefix($prefix)
183
    {
184
        trigger_error('Calling getExtensionKeyByPrefix() is deprecated and will be removed in TYPO3 v10. Use extension keys directly', E_USER_DEPRECATED);
185
        $result = false;
186
        // Build map of short keys referencing to real keys:
187
        if (!isset(self::$extensionKeyMap)) {
188
            self::$extensionKeyMap = [];
189
            foreach (static::$packageManager->getActivePackages() as $package) {
190
                $shortKey = str_replace('_', '', $package->getPackageKey());
191
                self::$extensionKeyMap[$shortKey] = $package->getPackageKey();
192
            }
193
        }
194
        // Lookup by the given short key:
195
        $parts = explode('_', $prefix);
196
        if (isset(self::$extensionKeyMap[$parts[1]])) {
197
            $result = self::$extensionKeyMap[$parts[1]];
198
        }
199
        return $result;
200
    }
201
202
    /**
203
     * Clears the extension key map.
204
     */
205
    public static function clearExtensionKeyMap()
206
    {
207
        self::$extensionKeyMap = null;
208
    }
209
210
    /**
211
     * Retrieves the version of an installed extension.
212
     * If the extension is not installed, this function returns an empty string.
213
     *
214
     * @param string $key The key of the extension to look up, must not be empty
215
     *
216
     * @throws \InvalidArgumentException
217
     * @throws \TYPO3\CMS\Core\Package\Exception
218
     * @return string The extension version as a string in the format "x.y.z",
219
     */
220
    public static function getExtensionVersion($key)
221
    {
222
        if (!is_string($key) || empty($key)) {
223
            throw new \InvalidArgumentException('Extension key must be a non-empty string.', 1294586096);
224
        }
225
        if (!static::isLoaded($key)) {
226
            return '';
227
        }
228
        $version = static::$packageManager->getPackage($key)->getPackageMetaData()->getVersion();
229
        if (empty($version)) {
230
            throw new \TYPO3\CMS\Core\Package\Exception('Version number in composer manifest of package "' . $key . '" is missing or invalid', 1395614959);
231
        }
232
        return $version;
233
    }
234
235
    /**************************************
236
     *
237
     *	 Adding BACKEND features
238
     *	 (related to core features)
239
     *
240
     ***************************************/
241
    /**
242
     * Adding fields to an existing table definition in $GLOBALS['TCA']
243
     * Adds an array with $GLOBALS['TCA'] column-configuration to the $GLOBALS['TCA']-entry for that table.
244
     * 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!
245
     * So to have the fields displayed you must also call fx. addToAllTCAtypes or manually add the fields to the types list.
246
     * FOR USE IN files in Configuration/TCA/Overrides/*.php . Use in ext_tables.php FILES may break the frontend.
247
     *
248
     * @param string $table The table name of a table already present in $GLOBALS['TCA'] with a columns section
249
     * @param array $columnArray The array with the additional columns (typical some fields an extension wants to add)
250
     */
251
    public static function addTCAcolumns($table, $columnArray)
252
    {
253
        if (is_array($columnArray) && is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'])) {
254
            // Candidate for array_merge() if integer-keys will some day make trouble...
255
            $GLOBALS['TCA'][$table]['columns'] = array_merge($GLOBALS['TCA'][$table]['columns'], $columnArray);
256
        }
257
    }
258
259
    /**
260
     * Makes fields visible in the TCEforms, adding them to the end of (all) "types"-configurations
261
     *
262
     * Adds a string $string (comma separated list of field names) to all ["types"][xxx]["showitem"] entries for table $table (unless limited by $typeList)
263
     * This is needed to have new fields shown automatically in the TCEFORMS of a record from $table.
264
     * Typically this function is called after having added new columns (database fields) with the addTCAcolumns function
265
     * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
266
     *
267
     * @param string $table Table name
268
     * @param string $newFieldsString Field list to add.
269
     * @param string $typeList List of specific types to add the field list to. (If empty, all type entries are affected)
270
     * @param string $position Insert fields before (default) or after one, or replace a field
271
     */
272
    public static function addToAllTCAtypes($table, $newFieldsString, $typeList = '', $position = '')
273
    {
274
        $newFieldsString = trim($newFieldsString);
275
        if ($newFieldsString === '' || !is_array($GLOBALS['TCA'][$table]['types'])) {
276
            return;
277
        }
278
        list($positionIdentifier, $entityName) = GeneralUtility::trimExplode(':', $position);
279
        $palettesChanged = [];
280
281
        foreach ($GLOBALS['TCA'][$table]['types'] as $type => &$typeDetails) {
282
            // skip if we don't want to add the field for this type
283
            if ($typeList !== '' && !GeneralUtility::inList($typeList, $type)) {
284
                continue;
285
            }
286
            // skip if fields were already added
287
            if (!isset($typeDetails['showitem'])) {
288
                continue;
289
            }
290
291
            $fieldArray = GeneralUtility::trimExplode(',', $typeDetails['showitem'], true);
292
            if (in_array($newFieldsString, $fieldArray, true)) {
293
                continue;
294
            }
295
296
            $fieldExists = false;
297
            $newPosition = '';
298
            if (is_array($GLOBALS['TCA'][$table]['palettes'] ?? false)) {
299
                // Get the palette names used in current showitem
300
                $paletteCount = preg_match_all('/(?:^|,)                    # Line start or a comma
301
					(?:
302
					    \\s*\\-\\-palette\\-\\-;[^;]*;([^,$]*)|             # --palette--;label;paletteName
303
					    \\s*\\b[^;,]+\\b(?:;[^;]*;([^;,]+))?[^,]*           # field;label;paletteName
304
					)/x', $typeDetails['showitem'], $paletteMatches);
305
                if ($paletteCount > 0) {
306
                    $paletteNames = array_filter(array_merge($paletteMatches[1], $paletteMatches[2]));
307
                    if (!empty($paletteNames)) {
308
                        foreach ($paletteNames as $paletteName) {
309
                            if (!isset($GLOBALS['TCA'][$table]['palettes'][$paletteName])) {
310
                                continue;
311
                            }
312
                            $palette = $GLOBALS['TCA'][$table]['palettes'][$paletteName];
313
                            switch ($positionIdentifier) {
314
                                case 'after':
315
                                case 'before':
316
                                    if (preg_match('/\\b' . $entityName . '\\b/', $palette['showitem']) > 0) {
317
                                        $newPosition = $positionIdentifier . ':--palette--;;' . $paletteName;
318
                                    }
319
                                    break;
320
                                case 'replace':
321
                                    // check if fields have been added to palette before
322
                                    if (isset($palettesChanged[$paletteName])) {
323
                                        $fieldExists = true;
324
                                        continue;
325
                                    }
326
                                    if (preg_match('/\\b' . $entityName . '\\b/', $palette['showitem']) > 0) {
327
                                        self::addFieldsToPalette($table, $paletteName, $newFieldsString, $position);
328
                                        // Memorize that we already changed this palette, in case other types also use it
329
                                        $palettesChanged[$paletteName] = true;
330
                                        $fieldExists = true;
331
                                        continue;
332
                                    }
333
                                    break;
334
                                default:
335
                                    // Intentionally left blank
336
                            }
337
                        }
338
                    }
339
                }
340
            }
341
            if ($fieldExists === false) {
342
                $typeDetails['showitem'] = self::executePositionedStringInsertion(
343
                    $typeDetails['showitem'],
344
                    $newFieldsString,
345
                    $newPosition !== '' ? $newPosition : $position
346
                );
347
            }
348
        }
349
        unset($typeDetails);
350
    }
351
352
    /**
353
     * Adds new fields to all palettes that is defined after an existing field.
354
     * If the field does not have a following palette yet, it's created automatically
355
     * and gets called "generatedFor-$field".
356
     * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
357
     *
358
     * See unit tests for more examples and edge cases.
359
     *
360
     * Example:
361
     *
362
     * 'aTable' => array(
363
     * 	'types' => array(
364
     * 		'aType' => array(
365
     * 			'showitem' => 'aField, --palette--;;aPalette',
366
     * 		),
367
     * 	),
368
     * 	'palettes' => array(
369
     * 		'aPallete' => array(
370
     * 			'showitem' => 'fieldB, fieldC',
371
     * 		),
372
     * 	),
373
     * ),
374
     *
375
     * Calling addFieldsToAllPalettesOfField('aTable', 'aField', 'newA', 'before: fieldC') results in:
376
     *
377
     * 'aTable' => array(
378
     * 	'types' => array(
379
     * 		'aType' => array(
380
     * 			'showitem' => 'aField, --palette--;;aPalette',
381
     * 		),
382
     * 	),
383
     * 	'palettes' => array(
384
     * 		'aPallete' => array(
385
     * 			'showitem' => 'fieldB, newA, fieldC',
386
     * 		),
387
     * 	),
388
     * ),
389
     *
390
     * @param string $table Name of the table
391
     * @param string $field Name of the field that has the palette to be extended
392
     * @param string $addFields List of fields to be added to the palette
393
     * @param string $insertionPosition Insert fields before (default) or after one
394
     */
395
    public static function addFieldsToAllPalettesOfField($table, $field, $addFields, $insertionPosition = '')
396
    {
397
        if (!isset($GLOBALS['TCA'][$table]['columns'][$field])) {
398
            return;
399
        }
400
        if (!is_array($GLOBALS['TCA'][$table]['types'])) {
401
            return;
402
        }
403
404
        // Iterate through all types and search for the field that defines the palette to be extended
405
        foreach ($GLOBALS['TCA'][$table]['types'] as $typeName => $typeArray) {
406
            // Continue if types has no showitem at all or if requested field is not in it
407 View Code Duplication
            if (!isset($typeArray['showitem']) || strpos($typeArray['showitem'], $field) === false) {
408
                continue;
409
            }
410
            $fieldArrayWithOptions = GeneralUtility::trimExplode(',', $typeArray['showitem']);
411
            // Find the field we're handling
412
            $newFieldStringArray = [];
413
            foreach ($fieldArrayWithOptions as $fieldNumber => $fieldString) {
414
                $newFieldStringArray[] = $fieldString;
415
                $fieldArray = GeneralUtility::trimExplode(';', $fieldString);
416
                if ($fieldArray[0] !== $field) {
417
                    continue;
418
                }
419
                if (
420
                    isset($fieldArrayWithOptions[$fieldNumber + 1])
421
                    && strpos($fieldArrayWithOptions[$fieldNumber + 1], '--palette--') === 0
422
                ) {
423
                    // Match for $field and next field is a palette - add fields to this one
424
                    $paletteName = GeneralUtility::trimExplode(';', $fieldArrayWithOptions[$fieldNumber + 1]);
425
                    $paletteName = $paletteName[2];
426
                    self::addFieldsToPalette($table, $paletteName, $addFields, $insertionPosition);
427
                } else {
428
                    // Match for $field but next field is no palette - create a new one
429
                    $newPaletteName = 'generatedFor-' . $field;
430
                    self::addFieldsToPalette($table, 'generatedFor-' . $field, $addFields, $insertionPosition);
431
                    $newFieldStringArray[] = '--palette--;;' . $newPaletteName;
432
                }
433
            }
434
            $GLOBALS['TCA'][$table]['types'][$typeName]['showitem'] = implode(', ', $newFieldStringArray);
435
        }
436
    }
437
438
    /**
439
     * Adds new fields to a palette.
440
     * If the palette does not exist yet, it's created automatically.
441
     * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
442
     *
443
     * @param string $table Name of the table
444
     * @param string $palette Name of the palette to be extended
445
     * @param string $addFields List of fields to be added to the palette
446
     * @param string $insertionPosition Insert fields before (default) or after one
447
     */
448
    public static function addFieldsToPalette($table, $palette, $addFields, $insertionPosition = '')
449
    {
450
        if (isset($GLOBALS['TCA'][$table])) {
451
            $paletteData = &$GLOBALS['TCA'][$table]['palettes'][$palette];
452
            // If palette already exists, merge the data:
453
            if (is_array($paletteData)) {
454
                $paletteData['showitem'] = self::executePositionedStringInsertion($paletteData['showitem'], $addFields, $insertionPosition);
455
            } else {
456
                $paletteData['showitem'] = self::removeDuplicatesForInsertion($addFields);
457
            }
458
        }
459
    }
460
461
    /**
462
     * Add an item to a select field item list.
463
     *
464
     * Warning: Do not use this method for radio or check types, especially not
465
     * with $relativeToField and $relativePosition parameters. This would shift
466
     * existing database data 'off by one'.
467
     * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
468
     *
469
     * As an example, this can be used to add an item to tt_content CType select
470
     * drop-down after the existing 'mailform' field with these parameters:
471
     * - $table = 'tt_content'
472
     * - $field = 'CType'
473
     * - $item = array(
474
     * 'LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:CType.I.10',
475
     * 'login',
476
     * 'i/imagename.gif',
477
     * ),
478
     * - $relativeToField = mailform
479
     * - $relativePosition = after
480
     *
481
     * @throws \InvalidArgumentException If given parameters are not of correct
482
     * @throws \RuntimeException If reference to related position fields can not
483
     * @param string $table Name of TCA table
484
     * @param string $field Name of TCA field
485
     * @param array $item New item to add
486
     * @param string $relativeToField Add item relative to existing field
487
     * @param string $relativePosition Valid keywords: 'before', 'after'
488
     */
489
    public static function addTcaSelectItem($table, $field, array $item, $relativeToField = '', $relativePosition = '')
490
    {
491
        if (!is_string($table)) {
492
            throw new \InvalidArgumentException('Given table is of type "' . gettype($table) . '" but a string is expected.', 1303236963);
493
        }
494
        if (!is_string($field)) {
495
            throw new \InvalidArgumentException('Given field is of type "' . gettype($field) . '" but a string is expected.', 1303236964);
496
        }
497
        if (!is_string($relativeToField)) {
498
            throw new \InvalidArgumentException('Given relative field is of type "' . gettype($relativeToField) . '" but a string is expected.', 1303236965);
499
        }
500
        if (!is_string($relativePosition)) {
501
            throw new \InvalidArgumentException('Given relative position is of type "' . gettype($relativePosition) . '" but a string is expected.', 1303236966);
502
        }
503
        if ($relativePosition !== '' && $relativePosition !== 'before' && $relativePosition !== 'after' && $relativePosition !== 'replace') {
504
            throw new \InvalidArgumentException('Relative position must be either empty or one of "before", "after", "replace".', 1303236967);
505
        }
506
        if (!is_array($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'])) {
507
            throw new \RuntimeException('Given select field item list was not found.', 1303237468);
508
        }
509
        // Make sure item keys are integers
510
        $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'] = array_values($GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
511
        if ($relativePosition !== '') {
512
            // Insert at specified position
513
            $matchedPosition = ArrayUtility::filterByValueRecursive($relativeToField, $GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
514
            if (!empty($matchedPosition)) {
515
                $relativeItemKey = key($matchedPosition);
516
                if ($relativePosition === 'replace') {
517
                    $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][$relativeItemKey] = $item;
518
                } else {
519
                    if ($relativePosition === 'before') {
520
                        $offset = $relativeItemKey;
521
                    } else {
522
                        $offset = $relativeItemKey + 1;
523
                    }
524
                    array_splice($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'], $offset, 0, [0 => $item]);
0 ignored issues
show
Bug introduced by
It seems like $offset can also be of type string; however, parameter $offset of array_splice() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

524
                    array_splice($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'], /** @scrutinizer ignore-type */ $offset, 0, [0 => $item]);
Loading history...
525
                }
526 View Code Duplication
            } else {
527
                // Insert at new item at the end of the array if relative position was not found
528
                $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
529
            }
530 View Code Duplication
        } else {
531
            // Insert at new item at the end of the array
532
            $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
533
        }
534
    }
535
536
    /**
537
     * Gets the TCA configuration for a field handling (FAL) files.
538
     *
539
     * @param string $fieldName Name of the field to be used
540
     * @param array $customSettingOverride Custom field settings overriding the basics
541
     * @param string $allowedFileExtensions Comma list of allowed file extensions (e.g. "jpg,gif,pdf")
542
     * @param string $disallowedFileExtensions
543
     *
544
     * @return array
545
     */
546
    public static function getFileFieldTCAConfig($fieldName, array $customSettingOverride = [], $allowedFileExtensions = '', $disallowedFileExtensions = '')
547
    {
548
        $fileFieldTCAConfig = [
549
            'type' => 'inline',
550
            'foreign_table' => 'sys_file_reference',
551
            'foreign_field' => 'uid_foreign',
552
            'foreign_sortby' => 'sorting_foreign',
553
            'foreign_table_field' => 'tablenames',
554
            'foreign_match_fields' => [
555
                'fieldname' => $fieldName
556
            ],
557
            'foreign_label' => 'uid_local',
558
            'foreign_selector' => 'uid_local',
559
            'overrideChildTca' => [
560
                'columns' => [
561
                    'uid_local' => [
562
                        'config' => [
563
                            'appearance' => [
564
                                'elementBrowserType' => 'file',
565
                                'elementBrowserAllowed' => $allowedFileExtensions
566
                            ],
567
                        ],
568
                    ],
569
                ],
570
            ],
571
            'filter' => [
572
                [
573
                    'userFunc' => \TYPO3\CMS\Core\Resource\Filter\FileExtensionFilter::class . '->filterInlineChildren',
574
                    'parameters' => [
575
                        'allowedFileExtensions' => $allowedFileExtensions,
576
                        'disallowedFileExtensions' => $disallowedFileExtensions
577
                    ]
578
                ]
579
            ],
580
            'appearance' => [
581
                'useSortable' => true,
582
                'headerThumbnail' => [
583
                    'field' => 'uid_local',
584
                    'width' => '45',
585
                    'height' => '45c',
586
                ],
587
588
                'enabledControls' => [
589
                    'info' => true,
590
                    'new' => false,
591
                    'dragdrop' => true,
592
                    'sort' => false,
593
                    'hide' => true,
594
                    'delete' => true,
595
                ],
596
            ]
597
        ];
598
        ArrayUtility::mergeRecursiveWithOverrule($fileFieldTCAConfig, $customSettingOverride);
599
        return $fileFieldTCAConfig;
600
    }
601
602
    /**
603
     * Adds a list of new fields to the TYPO3 USER SETTINGS configuration "showitem" list, the array with
604
     * the new fields itself needs to be added additionally to show up in the user setup, like
605
     * $GLOBALS['TYPO3_USER_SETTINGS']['columns'] += $tempColumns
606
     *
607
     * @param string $addFields List of fields to be added to the user settings
608
     * @param string $insertionPosition Insert fields before (default) or after one
609
     */
610
    public static function addFieldsToUserSettings($addFields, $insertionPosition = '')
611
    {
612
        $GLOBALS['TYPO3_USER_SETTINGS']['showitem'] = self::executePositionedStringInsertion($GLOBALS['TYPO3_USER_SETTINGS']['showitem'], $addFields, $insertionPosition);
613
    }
614
615
    /**
616
     * Inserts as list of data into an existing list.
617
     * The insertion position can be defined accordant before of after existing list items.
618
     *
619
     * Example:
620
     * + list: 'field_a, field_b, field_c'
621
     * + insertionList: 'field_d, field_e'
622
     * + insertionPosition: 'after:field_b'
623
     * -> 'field_a, field_b, field_d, field_e, field_c'
624
     *
625
     * $insertPosition may contain ; and - characters: after:--palette--;;title
626
     *
627
     * @param string $list The list of items to be extended
628
     * @param string $insertionList The list of items to inserted
629
     * @param string $insertionPosition Insert fields before (default) or after one
630
     * @return string The extended list
631
     */
632
    protected static function executePositionedStringInsertion($list, $insertionList, $insertionPosition = '')
633
    {
634
        $list = $newList = trim($list, ", \t\n\r\0\x0B");
635
636
        list($location, $positionName) = GeneralUtility::trimExplode(':', $insertionPosition, false, 2);
637
638
        if ($location !== 'replace') {
639
            $insertionList = self::removeDuplicatesForInsertion($insertionList, $list);
640
        }
641
642
        if ($insertionList === '') {
643
            return $list;
644
        }
645
        if ($list === '') {
646
            return $insertionList;
647
        }
648
        if ($insertionPosition === '') {
649
            return $list . ', ' . $insertionList;
650
        }
651
652
        // The $insertPosition may be a palette: after:--palette--;;title
653
        // In the $list the palette may contain a LLL string in between the ;;
654
        // Adjust the regex to match that
655
        $positionName = preg_quote($positionName, '/');
656
        if (strpos($positionName, ';;') !== false) {
657
            $positionName = str_replace(';;', ';[^;]*;', $positionName);
658
        }
659
660
        $pattern = ('/(^|,\\s*)(' . $positionName . ')(;[^,$]+)?(,|$)/');
661
        switch ($location) {
662
            case 'after':
663
                $newList = preg_replace($pattern, '$1$2$3, ' . $insertionList . '$4', $list);
664
                break;
665
            case 'before':
666
                $newList = preg_replace($pattern, '$1' . $insertionList . ', $2$3$4', $list);
667
                break;
668
            case 'replace':
669
                $newList = preg_replace($pattern, '$1' . $insertionList . '$4', $list);
670
                break;
671
            default:
672
        }
673
674
        // When preg_replace did not replace anything; append the $insertionList.
675
        if ($list === $newList) {
676
            return $list . ', ' . $insertionList;
677
        }
678
        return $newList;
679
    }
680
681
    /**
682
     * Compares an existing list of items and a list of items to be inserted
683
     * and returns a duplicate-free variant of that insertion list.
684
     *
685
     * Example:
686
     * + list: 'field_a, field_b, field_c'
687
     * + insertion: 'field_b, field_d, field_c'
688
     * -> new insertion: 'field_d'
689
     *
690
     * Duplicate values in $insertionList are removed.
691
     *
692
     * @param string $insertionList The list of items to inserted
693
     * @param string $list The list of items to be extended (default: '')
694
     * @return string Duplicate-free list of items to be inserted
695
     */
696
    protected static function removeDuplicatesForInsertion($insertionList, $list = '')
697
    {
698
        $insertionListParts = preg_split('/\\s*,\\s*/', $insertionList);
699
        $listMatches = [];
700
        if ($list !== '') {
701
            preg_match_all('/(?:^|,)\\s*\\b([^;,]+)\\b[^,]*/', $list, $listMatches);
702
            $listMatches = $listMatches[1];
703
        }
704
705
        $cleanInsertionListParts = [];
706
        foreach ($insertionListParts as $fieldName) {
707
            $fieldNameParts = explode(';', $fieldName, 2);
708
            $cleanFieldName = $fieldNameParts[0];
709
            if (
710
                $cleanFieldName === '--linebreak--'
711
                || (
712
                    !in_array($cleanFieldName, $cleanInsertionListParts, true)
713
                    && !in_array($cleanFieldName, $listMatches, true)
714
                )
715
            ) {
716
                $cleanInsertionListParts[] = $fieldName;
717
            }
718
        }
719
        return implode(', ', $cleanInsertionListParts);
720
    }
721
722
    /**
723
     * Generates an array of fields/items with additional information such as e.g. the name of the palette.
724
     *
725
     * @param string $itemList List of fields/items to be splitted up
726
     * @return array An array with the names of the fields/items as keys and additional information
727
     */
728
    protected static function explodeItemList($itemList)
729
    {
730
        $items = [];
731
        $itemParts = GeneralUtility::trimExplode(',', $itemList, true);
732
        foreach ($itemParts as $itemPart) {
733
            $itemDetails = GeneralUtility::trimExplode(';', $itemPart, false, 5);
734
            $key = $itemDetails[0];
735
            if (strpos($key, '--') !== false) {
736
                // 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!
737
                $key .= count($items);
738
            }
739
            if (!isset($items[$key])) {
740
                $items[$key] = [
741
                    'rawData' => $itemPart,
742
                    'details' => []
743
                ];
744
                $details = [0 => 'field', 1 => 'label', 2 => 'palette'];
745
                foreach ($details as $id => $property) {
746
                    $items[$key]['details'][$property] = isset($itemDetails[$id]) ? $itemDetails[$id] : '';
747
                }
748
            }
749
        }
750
        return $items;
751
    }
752
753
    /**
754
     * Generates a list of fields/items out of an array provided by the function getFieldsOfFieldList().
755
     *
756
     * @see explodeItemList
757
     * @param array $items The array of fields/items with optional additional information
758
     * @param bool $useRawData Use raw data instead of building by using the details (default: FALSE)
759
     * @return string The list of fields/items which gets used for $GLOBALS['TCA'][<table>]['types'][<type>]['showitem']
760
     */
761
    protected static function generateItemList(array $items, $useRawData = false)
762
    {
763
        $itemParts = [];
764
        foreach ($items as $item => $itemDetails) {
765
            if (strpos($item, '--') !== false) {
766
                // 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.
767
                $item = str_replace([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], '', $item);
768
            }
769
            if ($useRawData) {
770
                $itemParts[] = $itemDetails['rawData'];
771
            } else {
772
                if (count($itemDetails['details']) > 1) {
773
                    $details = ['palette', 'label', 'field'];
774
                    $elements = [];
775
                    $addEmpty = false;
776
                    foreach ($details as $property) {
777
                        if ($itemDetails['details'][$property] !== '' || $addEmpty) {
778
                            $addEmpty = true;
779
                            array_unshift($elements, $itemDetails['details'][$property]);
780
                        }
781
                    }
782
                    $item = implode(';', $elements);
783
                }
784
                $itemParts[] = $item;
785
            }
786
        }
787
        return implode(', ', $itemParts);
788
    }
789
790
    /**
791
     * Add tablename to default list of allowed tables on pages (in $PAGES_TYPES)
792
     * Will add the $table to the list of tables allowed by default on pages as setup by $PAGES_TYPES['default']['allowedTables']
793
     * FOR USE IN ext_tables.php FILES
794
     *
795
     * @param string $table Table name
796
     */
797
    public static function allowTableOnStandardPages($table)
798
    {
799
        $GLOBALS['PAGES_TYPES']['default']['allowedTables'] .= ',' . $table;
800
    }
801
802
    /**
803
     * This method is called from \TYPO3\CMS\Backend\Module\ModuleLoader::checkMod
804
     * and it replaces old conf.php.
805
     *
806
     * @param string $moduleSignature The module name
807
     * @return array Configuration of the module
808
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, addModule() works the same way nowadays.
809
     */
810
    public static function configureModule($moduleSignature)
811
    {
812
        trigger_error('This method will be removed in TYPO3 v10, as the same functionality is found in addModule() as well.', E_USER_DEPRECATED);
813
        $moduleConfiguration = $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature];
814
815
        // Register the icon and move it too "iconIdentifier"
816 View Code Duplication
        if (!empty($moduleConfiguration['icon'])) {
817
            $iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
818
            $iconIdentifier = 'module-' . $moduleSignature;
819
            $iconProvider = $iconRegistry->detectIconProvider($moduleConfiguration['icon']);
820
            $iconRegistry->registerIcon(
821
                $iconIdentifier,
822
                $iconProvider,
823
                [ 'source' => GeneralUtility::getFileAbsFileName($moduleConfiguration['icon']) ]
824
            );
825
            $moduleConfiguration['iconIdentifier'] = $iconIdentifier;
826
            unset($moduleConfiguration['icon']);
827
        }
828
829
        return $moduleConfiguration;
830
    }
831
832
    /**
833
     * Adds a module (main or sub) to the backend interface
834
     * FOR USE IN ext_tables.php FILES
835
     *
836
     * @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.
837
     * @param string $sub The submodule key. If $sub is not set a blank $main module is created.
838
     * @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.
839
     * @param string $path The absolute path to the module. Was used prior to TYPO3 v8, use $moduleConfiguration[routeTarget] now
840
     * @param array $moduleConfiguration additional configuration, previously put in "conf.php" of the module directory
841
     */
842
    public static function addModule($main, $sub = '', $position = '', $path = null, $moduleConfiguration = [])
843
    {
844
        if (($moduleConfiguration['navigationComponentId'] ?? '') === 'typo3-pagetree') {
845
            trigger_error(
846
                'Navigation component ID "typo3-pagetree" has been deprecated and will be removed in TYPO3 v10.'
847
                . 'Use "TYPO3/CMS/Backend/PageTree/PageTreeElement" instead. Module key: ' . $main . '-' . $sub,
848
                E_USER_DEPRECATED
849
            );
850
            $moduleConfiguration['navigationComponentId'] = 'TYPO3/CMS/Backend/PageTree/PageTreeElement';
851
        }
852
853
        // If there is already a main module by this name:
854
        // Adding the submodule to the correct position:
855
        if (isset($GLOBALS['TBE_MODULES'][$main]) && $sub) {
856
            list($place, $modRef) = array_pad(GeneralUtility::trimExplode(':', $position, true), 2, null);
857
            $modules = ',' . $GLOBALS['TBE_MODULES'][$main] . ',';
858
            if ($place === null || ($modRef !== null && !GeneralUtility::inList($modules, $modRef))) {
859
                $place = 'bottom';
860
            }
861
            $modRef = ',' . $modRef . ',';
862
            if (!GeneralUtility::inList($modules, $sub)) {
863
                switch (strtolower($place)) {
864
                    case 'after':
865
                        $modules = str_replace($modRef, $modRef . $sub . ',', $modules);
866
                        break;
867
                    case 'before':
868
                        $modules = str_replace($modRef, ',' . $sub . $modRef, $modules);
869
                        break;
870
                    case 'top':
871
                        $modules = $sub . $modules;
872
                        break;
873
                    case 'bottom':
874
                    default:
875
                        $modules = $modules . $sub;
876
                }
877
            }
878
            // Re-inserting the submodule list:
879
            $GLOBALS['TBE_MODULES'][$main] = trim($modules, ',');
880
        } else {
881
            // Create new main modules with only one submodule, $sub (or none if $sub is blank)
882
            $GLOBALS['TBE_MODULES'][$main] = $sub;
883
        }
884
885
        // add additional configuration
886
        $fullModuleSignature = $main . ($sub ? '_' . $sub : '');
887
        if (is_array($moduleConfiguration) && !empty($moduleConfiguration)) {
888 View Code Duplication
            if (!empty($moduleConfiguration['icon'])) {
889
                $iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
890
                $iconIdentifier = 'module-' . $fullModuleSignature;
891
                $iconProvider = $iconRegistry->detectIconProvider($moduleConfiguration['icon']);
892
                $iconRegistry->registerIcon(
893
                    $iconIdentifier,
894
                    $iconProvider,
895
                    [ 'source' => GeneralUtility::getFileAbsFileName($moduleConfiguration['icon']) ]
896
                );
897
                $moduleConfiguration['iconIdentifier'] = $iconIdentifier;
898
                unset($moduleConfiguration['icon']);
899
            }
900
901
            $GLOBALS['TBE_MODULES']['_configuration'][$fullModuleSignature] = $moduleConfiguration;
902
        }
903
904
        // Also register the module as regular route
905
        // Build Route objects from the data
906
        $name = $fullModuleSignature;
907
        if (isset($moduleConfiguration['path'])) {
908
            $path = $moduleConfiguration['path'];
909
        } else {
910
            $path = str_replace('_', '/', $name);
911
        }
912
        $path = '/' . trim($path, '/') . '/';
913
914
        $options = [
915
            'module' => true,
916
            'moduleName' => $fullModuleSignature,
917
            'access' => !empty($moduleConfiguration['access']) ? $moduleConfiguration['access'] : 'user,group'
918
        ];
919
        if (!empty($moduleConfiguration['routeTarget'])) {
920
            $options['target'] = $moduleConfiguration['routeTarget'];
921
        }
922
923
        $router = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Router::class);
924
        $router->addRoute(
925
            $name,
926
            // @todo: see if we should do a "module route"
927
            GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Route::class, $path, $options)
0 ignored issues
show
Bug introduced by
$path of type string is incompatible with the type array<integer,mixed> expected by parameter $constructorArguments of TYPO3\CMS\Core\Utility\G...Utility::makeInstance(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

927
            GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Route::class, /** @scrutinizer ignore-type */ $path, $options)
Loading history...
928
        );
929
    }
930
931
    /**
932
     * Adds a "Function menu module" ('third level module') to an existing function menu for some other backend module
933
     * The arguments values are generally determined by which function menu this is supposed to interact with
934
     * See Inside TYPO3 for information on how to use this function.
935
     * FOR USE IN ext_tables.php FILES
936
     *
937
     * @param string $modname Module name
938
     * @param string $className Class name
939
     * @param string $_ unused
940
     * @param string $title Title of module
941
     * @param string $MM_key Menu array key - default is "function
942
     * @param string $WS Workspace conditions. Blank means all workspaces, any other string can be a comma list of "online", "offline" and "custom
943
     * @see \TYPO3\CMS\Backend\Module\BaseScriptClass::mergeExternalItems()
944
     */
945
    public static function insertModuleFunction($modname, $className, $_ = null, $title, $MM_key = 'function', $WS = '')
946
    {
947
        $GLOBALS['TBE_MODULES_EXT'][$modname]['MOD_MENU'][$MM_key][$className] = [
948
            'name' => $className,
949
            'title' => $title,
950
            'ws' => $WS
951
        ];
952
    }
953
954
    /**
955
     * Adds $content to the default Page TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultPageTSconfig']
956
     * Prefixed with a [GLOBAL] line
957
     * FOR USE IN ext_tables.php/ext_localconf.php FILES
958
     *
959
     * @param string $content Page TSconfig content
960
     */
961
    public static function addPageTSConfig($content)
962
    {
963
        $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'] .= '
964
[GLOBAL]
965
' . $content;
966
    }
967
968
    /**
969
     * Adds $content to the default User TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultUserTSconfig']
970
     * Prefixed with a [GLOBAL] line
971
     * FOR USE IN ext_tables.php/ext_localconf.php FILES
972
     *
973
     * @param string $content User TSconfig content
974
     */
975
    public static function addUserTSConfig($content)
976
    {
977
        $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'] .= '
978
[GLOBAL]
979
' . $content;
980
    }
981
982
    /**
983
     * Adds a reference to a locallang file with $GLOBALS['TCA_DESCR'] labels
984
     * FOR USE IN ext_tables.php FILES
985
     * 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.
986
     *
987
     * @param string $key Description key. Typically a database table (like "pages") but for applications can be other strings, but prefixed with "_MOD_")
988
     * @param string $file File reference to locallang file, eg. "EXT:lang/Resources/Private/Language/locallang_csh_pages.xlf" (or ".xml")
989
     */
990
    public static function addLLrefForTCAdescr($key, $file)
991
    {
992
        if (empty($key)) {
993
            throw new \RuntimeException('No extension key set in addLLrefForTCAdescr(). Provide it as third parameter', 1507321596);
994
        }
995 View Code Duplication
        if (!is_array($GLOBALS['TCA_DESCR'][$key] ?? false)) {
996
            $GLOBALS['TCA_DESCR'][$key] = [];
997
        }
998 View Code Duplication
        if (!is_array($GLOBALS['TCA_DESCR'][$key]['refs'] ?? false)) {
999
            $GLOBALS['TCA_DESCR'][$key]['refs'] = [];
1000
        }
1001
        $GLOBALS['TCA_DESCR'][$key]['refs'][] = $file;
1002
    }
1003
1004
    /**
1005
     * Registers a navigation component e.g. page tree
1006
     *
1007
     * @param string $module
1008
     * @param string $componentId componentId is also an RequireJS module name e.g. 'TYPO3/CMS/MyExt/MyNavComponent'
1009
     * @param string $extensionKey
1010
     * @throws \RuntimeException
1011
     */
1012
    public static function addNavigationComponent($module, $componentId, $extensionKey)
1013
    {
1014
        if (empty($extensionKey)) {
1015
            throw new \RuntimeException('No extensionKey set in addNavigationComponent(). Provide it as third parameter', 1404068039);
1016
        }
1017
        $GLOBALS['TBE_MODULES']['_navigationComponents'][$module] = [
1018
            'componentId' => $componentId,
1019
            'extKey' => $extensionKey,
1020
            'isCoreComponent' => false
1021
        ];
1022
    }
1023
1024
    /**
1025
     * Registers a core navigation component
1026
     *
1027
     * @param string $module
1028
     * @param string $componentId
1029
     */
1030
    public static function addCoreNavigationComponent($module, $componentId)
1031
    {
1032
        self::addNavigationComponent($module, $componentId, 'core');
1033
        $GLOBALS['TBE_MODULES']['_navigationComponents'][$module]['isCoreComponent'] = true;
1034
    }
1035
1036
    /**************************************
1037
     *
1038
     *	 Adding SERVICES features
1039
     *
1040
     ***************************************/
1041
    /**
1042
     * Adds a service to the global services array
1043
     *
1044
     * @param string $extKey Extension key
1045
     * @param string $serviceType Service type, must not be prefixed "tx_" or "Tx_"
1046
     * @param string $serviceKey Service key, must be prefixed "tx_", "Tx_" or "user_"
1047
     * @param array $info Service description array
1048
     */
1049
    public static function addService($extKey, $serviceType, $serviceKey, $info)
1050
    {
1051
        if (!$serviceType) {
1052
            throw new \InvalidArgumentException('No serviceType given.', 1507321535);
1053
        }
1054
        if (!is_array($info)) {
1055
            throw new \InvalidArgumentException('No information array given.', 1507321542);
1056
        }
1057
        $info['priority'] = max(0, min(100, $info['priority']));
1058
        $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = $info;
1059
        $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['extKey'] = $extKey;
1060
        $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceKey'] = $serviceKey;
1061
        $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceType'] = $serviceType;
1062
        // Change the priority (and other values) from $GLOBALS['TYPO3_CONF_VARS']
1063
        // $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]['priority']
1064
        // even the activation is possible (a unix service might be possible on windows for some reasons)
1065
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey])) {
1066
            // No check is done here - there might be configuration values only the service type knows about, so
1067
            // we pass everything
1068
            $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = array_merge($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey], $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]);
1069
        }
1070
        // OS check
1071
        // Empty $os means 'not limited to one OS', therefore a check is not needed
1072
        if ($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] && $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os'] != '') {
1073
            $os_type = TYPO3_OS === 'WIN' ? 'WIN' : 'UNIX';
1074
            $os = GeneralUtility::trimExplode(',', strtoupper($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os']));
1075
            if (!in_array($os_type, $os, true)) {
1076
                self::deactivateService($serviceType, $serviceKey);
1077
            }
1078
        }
1079
        // Convert subtype list to array for quicker access
1080
        $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'] = [];
1081
        $serviceSubTypes = GeneralUtility::trimExplode(',', $info['subtype']);
1082
        foreach ($serviceSubTypes as $subtype) {
1083
            $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'][$subtype] = $subtype;
1084
        }
1085
    }
1086
1087
    /**
1088
     * Find the available service with highest priority
1089
     *
1090
     * @param string $serviceType Service type
1091
     * @param string $serviceSubType Service sub type
1092
     * @param mixed $excludeServiceKeys Service keys that should be excluded in the search for a service. Array or comma list.
1093
     * @return mixed Service info array if a service was found, FALSE otherwise
1094
     */
1095
    public static function findService($serviceType, $serviceSubType = '', $excludeServiceKeys = [])
1096
    {
1097
        $serviceKey = false;
1098
        $serviceInfo = false;
1099
        $priority = 0;
1100
        $quality = 0;
1101
        if (!is_array($excludeServiceKeys)) {
1102
            $excludeServiceKeys = GeneralUtility::trimExplode(',', $excludeServiceKeys, true);
1103
        }
1104
        if (is_array($GLOBALS['T3_SERVICES'][$serviceType])) {
1105
            foreach ($GLOBALS['T3_SERVICES'][$serviceType] as $key => $info) {
1106
                if (in_array($key, $excludeServiceKeys)) {
1107
                    continue;
1108
                }
1109
                // Select a subtype randomly
1110
                // Useful to start a service by service key without knowing his subtypes - for testing purposes
1111
                if ($serviceSubType === '*') {
1112
                    $serviceSubType = key($info['serviceSubTypes']);
1113
                }
1114
                // This matches empty subtype too
1115
                if ($info['available'] && ($info['subtype'] == $serviceSubType || $info['serviceSubTypes'][$serviceSubType]) && $info['priority'] >= $priority) {
1116
                    // Has a lower quality than the already found, therefore we skip this service
1117
                    if ($info['priority'] == $priority && $info['quality'] < $quality) {
1118
                        continue;
1119
                    }
1120
                    // Check if the service is available
1121
                    $info['available'] = self::isServiceAvailable($serviceType, $key, $info);
1122
                    // Still available after exec check?
1123
                    if ($info['available']) {
1124
                        $serviceKey = $key;
1125
                        $priority = $info['priority'];
1126
                        $quality = $info['quality'];
1127
                    }
1128
                }
1129
            }
1130
        }
1131
        if ($serviceKey) {
1132
            $serviceInfo = $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey];
1133
        }
1134
        return $serviceInfo;
1135
    }
1136
1137
    /**
1138
     * Find a specific service identified by its key
1139
     * Note that this completely bypasses the notions of priority and quality
1140
     *
1141
     * @param string $serviceKey Service key
1142
     * @return array Service info array if a service was found
1143
     * @throws \TYPO3\CMS\Core\Exception
1144
     */
1145
    public static function findServiceByKey($serviceKey)
1146
    {
1147
        if (is_array($GLOBALS['T3_SERVICES'])) {
1148
            // Loop on all service types
1149
            // NOTE: we don't care about the actual type, we are looking for a specific key
1150
            foreach ($GLOBALS['T3_SERVICES'] as $serviceType => $servicesPerType) {
1151
                if (isset($servicesPerType[$serviceKey])) {
1152
                    $serviceDetails = $servicesPerType[$serviceKey];
1153
                    // Test if service is available
1154
                    if (self::isServiceAvailable($serviceType, $serviceKey, $serviceDetails)) {
1155
                        // We have found the right service, return its information
1156
                        return $serviceDetails;
1157
                    }
1158
                }
1159
            }
1160
        }
1161
        throw new \TYPO3\CMS\Core\Exception('Service not found for key: ' . $serviceKey, 1319217244);
1162
    }
1163
1164
    /**
1165
     * Check if a given service is available, based on the executable files it depends on
1166
     *
1167
     * @param string $serviceType Type of service
1168
     * @param string $serviceKey Specific key of the service
1169
     * @param array $serviceDetails Information about the service
1170
     * @return bool Service availability
1171
     */
1172
    public static function isServiceAvailable($serviceType, $serviceKey, $serviceDetails)
1173
    {
1174
        // If the service depends on external programs - check if they exists
1175
        if (trim($serviceDetails['exec'])) {
1176
            $executables = GeneralUtility::trimExplode(',', $serviceDetails['exec'], true);
1177
            foreach ($executables as $executable) {
1178
                // If at least one executable file is not available, exit early returning FALSE
1179
                if (!CommandUtility::checkCommand($executable)) {
1180
                    self::deactivateService($serviceType, $serviceKey);
1181
                    return false;
1182
                }
1183
            }
1184
        }
1185
        // The service is available
1186
        return true;
1187
    }
1188
1189
    /**
1190
     * Deactivate a service
1191
     *
1192
     * @param string $serviceType Service type
1193
     * @param string $serviceKey Service key
1194
     */
1195
    public static function deactivateService($serviceType, $serviceKey)
1196
    {
1197
        // ... maybe it's better to move non-available services to a different array??
1198
        $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] = false;
1199
    }
1200
1201
    /**************************************
1202
     *
1203
     *	 Adding FRONTEND features
1204
     *
1205
     ***************************************/
1206
    /**
1207
     * Adds an entry to the list of plugins in content elements of type "Insert plugin"
1208
     * 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)
1209
     * 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.
1210
     * 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
1211
     * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
1212
     *
1213
     * @param array $itemArray Numerical array: [0] => Plugin label, [1] => Underscored extension key, [2] => Path to plugin icon relative to TYPO3_mainDir
1214
     * @param string $type Type (eg. "list_type") - basically a field from "tt_content" table
1215
     * @param string $extensionKey The extension key
1216
     * @throws \RuntimeException
1217
     */
1218
    public static function addPlugin($itemArray, $type = 'list_type', $extensionKey = null)
1219
    {
1220
        if (!isset($extensionKey)) {
1221
            throw new \InvalidArgumentException(
1222
                'No extension key could be determined when calling addPlugin()!'
1223
                . LF
1224
                . 'This method is meant to be called from Configuration/TCA/Overrides files. '
1225
                . 'The extension key needs to be specified as third parameter. '
1226
                . 'Calling it from any other place e.g. ext_localconf.php does not work and is not supported.',
1227
                1404068038
1228
            );
1229
        }
1230
        if (!$itemArray[2] && isset($GLOBALS['TYPO3_LOADED_EXT'][$extensionKey]['ext_icon'])) {
1231
            $itemArray[2] = 'EXT:' . $extensionKey . '/' . $GLOBALS['TYPO3_LOADED_EXT'][$extensionKey]['ext_icon'];
1232
        }
1233
        if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'])) {
1234
            foreach ($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'] as $k => $v) {
1235
                if ((string)$v[1] === (string)$itemArray[1]) {
1236
                    $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][$k] = $itemArray;
1237
                    return;
1238
                }
1239
            }
1240
            $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][] = $itemArray;
1241
        }
1242
    }
1243
1244
    /**
1245
     * Adds an entry to the "ds" array of the tt_content field "pi_flexform".
1246
     * This is used by plugins to add a flexform XML reference / content for use when they are selected as plugin or content element.
1247
     * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
1248
     *
1249
     * @param string $piKeyToMatch Plugin key as used in the list_type field. Use the asterisk * to match all list_type values.
1250
     * @param string $value Either a reference to a flex-form XML file (eg. "FILE:EXT:newloginbox/flexform_ds.xml") or the XML directly.
1251
     * @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.
1252
     * @see addPlugin()
1253
     */
1254
    public static function addPiFlexFormValue($piKeyToMatch, $value, $CTypeToMatch = 'list')
1255
    {
1256
        if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'])) {
1257
            $GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'][$piKeyToMatch . ',' . $CTypeToMatch] = $value;
1258
        }
1259
    }
1260
1261
    /**
1262
     * Adds the $table tablename to the list of tables allowed to be includes by content element type "Insert records"
1263
     * By using $content_table and $content_field you can also use the function for other tables.
1264
     * FOR USE IN files in Configuration/TCA/Overrides/*.php Use in ext_tables.php FILES may break the frontend.
1265
     *
1266
     * @param string $table Table name to allow for "insert record
1267
     * @param string $content_table Table name TO WHICH the $table name is applied. See $content_field as well.
1268
     * @param string $content_field Field name in the database $content_table in which $table is allowed to be added as a reference ("Insert Record")
1269
     */
1270
    public static function addToInsertRecords($table, $content_table = 'tt_content', $content_field = 'records')
1271
    {
1272
        if (is_array($GLOBALS['TCA'][$content_table]['columns']) && isset($GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'])) {
1273
            $GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'] .= ',' . $table;
1274
        }
1275
    }
1276
1277
    /**
1278
     * Add PlugIn to the default template rendering (previously called "Static Template #43")
1279
     *
1280
     * 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.
1281
     *
1282
     * The naming of #43 has historic reason and is rooted inside code which is now put into a TER extension called
1283
     * "statictemplates". Since the static template with uid 43 is the "content.default" and practically always used
1284
     * for rendering the content elements it's very useful to have this function automatically adding the necessary
1285
     * TypoScript for calling your plugin.
1286
     * The logic is now generalized and called "defaultContentRendering", see addTypoScript() as well.
1287
     *
1288
     * $type determines the type of frontend plugin:
1289
     * + list_type (default) - the good old "Insert plugin" entry
1290
     * + menu_type - a "Menu/Sitemap" entry
1291
     * + CType - a new content element type
1292
     * + header_layout - an additional header type (added to the selection of layout1-5)
1293
     * + includeLib - just includes the library for manual use somewhere in TypoScript.
1294
     * (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)
1295
     * FOR USE IN ext_localconf.php FILES
1296
     *
1297
     * @param string $key The extension key
1298
     * @param string $_ unused since TYPO3 CMS 8
1299
     * @param string $suffix Is used as a suffix of the class name (e.g. "_pi1")
1300
     * @param string $type See description above
1301
     * @param bool $cacheable If $cached is set as USER content object (cObject) is created - otherwise a USER_INT object is created.
1302
     */
1303
    public static function addPItoST43($key, $_, $suffix = '', $type = 'list_type', $cacheable = false)
1304
    {
1305
        $cN = self::getCN($key);
1306
        // General plugin
1307
        $pluginContent = trim('
1308
plugin.' . $cN . $suffix . ' = USER' . ($cacheable ? '' : '_INT') . '
1309
plugin.' . $cN . $suffix . '.userFunc = ' . $cN . $suffix . '->main
1310
');
1311
        self::addTypoScript($key, 'setup', '
1312
# Setting ' . $key . ' plugin TypoScript
1313
' . $pluginContent);
1314
        // Add after defaultContentRendering
1315
        switch ($type) {
1316
            case 'list_type':
1317
                $addLine = 'tt_content.list.20.' . $key . $suffix . ' = < plugin.' . $cN . $suffix;
1318
                break;
1319
            case 'menu_type':
1320
                $addLine = 'tt_content.menu.20.' . $key . $suffix . ' = < plugin.' . $cN . $suffix;
1321
                break;
1322
            case 'CType':
1323
                $addLine = trim('
1324
tt_content.' . $key . $suffix . ' =< lib.contentElement
1325
tt_content.' . $key . $suffix . ' {
1326
    templateName = Generic
1327
    20 =< plugin.' . $cN . $suffix . '
1328
}
1329
');
1330
                break;
1331
            case 'header_layout':
1332
                $addLine = 'lib.stdheader.10.' . $key . $suffix . ' = < plugin.' . $cN . $suffix;
1333
                break;
1334
            case 'includeLib':
1335
                $addLine = 'page.1000 = < plugin.' . $cN . $suffix;
1336
                break;
1337
            default:
1338
                $addLine = '';
1339
        }
1340
        if ($addLine) {
1341
            self::addTypoScript($key, 'setup', '
1342
# Setting ' . $key . ' plugin TypoScript
1343
' . $addLine . '
1344
', 'defaultContentRendering');
1345
        }
1346
    }
1347
1348
    /**
1349
     * Call this method to add an entry in the static template list found in sys_templates
1350
     * FOR USE IN Configuration/TCA/Overrides/sys_template.php Use in ext_tables.php may break the frontend.
1351
     *
1352
     * @param string $extKey Is of course the extension key
1353
     * @param string $path Is the path where the template files (fixed names) include_static.txt, 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:fluid_styled_content/Configuration/TypoScript/,EXT:da_newsletter_subscription/static/,EXT:cc_random_image/pi2/static/
1354
     * @param string $title Is the title in the selector box.
1355
     * @see addTypoScript()
1356
     */
1357
    public static function addStaticFile($extKey, $path, $title)
1358
    {
1359
        if (!$extKey) {
1360
            throw new \InvalidArgumentException('No extension key given.', 1507321291);
1361
        }
1362
        if (!$path) {
1363
            throw new \InvalidArgumentException('No file path given.', 1507321297);
1364
        }
1365
        if (is_array($GLOBALS['TCA']['sys_template']['columns'])) {
1366
            $value = str_replace(',', '', 'EXT:' . $extKey . '/' . $path);
1367
            $itemArray = [trim($title . ' (' . $extKey . ')'), $value];
1368
            $GLOBALS['TCA']['sys_template']['columns']['include_static_file']['config']['items'][] = $itemArray;
1369
        }
1370
    }
1371
1372
    /**
1373
     * Call this method to add an entry in the pageTSconfig list found in pages
1374
     * FOR USE in Configuration/TCA/Overrides/pages.php
1375
     *
1376
     * @param string $extKey The extension key
1377
     * @param string $filePath The path where the TSconfig file is located
1378
     * @param string $title The title in the selector box
1379
     */
1380
    public static function registerPageTSConfigFile($extKey, $filePath, $title)
1381
    {
1382
        if (!$extKey) {
1383
            throw new \InvalidArgumentException('No extension key given.', 1447789490);
1384
        }
1385
        if (!$filePath) {
1386
            throw new \InvalidArgumentException('No file path given.', 1447789491);
1387
        }
1388
        if (!isset($GLOBALS['TCA']['pages']['columns']) || !is_array($GLOBALS['TCA']['pages']['columns'])) {
1389
            throw new \InvalidArgumentException('No TCA definition for table "pages".', 1447789492);
1390
        }
1391
1392
        $value = str_replace(',', '', 'EXT:' . $extKey . '/' . $filePath);
1393
        $itemArray = [trim($title . ' (' . $extKey . ')'), $value];
1394
        $GLOBALS['TCA']['pages']['columns']['tsconfig_includes']['config']['items'][] = $itemArray;
1395
    }
1396
1397
    /**
1398
     * Adds $content to the default TypoScript setup code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_setup']
1399
     * Prefixed with a [GLOBAL] line
1400
     * FOR USE IN ext_localconf.php FILES
1401
     *
1402
     * @param string $content TypoScript Setup string
1403
     */
1404
    public static function addTypoScriptSetup($content)
1405
    {
1406
        $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'] .= '
1407
[GLOBAL]
1408
' . $content;
1409
    }
1410
1411
    /**
1412
     * Adds $content to the default TypoScript constants code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_constants']
1413
     * Prefixed with a [GLOBAL] line
1414
     * FOR USE IN ext_localconf.php FILES
1415
     *
1416
     * @param string $content TypoScript Constants string
1417
     */
1418
    public static function addTypoScriptConstants($content)
1419
    {
1420
        $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants'] .= '
1421
[GLOBAL]
1422
' . $content;
1423
    }
1424
1425
    /**
1426
     * Adds $content to the default TypoScript code for either setup or constants as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_*']
1427
     * (Basically this function can do the same as addTypoScriptSetup and addTypoScriptConstants - just with a little more hazzle, but also with some more options!)
1428
     * FOR USE IN ext_localconf.php FILES
1429
     * Note: As of TYPO3 CMS 6.2, static template #43 (content: default) was replaced with "defaultContentRendering" which makes it
1430
     * possible that a first extension like fluid_styled_content registers a "contentRendering" template (= a template that defines default content rendering TypoScript)
1431
     * by adding itself to $TYPO3_CONF_VARS[FE][contentRenderingTemplates][] = 'myext/Configuration/TypoScript'.
1432
     * An extension calling addTypoScript('myext', 'setup', $typoScript, 'defaultContentRendering') will add its TypoScript directly after;
1433
     * For now, "43" and "defaultContentRendering" can be used, but "defaultContentRendering" is more descriptive and
1434
     * should be used in the future.
1435
     *
1436
     * @param string $key Is the extension key (informative only).
1437
     * @param string $type Is either "setup" or "constants" and obviously determines which kind of TypoScript code we are adding.
1438
     * @param string $content Is the TS content, will be prefixed with a [GLOBAL] line and a comment-header.
1439
     * @param int|string 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.
1440
     */
1441
    public static function addTypoScript(string $key, string $type, string $content, $afterStaticUid = 0)
1442
    {
1443
        if ($type !== 'setup' && $type !== 'constants') {
1444
            throw new \InvalidArgumentException('Argument $type must be set to either "setup" or "constants" when calling addTypoScript from extension "' . $key . '"', 1507321200);
1445
        }
1446
        $content = '
1447
1448
[GLOBAL]
1449
#############################################
1450
## TypoScript added by extension "' . $key . '"
1451
#############################################
1452
1453
' . $content;
1454
        if ($afterStaticUid) {
1455
            // If 'content (default)' is targeted (static uid 43),
1456
            // the content is added after typoscript of type contentRendering, eg. fluid_styled_content, see EXT:frontend/TemplateService for more information on how the code is parsed
1457
            if ($afterStaticUid === 'defaultContentRendering' || $afterStaticUid == 43) {
1458
                $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.']['defaultContentRendering'] .= $content;
1459
            } else {
1460
                $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.'][$afterStaticUid] .= $content;
1461
            }
1462
        } else {
1463
            $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type] .= $content;
1464
        }
1465
    }
1466
1467
    /***************************************
1468
     *
1469
     * Internal extension management methods
1470
     *
1471
     ***************************************/
1472
    /**
1473
     * Find extension icon
1474
     *
1475
     * @param string $extensionPath Path to extension directory.
1476
     * @param bool $returnFullPath Return full path of file.
1477
     *
1478
     * @return string
1479
     */
1480
    public static function getExtensionIcon($extensionPath, $returnFullPath = false)
1481
    {
1482
        $icon = '';
1483
        $locationsToCheckFor = [
1484
            'Resources/Public/Icons/Extension.svg',
1485
            'Resources/Public/Icons/Extension.png',
1486
            'Resources/Public/Icons/Extension.gif',
1487
            'ext_icon.svg',
1488
            'ext_icon.png',
1489
            'ext_icon.gif',
1490
        ];
1491
        foreach ($locationsToCheckFor as $fileLocation) {
1492
            if (file_exists($extensionPath . $fileLocation)) {
1493
                $icon = $fileLocation;
1494
                break;
1495
            }
1496
        }
1497
        return $returnFullPath ? $extensionPath . $icon : $icon;
1498
    }
1499
1500
    /**
1501
     * Execute all ext_localconf.php files of loaded extensions.
1502
     * The method implements an optionally used caching mechanism that concatenates all
1503
     * ext_localconf.php files in one file.
1504
     *
1505
     * This is an internal method. It is only used during bootstrap and
1506
     * extensions should not use it!
1507
     *
1508
     * @param bool $allowCaching Whether or not to load / create concatenated cache file
1509
     * @access private
1510
     */
1511
    public static function loadExtLocalconf($allowCaching = true)
1512
    {
1513
        if ($allowCaching) {
1514
            $cacheIdentifier = self::getExtLocalconfCacheIdentifier();
1515
            /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1516
            $codeCache = self::getCacheManager()->getCache('cache_core');
1517
            if ($codeCache->has($cacheIdentifier)) {
1518
                $codeCache->requireOnce($cacheIdentifier);
1519
            } else {
1520
                self::loadSingleExtLocalconfFiles();
1521
                self::createExtLocalconfCacheEntry();
1522
            }
1523
        } else {
1524
            self::loadSingleExtLocalconfFiles();
1525
        }
1526
    }
1527
1528
    /**
1529
     * Execute ext_localconf.php files from extensions
1530
     */
1531
    protected static function loadSingleExtLocalconfFiles()
1532
    {
1533
        // This is the main array meant to be manipulated in the ext_localconf.php files
1534
        // In general it is recommended to not rely on it to be globally defined in that
1535
        // scope but to use $GLOBALS['TYPO3_CONF_VARS'] instead.
1536
        // Nevertheless we define it here as global for backwards compatibility.
1537
        global $TYPO3_CONF_VARS;
1538 View Code Duplication
        foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1539
            if ((is_array($extensionInformation) || $extensionInformation instanceof \ArrayAccess) && isset($extensionInformation['ext_localconf.php'])) {
1540
                // $_EXTKEY and $_EXTCONF are available in ext_localconf.php
1541
                // and are explicitly set in cached file as well
1542
                $_EXTCONF = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY] ?? null;
1543
                require $extensionInformation['ext_localconf.php'];
1544
            }
1545
        }
1546
    }
1547
1548
    /**
1549
     * Create cache entry for concatenated ext_localconf.php files
1550
     */
1551
    protected static function createExtLocalconfCacheEntry()
1552
    {
1553
        $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1554
        $phpCodeToCache = [];
1555
        // Set same globals as in loadSingleExtLocalconfFiles()
1556
        $phpCodeToCache[] = '/**';
1557
        $phpCodeToCache[] = ' * Compiled ext_localconf.php cache file';
1558
        $phpCodeToCache[] = ' */';
1559
        $phpCodeToCache[] = '';
1560
        $phpCodeToCache[] = 'global $TYPO3_CONF_VARS, $T3_SERVICES, $T3_VAR;';
1561
        $phpCodeToCache[] = '';
1562
        // Iterate through loaded extensions and add ext_localconf content
1563 View Code Duplication
        foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1564
            if (isset($extensionDetails['ext_localconf.php']) && $extensionDetails['ext_localconf.php']) {
1565
                // Include a header per extension to make the cache file more readable
1566
                $phpCodeToCache[] = '/**';
1567
                $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1568
                $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_localconf.php'];
1569
                $phpCodeToCache[] = ' */';
1570
                $phpCodeToCache[] = '';
1571
                // Set $_EXTKEY and $_EXTCONF for this extension
1572
                $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1573
                $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY] ?? null;';
1574
                $phpCodeToCache[] = '';
1575
                // Add ext_localconf.php content of extension
1576
                $phpCodeToCache[] = trim(file_get_contents($extensionDetails['ext_localconf.php']));
0 ignored issues
show
Bug introduced by
It seems like file_get_contents($exten...s['ext_localconf.php']) can also be of type false; however, parameter $str of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1576
                $phpCodeToCache[] = trim(/** @scrutinizer ignore-type */ file_get_contents($extensionDetails['ext_localconf.php']));
Loading history...
1577
                $phpCodeToCache[] = '';
1578
                $phpCodeToCache[] = '';
1579
            }
1580
        }
1581
        $phpCodeToCache = implode(LF, $phpCodeToCache);
1582
        // Remove all start and ending php tags from content
1583
        $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1584
        self::getCacheManager()->getCache('cache_core')->set(self::getExtLocalconfCacheIdentifier(), $phpCodeToCache);
1585
    }
1586
1587
    /**
1588
     * Cache identifier of concatenated ext_localconf file
1589
     *
1590
     * @return string
1591
     */
1592
    protected static function getExtLocalconfCacheIdentifier()
1593
    {
1594
        return 'ext_localconf_' . sha1(TYPO3_version . PATH_site . 'extLocalconf' . serialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']));
1595
    }
1596
1597
    /**
1598
     * Wrapper for buildBaseTcaFromSingleFiles handling caching.
1599
     *
1600
     * This builds 'base' TCA that is later overloaded by ext_tables.php.
1601
     *
1602
     * Use a cache file if exists and caching is allowed.
1603
     *
1604
     * This is an internal method. It is only used during bootstrap and
1605
     * extensions should not use it!
1606
     *
1607
     * @param bool $allowCaching Whether or not to load / create concatenated cache file
1608
     * @access private
1609
     */
1610
    public static function loadBaseTca($allowCaching = true)
1611
    {
1612
        if ($allowCaching) {
1613
            $cacheIdentifier = static::getBaseTcaCacheIdentifier();
1614
            /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1615
            $codeCache = static::getCacheManager()->getCache('cache_core');
1616
            $cacheData = $codeCache->requireOnce($cacheIdentifier);
1617
            if ($cacheData) {
1618
                $GLOBALS['TCA'] = $cacheData['tca'];
1619
                GeneralUtility::setSingletonInstance(
1620
                    CategoryRegistry::class,
1621
                    unserialize(
1622
                        $cacheData['categoryRegistry'],
1623
                        ['allowed_classes' => [CategoryRegistry::class]]
1624
                    )
1625
                );
1626
            } else {
1627
                static::buildBaseTcaFromSingleFiles();
1628
                static::createBaseTcaCacheFile();
1629
            }
1630
        } else {
1631
            static::buildBaseTcaFromSingleFiles();
1632
        }
1633
    }
1634
1635
    /**
1636
     * Find all Configuration/TCA/* files of extensions and create base TCA from it.
1637
     * The filename must be the table name in $GLOBALS['TCA'], and the content of
1638
     * the file should return an array with content of a specific table.
1639
     *
1640
     * @see Extension core, extensionmanager and others for examples.
1641
     */
1642
    protected static function buildBaseTcaFromSingleFiles()
1643
    {
1644
        $GLOBALS['TCA'] = [];
1645
1646
        $activePackages = static::$packageManager->getActivePackages();
1647
1648
        // First load "full table" files from Configuration/TCA
1649 View Code Duplication
        foreach ($activePackages as $package) {
1650
            $tcaConfigurationDirectory = $package->getPackagePath() . 'Configuration/TCA';
1651
            if (is_dir($tcaConfigurationDirectory)) {
1652
                $files = scandir($tcaConfigurationDirectory);
1653
                foreach ($files as $file) {
1654
                    if (
1655
                        is_file($tcaConfigurationDirectory . '/' . $file)
1656
                        && ($file !== '.')
1657
                        && ($file !== '..')
1658
                        && (substr($file, -4, 4) === '.php')
1659
                    ) {
1660
                        $tcaOfTable = require($tcaConfigurationDirectory . '/' . $file);
1661
                        if (is_array($tcaOfTable)) {
1662
                            // TCA table name is filename without .php suffix, eg 'sys_notes', not 'sys_notes.php'
1663
                            $tcaTableName = substr($file, 0, -4);
1664
                            $GLOBALS['TCA'][$tcaTableName] = $tcaOfTable;
1665
                        }
1666
                    }
1667
                }
1668
            }
1669
        }
1670
1671
        // Apply category stuff
1672
        CategoryRegistry::getInstance()->applyTcaForPreRegisteredTables();
1673
1674
        // Execute override files from Configuration/TCA/Overrides
1675 View Code Duplication
        foreach ($activePackages as $package) {
1676
            $tcaOverridesPathForPackage = $package->getPackagePath() . 'Configuration/TCA/Overrides';
1677
            if (is_dir($tcaOverridesPathForPackage)) {
1678
                $files = scandir($tcaOverridesPathForPackage);
1679
                foreach ($files as $file) {
1680
                    if (
1681
                        is_file($tcaOverridesPathForPackage . '/' . $file)
1682
                        && ($file !== '.')
1683
                        && ($file !== '..')
1684
                        && (substr($file, -4, 4) === '.php')
1685
                    ) {
1686
                        require($tcaOverridesPathForPackage . '/' . $file);
1687
                    }
1688
                }
1689
            }
1690
        }
1691
1692
        // TCA migration
1693
        // @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.
1694
        $tcaMigration = GeneralUtility::makeInstance(TcaMigration::class);
1695
        $GLOBALS['TCA'] = $tcaMigration->migrate($GLOBALS['TCA']);
1696
        $messages = $tcaMigration->getMessages();
1697
        if (!empty($messages)) {
1698
            $context = 'Automatic TCA migration done during bootstrap. Please adapt TCA accordingly, these migrations'
1699
                . ' will be removed. The backend module "Configuration -> TCA" shows the modified values.'
1700
                . ' Please adapt these areas:';
1701
            array_unshift($messages, $context);
1702
            trigger_error(implode(LF, $messages), E_USER_DEPRECATED);
1703
        }
1704
1705
        // TCA preparation
1706
        $tcaPreparation = GeneralUtility::makeInstance(TcaPreparation::class);
1707
        $GLOBALS['TCA'] = $tcaPreparation->prepare($GLOBALS['TCA']);
1708
1709
        static::emitTcaIsBeingBuiltSignal($GLOBALS['TCA']);
1710
    }
1711
1712
    /**
1713
     * Emits the signal and uses the result of slots for the final TCA
1714
     * This means, that *all* slots *must* return the complete TCA to
1715
     * be effective. If a slot calls methods that manipulate the global array,
1716
     * it needs to return the global array in the end. To be future proof,
1717
     * a slot should manipulate the signal argument only and return it
1718
     * after manipulation.
1719
     *
1720
     * @param array $tca
1721
     */
1722
    protected static function emitTcaIsBeingBuiltSignal(array $tca)
1723
    {
1724
        list($tca) = static::getSignalSlotDispatcher()->dispatch(__CLASS__, 'tcaIsBeingBuilt', [$tca]);
1725
        $GLOBALS['TCA'] = $tca;
1726
    }
1727
1728
    /**
1729
     * Cache base $GLOBALS['TCA'] to cache file to require the whole thing in one
1730
     * file for next access instead of cycling through all extensions again.
1731
     */
1732
    protected static function createBaseTcaCacheFile()
1733
    {
1734
        /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1735
        $codeCache = self::getCacheManager()->getCache('cache_core');
1736
        $codeCache->set(
1737
            static::getBaseTcaCacheIdentifier(),
1738
            'return '
1739
                . var_export(['tca' => $GLOBALS['TCA'], 'categoryRegistry' => serialize(CategoryRegistry::getInstance())], true)
1740
                . ';'
1741
        );
1742
    }
1743
1744
    /**
1745
     * Cache identifier of base TCA cache entry.
1746
     *
1747
     * @return string
1748
     */
1749
    protected static function getBaseTcaCacheIdentifier()
1750
    {
1751
        return 'tca_base_' . sha1(TYPO3_version . PATH_site . 'tca_code' . serialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']));
1752
    }
1753
1754
    /**
1755
     * Execute all ext_tables.php files of loaded extensions.
1756
     * The method implements an optionally used caching mechanism that concatenates all
1757
     * ext_tables.php files in one file.
1758
     *
1759
     * This is an internal method. It is only used during bootstrap and
1760
     * extensions should not use it!
1761
     *
1762
     * @param bool $allowCaching Whether to load / create concatenated cache file
1763
     * @access private
1764
     */
1765
    public static function loadExtTables($allowCaching = true)
1766
    {
1767
        if ($allowCaching && !self::$extTablesWasReadFromCacheOnce) {
1768
            self::$extTablesWasReadFromCacheOnce = true;
1769
            $cacheIdentifier = self::getExtTablesCacheIdentifier();
1770
            /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1771
            $codeCache = self::getCacheManager()->getCache('cache_core');
1772
            if ($codeCache->has($cacheIdentifier)) {
1773
                $codeCache->requireOnce($cacheIdentifier);
1774
            } else {
1775
                self::loadSingleExtTablesFiles();
1776
                self::createExtTablesCacheEntry();
1777
            }
1778
        } else {
1779
            self::loadSingleExtTablesFiles();
1780
        }
1781
    }
1782
1783
    /**
1784
     * Load ext_tables.php as single files
1785
     */
1786
    protected static function loadSingleExtTablesFiles()
1787
    {
1788
        // In general it is recommended to not rely on it to be globally defined in that
1789
        // scope, but we can not prohibit this without breaking backwards compatibility
1790
        global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
1791
        global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;
1792
        global $PAGES_TYPES, $TBE_STYLES;
1793
        global $_EXTKEY;
1794
        // Load each ext_tables.php file of loaded extensions
1795 View Code Duplication
        foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1796
            if ((is_array($extensionInformation) || $extensionInformation instanceof \ArrayAccess) && !empty($extensionInformation['ext_tables.php'])) {
1797
                // $_EXTKEY and $_EXTCONF are available in ext_tables.php
1798
                // and are explicitly set in cached file as well
1799
                $_EXTCONF = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY] ?? null;
1800
                require $extensionInformation['ext_tables.php'];
1801
            }
1802
        }
1803
    }
1804
1805
    /**
1806
     * Create concatenated ext_tables.php cache file
1807
     */
1808
    protected static function createExtTablesCacheEntry()
1809
    {
1810
        $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1811
        $phpCodeToCache = [];
1812
        // Set same globals as in loadSingleExtTablesFiles()
1813
        $phpCodeToCache[] = '/**';
1814
        $phpCodeToCache[] = ' * Compiled ext_tables.php cache file';
1815
        $phpCodeToCache[] = ' */';
1816
        $phpCodeToCache[] = '';
1817
        $phpCodeToCache[] = 'global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;';
1818
        $phpCodeToCache[] = 'global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;';
1819
        $phpCodeToCache[] = 'global $PAGES_TYPES, $TBE_STYLES;';
1820
        $phpCodeToCache[] = 'global $_EXTKEY;';
1821
        $phpCodeToCache[] = '';
1822
        // Iterate through loaded extensions and add ext_tables content
1823 View Code Duplication
        foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1824
            if (isset($extensionDetails['ext_tables.php']) && $extensionDetails['ext_tables.php']) {
1825
                // Include a header per extension to make the cache file more readable
1826
                $phpCodeToCache[] = '/**';
1827
                $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1828
                $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_tables.php'];
1829
                $phpCodeToCache[] = ' */';
1830
                $phpCodeToCache[] = '';
1831
                // Set $_EXTKEY and $_EXTCONF for this extension
1832
                $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1833
                $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY] ?? null;';
1834
                $phpCodeToCache[] = '';
1835
                // Add ext_tables.php content of extension
1836
                $phpCodeToCache[] = trim(file_get_contents($extensionDetails['ext_tables.php']));
0 ignored issues
show
Bug introduced by
It seems like file_get_contents($exten...ails['ext_tables.php']) can also be of type false; however, parameter $str of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1836
                $phpCodeToCache[] = trim(/** @scrutinizer ignore-type */ file_get_contents($extensionDetails['ext_tables.php']));
Loading history...
1837
                $phpCodeToCache[] = '';
1838
            }
1839
        }
1840
        $phpCodeToCache = implode(LF, $phpCodeToCache);
1841
        // Remove all start and ending php tags from content
1842
        $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1843
        self::getCacheManager()->getCache('cache_core')->set(self::getExtTablesCacheIdentifier(), $phpCodeToCache);
1844
    }
1845
1846
    /**
1847
     * Cache identifier for concatenated ext_tables.php files
1848
     *
1849
     * @return string
1850
     */
1851
    protected static function getExtTablesCacheIdentifier()
1852
    {
1853
        return 'ext_tables_' . sha1(TYPO3_version . PATH_site . 'extTables' . serialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']));
1854
    }
1855
1856
    /**
1857
     * Remove cache files from php code cache, grouped by 'system'
1858
     *
1859
     * This removes the following cache entries:
1860
     * - autoloader cache registry
1861
     * - cache loaded extension array
1862
     * - ext_localconf concatenation
1863
     * - ext_tables concatenation
1864
     *
1865
     * This method is usually only used by extension that fiddle
1866
     * with the loaded extensions. An example is the extension
1867
     * manager and the install tool.
1868
     *
1869
     * @deprecated CacheManager provides the functionality directly
1870
     */
1871
    public static function removeCacheFiles()
1872
    {
1873
        trigger_error('removeCacheFiles() will be removed in TYPO3 v10. Use CacheManager directly to flush all system caches.', E_USER_DEPRECATED);
1874
        self::getCacheManager()->flushCachesInGroup('system');
1875
    }
1876
1877
    /**
1878
     * Gets an array of loaded extension keys
1879
     *
1880
     * @return array Loaded extensions
1881
     */
1882
    public static function getLoadedExtensionListArray()
1883
    {
1884
        return array_keys(static::$packageManager->getActivePackages());
1885
    }
1886
1887
    /**
1888
     * Loads given extension
1889
     *
1890
     * Warning: This method only works if the ugrade wizard to transform
1891
     * localconf.php to LocalConfiguration.php was already run
1892
     *
1893
     * @param string $extensionKey Extension key to load
1894
     * @throws \RuntimeException
1895
     */
1896
    public static function loadExtension($extensionKey)
1897
    {
1898
        if (static::$packageManager->isPackageActive($extensionKey)) {
1899
            throw new \RuntimeException('Extension already loaded', 1342345486);
1900
        }
1901
        static::$packageManager->activatePackage($extensionKey);
1902
    }
1903
1904
    /**
1905
     * Unloads given extension
1906
     *
1907
     * Warning: This method only works if the ugrade wizard to transform
1908
     * localconf.php to LocalConfiguration.php was already run
1909
     *
1910
     * @param string $extensionKey Extension key to remove
1911
     * @throws \RuntimeException
1912
     */
1913
    public static function unloadExtension($extensionKey)
1914
    {
1915
        if (!static::$packageManager->isPackageActive($extensionKey)) {
1916
            throw new \RuntimeException('Extension not loaded', 1342345487);
1917
        }
1918
        static::$packageManager->deactivatePackage($extensionKey);
1919
    }
1920
1921
    /**
1922
     * Makes a table categorizable by adding value into the category registry.
1923
     * FOR USE IN ext_localconf.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1924
     *
1925
     * @param string $extensionKey Extension key to be used
1926
     * @param string $tableName Name of the table to be categorized
1927
     * @param string $fieldName Name of the field to be used to store categories
1928
     * @param array $options Additional configuration options
1929
     * @param bool $override If TRUE, any category configuration for the same table / field is removed before the new configuration is added
1930
     * @see addTCAcolumns
1931
     * @see addToAllTCAtypes
1932
     */
1933
    public static function makeCategorizable($extensionKey, $tableName, $fieldName = 'categories', array $options = [], $override = false)
1934
    {
1935
        // Update the category registry
1936
        $result = CategoryRegistry::getInstance()->add($extensionKey, $tableName, $fieldName, $options, $override);
1937
        if ($result === false) {
1938
            $message = CategoryRegistry::class . ': no category registered for table "%s". Key was already registered.';
1939
            /** @var $logger \TYPO3\CMS\Core\Log\Logger */
1940
            $logger = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Log\LogManager::class)->getLogger(__CLASS__);
1941
            $logger->warning(
1942
                sprintf($message, $tableName)
1943
            );
1944
        }
1945
    }
1946
}
1947