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