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