[BUGFIX] Better positionName extraction in executePositionedStringInsertion
[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 if (strpos($positionName, ';;') !== false) {
670 $positionName = str_replace(';;', ';[^;]*;', $positionName);
671 }
672
673 $pattern = ('/(^|,\\s*)(' . preg_quote($positionName, '/') . ')(;[^,$]+)?(,|$)/');
674 switch ($location) {
675 case 'after':
676 $newList = preg_replace($pattern, '$1$2$3, ' . $insertionList . '$4', $list);
677 break;
678 case 'before':
679 $newList = preg_replace($pattern, '$1' . $insertionList . ', $2$3$4', $list);
680 break;
681 case 'replace':
682 $newList = preg_replace($pattern, '$1' . $insertionList . '$4', $list);
683 break;
684 default:
685 }
686
687 // When preg_replace did not replace anything; append the $insertionList.
688 if ($list === $newList) {
689 return $list . ', ' . $insertionList;
690 }
691 return $newList;
692 }
693
694 /**
695 * Compares an existing list of items and a list of items to be inserted
696 * and returns a duplicate-free variant of that insertion list.
697 *
698 * Example:
699 * + list: 'field_a, field_b, field_c'
700 * + insertion: 'field_b, field_d, field_c'
701 * -> new insertion: 'field_d'
702 *
703 * Duplicate values in $insertionList are removed.
704 *
705 * @param string $insertionList The list of items to inserted
706 * @param string $list The list of items to be extended (default: '')
707 * @return string Duplicate-free list of items to be inserted
708 */
709 protected static function removeDuplicatesForInsertion($insertionList, $list = '')
710 {
711 $insertionListParts = preg_split('/\\s*,\\s*/', $insertionList);
712 $listMatches = array();
713 if ($list !== '') {
714 preg_match_all('/(?:^|,)\\s*\\b([^;,]+)\\b[^,]*/', $list, $listMatches);
715 $listMatches = $listMatches[1];
716 }
717
718 $cleanInsertionListParts = array();
719 foreach ($insertionListParts as $fieldName) {
720 $fieldNameParts = explode(';', $fieldName, 2);
721 $cleanFieldName = $fieldNameParts[0];
722 if (
723 $cleanFieldName === '--linebreak--'
724 || (
725 !in_array($cleanFieldName, $cleanInsertionListParts, true)
726 && !in_array($cleanFieldName, $listMatches, true)
727 )
728 ) {
729 $cleanInsertionListParts[] = $fieldName;
730 }
731 }
732 return implode(', ', $cleanInsertionListParts);
733 }
734
735 /**
736 * Generates an array of fields/items with additional information such as e.g. the name of the palette.
737 *
738 * @param string $itemList List of fields/items to be splitted up
739 * @return array An array with the names of the fields/items as keys and additional information
740 */
741 protected static function explodeItemList($itemList)
742 {
743 $items = array();
744 $itemParts = GeneralUtility::trimExplode(',', $itemList, true);
745 foreach ($itemParts as $itemPart) {
746 $itemDetails = GeneralUtility::trimExplode(';', $itemPart, false, 5);
747 $key = $itemDetails[0];
748 if (strpos($key, '--') !== false) {
749 // 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!
750 $key .= count($items);
751 }
752 if (!isset($items[$key])) {
753 $items[$key] = array(
754 'rawData' => $itemPart,
755 'details' => array()
756 );
757 $details = array(0 => 'field', 1 => 'label', 2 => 'palette');
758 foreach ($details as $id => $property) {
759 $items[$key]['details'][$property] = isset($itemDetails[$id]) ? $itemDetails[$id] : '';
760 }
761 }
762 }
763 return $items;
764 }
765
766 /**
767 * Generates a list of fields/items out of an array provided by the function getFieldsOfFieldList().
768 *
769 * @see explodeItemList
770 * @param array $items The array of fields/items with optional additional information
771 * @param bool $useRawData Use raw data instead of building by using the details (default: FALSE)
772 * @return string The list of fields/items which gets used for $GLOBALS['TCA'][<table>]['types'][<type>]['showitem']
773 */
774 protected static function generateItemList(array $items, $useRawData = false)
775 {
776 $itemParts = array();
777 foreach ($items as $item => $itemDetails) {
778 if (strpos($item, '--') !== false) {
779 // 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.
780 $item = str_replace(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), '', $item);
781 }
782 if ($useRawData) {
783 $itemParts[] = $itemDetails['rawData'];
784 } else {
785 if (count($itemDetails['details']) > 1) {
786 $details = array('palette', 'label', 'field');
787 $elements = array();
788 $addEmpty = false;
789 foreach ($details as $property) {
790 if ($itemDetails['details'][$property] !== '' || $addEmpty) {
791 $addEmpty = true;
792 array_unshift($elements, $itemDetails['details'][$property]);
793 }
794 }
795 $item = implode(';', $elements);
796 }
797 $itemParts[] = $item;
798 }
799 }
800 return implode(', ', $itemParts);
801 }
802
803 /**
804 * Add tablename to default list of allowed tables on pages (in $PAGES_TYPES)
805 * Will add the $table to the list of tables allowed by default on pages as setup by $PAGES_TYPES['default']['allowedTables']
806 * FOR USE IN ext_tables.php FILES
807 *
808 * @param string $table Table name
809 * @return void
810 */
811 public static function allowTableOnStandardPages($table)
812 {
813 $GLOBALS['PAGES_TYPES']['default']['allowedTables'] .= ',' . $table;
814 }
815
816 /**
817 * Adds an ExtJS module (main or sub) to the backend interface
818 * FOR USE IN ext_tables.php FILES
819 *
820 * @static
821 * @param string $extensionName
822 * @param string $mainModuleName Is the main module key
823 * @param string $subModuleName Is the submodule key, if blank a plain main module is generated
824 * @param string $position Passed to \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModule, see reference there
825 * @param array $moduleConfiguration Icon with array keys: access, icon, labels to configure the module
826 * @throws \InvalidArgumentException
827 */
828 public static function addExtJSModule($extensionName, $mainModuleName, $subModuleName = '', $position = '', array $moduleConfiguration = array())
829 {
830 if (empty($extensionName)) {
831 throw new \InvalidArgumentException('The extension name must not be empty', 1325938973);
832 }
833 $extensionKey = GeneralUtility::camelCaseToLowerCaseUnderscored($extensionName);
834 $extensionName = str_replace(' ', '', ucwords(str_replace('_', ' ', $extensionName)));
835 $defaultModuleConfiguration = array(
836 'access' => 'admin',
837 'icon' => self::extRelPath('backend') . 'Resources/Public/Images/Logo.png',
838 'labels' => '',
839 'extRelPath' => self::extRelPath($extensionKey) . 'Classes/'
840 );
841 // Add mandatory parameter to use new pagetree
842 if ($mainModuleName === 'web') {
843 $defaultModuleConfiguration['navigationComponentId'] = 'typo3-pagetree';
844 }
845 ArrayUtility::mergeRecursiveWithOverrule($defaultModuleConfiguration, $moduleConfiguration);
846 $moduleConfiguration = $defaultModuleConfiguration;
847 if ($subModuleName !== '') {
848 $moduleSignature = $mainModuleName . '_' . $subModuleName;
849 } else {
850 $moduleSignature = $mainModuleName;
851 }
852 $moduleConfiguration['name'] = $moduleSignature;
853 $moduleConfiguration['script'] = 'extjspaneldummy.html';
854 $moduleConfiguration['extensionName'] = $extensionName;
855 $moduleConfiguration['configureModuleFunction'] = array(ExtensionManagementUtility::class, 'configureModule');
856 $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature] = $moduleConfiguration;
857 self::addModule($mainModuleName, $subModuleName, $position);
858 }
859
860 /**
861 * This method is called from \TYPO3\CMS\Backend\Module\ModuleLoader::checkMod
862 * and it replaces old conf.php.
863 *
864 * @param string $moduleSignature The module name
865 * @return array Configuration of the module
866 */
867 public static function configureModule($moduleSignature)
868 {
869 $moduleConfiguration = $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature];
870 if (!empty($moduleConfiguration['labels']['tabs_images']['tab'])) {
871 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.');
872 $moduleConfiguration['icon'] = $moduleConfiguration['labels']['tabs_images']['tab'];
873 unset($moduleConfiguration['labels']['tabs_images']['tab']);
874 }
875
876 // Register the icon and move it too "iconIdentifier"
877 if (!empty($moduleConfiguration['icon'])) {
878 $iconIdentifier = 'module-' . $moduleSignature;
879 $iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
880 $iconRegistry->registerIcon($iconIdentifier, BitmapIconProvider::class, [
881 'source' => GeneralUtility::getFileAbsFileName($moduleConfiguration['icon'])
882 ]);
883 $moduleConfiguration['iconIdentifier'] = $iconIdentifier;
884 unset($moduleConfiguration['icon']);
885 }
886
887 return $moduleConfiguration;
888 }
889
890 /**
891 * Adds a module (main or sub) to the backend interface
892 * FOR USE IN ext_tables.php FILES
893 *
894 * @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.
895 * @param string $sub The submodule key. If $sub is not set a blank $main module is created.
896 * @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.
897 * @param string $path The absolute path to the module. Was used prior to TYPO3 v8, use $moduleConfiguration[routeTarget] now
898 * @param array $moduleConfiguration additional configuration, previously put in "conf.php" of the module directory
899 * @return void
900 */
901 public static function addModule($main, $sub = '', $position = '', $path = null, $moduleConfiguration = array())
902 {
903 // If there is already a main module by this name:
904 // Adding the submodule to the correct position:
905 if (isset($GLOBALS['TBE_MODULES'][$main]) && $sub) {
906 list($place, $modRef) = GeneralUtility::trimExplode(':', $position, true);
907 $modules = ',' . $GLOBALS['TBE_MODULES'][$main] . ',';
908 if ($place === null || ($modRef !== null && !GeneralUtility::inList($modules, $modRef))) {
909 $place = 'bottom';
910 }
911 $modRef = ',' . $modRef . ',';
912 if (!GeneralUtility::inList($modules, $sub)) {
913 switch (strtolower($place)) {
914 case 'after':
915 $modules = str_replace($modRef, $modRef . $sub . ',', $modules);
916 break;
917 case 'before':
918 $modules = str_replace($modRef, ',' . $sub . $modRef, $modules);
919 break;
920 case 'top':
921 $modules = $sub . $modules;
922 break;
923 case 'bottom':
924 default:
925 $modules = $modules . $sub;
926 }
927 }
928 // Re-inserting the submodule list:
929 $GLOBALS['TBE_MODULES'][$main] = trim($modules, ',');
930 } else {
931 // Create new main modules with only one submodule, $sub (or none if $sub is blank)
932 $GLOBALS['TBE_MODULES'][$main] = $sub;
933 }
934
935 // add additional configuration
936 if (is_array($moduleConfiguration) && !empty($moduleConfiguration)) {
937 $fullModuleSignature = $main . ($sub ? '_' . $sub : '');
938
939 if (!empty($moduleConfiguration['labels']['tabs_images']['tab'])) {
940 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.');
941 $moduleConfiguration['icon'] = $moduleConfiguration['labels']['tabs_images']['tab'];
942 unset($moduleConfiguration['labels']['tabs_images']['tab']);
943 }
944
945 if (!empty($moduleConfiguration['icon'])) {
946 $iconIdentifier = 'module-' . $fullModuleSignature;
947 $iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
948 $iconRegistry->registerIcon($iconIdentifier, BitmapIconProvider::class, [
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 * @return void
967 */
968 public static function registerExtDirectComponent($endpointName, $callbackClass, $moduleName = null, $accessLevel = null)
969 {
970 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ExtDirect'][$endpointName] = array(
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] = array(
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 * @return void
1007 * @see \TYPO3\CMS\Backend\Module\BaseScriptClass::mergeExternalItems()
1008 */
1009 public static function insertModuleFunction($modname, $className, $classPath = null, $title, $MM_key = 'function', $WS = '')
1010 {
1011 $GLOBALS['TBE_MODULES_EXT'][$modname]['MOD_MENU'][$MM_key][$className] = array(
1012 'name' => $className,
1013 'title' => $title,
1014 'ws' => $WS
1015 );
1016 }
1017
1018 /**
1019 * Adds some more content to a key of TYPO3_CONF_VARS array.
1020 *
1021 * This also tracks which content was added by extensions (in TYPO3_CONF_VARS_extensionAdded)
1022 * so that they cannot be editted again through the Install Tool.
1023 *
1024 * @static
1025 * @param string $group The group ('FE', 'BE', 'SYS' ...)
1026 * @param string $key The key of this setting within the group
1027 * @param string $content The text to add (include leading "\n" in case of multi-line entries)
1028 * @return void
1029 */
1030 public static function appendToTypoConfVars($group, $key, $content)
1031 {
1032 $GLOBALS['TYPO3_CONF_VARS_extensionAdded'][$group][$key] .= $content;
1033 $GLOBALS['TYPO3_CONF_VARS'][$group][$key] .= $content;
1034 }
1035
1036 /**
1037 * Adds $content to the default Page TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultPageTSconfig']
1038 * Prefixed with a [GLOBAL] line
1039 * FOR USE IN ext_tables.php/ext_localconf.php FILES
1040 *
1041 * @param string $content Page TSconfig content
1042 * @return void
1043 */
1044 public static function addPageTSConfig($content)
1045 {
1046 self::appendToTypoConfVars('BE', 'defaultPageTSconfig', '
1047 [GLOBAL]
1048 ' . $content);
1049 }
1050
1051 /**
1052 * Adds $content to the default User TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultUserTSconfig']
1053 * Prefixed with a [GLOBAL] line
1054 * FOR USE IN ext_tables.php/ext_localconf.php FILES
1055 *
1056 * @param string $content User TSconfig content
1057 * @return void
1058 */
1059 public static function addUserTSConfig($content)
1060 {
1061 self::appendToTypoConfVars('BE', 'defaultUserTSconfig', '
1062 [GLOBAL]
1063 ' . $content);
1064 }
1065
1066 /**
1067 * Adds a reference to a locallang file with $GLOBALS['TCA_DESCR'] labels
1068 * FOR USE IN ext_tables.php FILES
1069 * 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.
1070 *
1071 * @param string $tca_descr_key Description key. Typically a database table (like "pages") but for applications can be other strings, but prefixed with "_MOD_")
1072 * @param string $file_ref File reference to locallang file, eg. "EXT:lang/locallang_csh_pages.xlf" (or ".xml")
1073 * @return void
1074 */
1075 public static function addLLrefForTCAdescr($tca_descr_key, $file_ref)
1076 {
1077 if ($tca_descr_key) {
1078 if (!is_array($GLOBALS['TCA_DESCR'][$tca_descr_key])) {
1079 $GLOBALS['TCA_DESCR'][$tca_descr_key] = array();
1080 }
1081 if (!is_array($GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'])) {
1082 $GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'] = array();
1083 }
1084 $GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'][] = $file_ref;
1085 }
1086 }
1087
1088 /**
1089 * Registers a navigation component
1090 *
1091 * @param string $module
1092 * @param string $componentId
1093 * @param string $extensionKey
1094 * @throws \RuntimeException
1095 *@return void
1096 */
1097 public static function addNavigationComponent($module, $componentId, $extensionKey = null)
1098 {
1099 $extensionKey = $extensionKey ?: $GLOBALS['_EXTKEY'];
1100 if (!isset($extensionKey)) {
1101 throw new \RuntimeException('No extensionKey set in addNavigationComponent(). Provide it as third Parameter', 1404068039);
1102 }
1103 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module] = array(
1104 'componentId' => $componentId,
1105 'extKey' => $extensionKey,
1106 'isCoreComponent' => false
1107 );
1108 }
1109
1110 /**
1111 * Registers a core navigation component
1112 *
1113 * @param string $module
1114 * @param string $componentId
1115 * @return void
1116 */
1117 public static function addCoreNavigationComponent($module, $componentId)
1118 {
1119 self::addNavigationComponent($module, $componentId);
1120 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module]['isCoreComponent'] = true;
1121 }
1122
1123 /**************************************
1124 *
1125 * Adding SERVICES features
1126 *
1127 ***************************************/
1128 /**
1129 * Adds a service to the global services array
1130 *
1131 * @param string $extKey Extension key
1132 * @param string $serviceType Service type, must not be prefixed "tx_" or "Tx_"
1133 * @param string $serviceKey Service key, must be prefixed "tx_", "Tx_" or "user_"
1134 * @param array $info Service description array
1135 * @return void
1136 */
1137 public static function addService($extKey, $serviceType, $serviceKey, $info)
1138 {
1139 if ($serviceType && is_array($info)) {
1140 $info['priority'] = max(0, min(100, $info['priority']));
1141 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = $info;
1142 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['extKey'] = $extKey;
1143 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceKey'] = $serviceKey;
1144 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceType'] = $serviceType;
1145 // Change the priority (and other values) from $GLOBALS['TYPO3_CONF_VARS']
1146 // $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]['priority']
1147 // even the activation is possible (a unix service might be possible on windows for some reasons)
1148 if (is_array($GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey])) {
1149 // No check is done here - there might be configuration values only the service type knows about, so
1150 // we pass everything
1151 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = array_merge($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey], $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]);
1152 }
1153 // OS check
1154 // Empty $os means 'not limited to one OS', therefore a check is not needed
1155 if ($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] && $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os'] != '') {
1156 // TYPO3_OS is not yet defined
1157 $os_type = stripos(PHP_OS, 'win') !== false && !stripos(PHP_OS, 'darwin') !== false ? 'WIN' : 'UNIX';
1158 $os = GeneralUtility::trimExplode(',', strtoupper($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os']));
1159 if (!in_array($os_type, $os)) {
1160 self::deactivateService($serviceType, $serviceKey);
1161 }
1162 }
1163 // Convert subtype list to array for quicker access
1164 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'] = array();
1165 $serviceSubTypes = GeneralUtility::trimExplode(',', $info['subtype']);
1166 foreach ($serviceSubTypes as $subtype) {
1167 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'][$subtype] = $subtype;
1168 }
1169 }
1170 }
1171
1172 /**
1173 * Find the available service with highest priority
1174 *
1175 * @param string $serviceType Service type
1176 * @param string $serviceSubType Service sub type
1177 * @param mixed $excludeServiceKeys Service keys that should be excluded in the search for a service. Array or comma list.
1178 * @return mixed Service info array if a service was found, FALSE otherwise
1179 */
1180 public static function findService($serviceType, $serviceSubType = '', $excludeServiceKeys = array())
1181 {
1182 $serviceKey = false;
1183 $serviceInfo = false;
1184 $priority = 0;
1185 $quality = 0;
1186 if (!is_array($excludeServiceKeys)) {
1187 $excludeServiceKeys = GeneralUtility::trimExplode(',', $excludeServiceKeys, true);
1188 }
1189 if (is_array($GLOBALS['T3_SERVICES'][$serviceType])) {
1190 foreach ($GLOBALS['T3_SERVICES'][$serviceType] as $key => $info) {
1191 if (in_array($key, $excludeServiceKeys)) {
1192 continue;
1193 }
1194 // Select a subtype randomly
1195 // Useful to start a service by service key without knowing his subtypes - for testing purposes
1196 if ($serviceSubType == '*') {
1197 $serviceSubType = key($info['serviceSubTypes']);
1198 }
1199 // This matches empty subtype too
1200 if ($info['available'] && ($info['subtype'] == $serviceSubType || $info['serviceSubTypes'][$serviceSubType]) && $info['priority'] >= $priority) {
1201 // Has a lower quality than the already found, therefore we skip this service
1202 if ($info['priority'] == $priority && $info['quality'] < $quality) {
1203 continue;
1204 }
1205 // Check if the service is available
1206 $info['available'] = self::isServiceAvailable($serviceType, $key, $info);
1207 // Still available after exec check?
1208 if ($info['available']) {
1209 $serviceKey = $key;
1210 $priority = $info['priority'];
1211 $quality = $info['quality'];
1212 }
1213 }
1214 }
1215 }
1216 if ($serviceKey) {
1217 $serviceInfo = $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey];
1218 }
1219 return $serviceInfo;
1220 }
1221
1222 /**
1223 * Find a specific service identified by its key
1224 * Note that this completely bypasses the notions of priority and quality
1225 *
1226 * @param string $serviceKey Service key
1227 * @return array Service info array if a service was found
1228 * @throws \TYPO3\CMS\Core\Exception
1229 */
1230 public static function findServiceByKey($serviceKey)
1231 {
1232 if (is_array($GLOBALS['T3_SERVICES'])) {
1233 // Loop on all service types
1234 // NOTE: we don't care about the actual type, we are looking for a specific key
1235 foreach ($GLOBALS['T3_SERVICES'] as $serviceType => $servicesPerType) {
1236 if (isset($servicesPerType[$serviceKey])) {
1237 $serviceDetails = $servicesPerType[$serviceKey];
1238 // Test if service is available
1239 if (self::isServiceAvailable($serviceType, $serviceKey, $serviceDetails)) {
1240 // We have found the right service, return its information
1241 return $serviceDetails;
1242 }
1243 }
1244 }
1245 }
1246 throw new \TYPO3\CMS\Core\Exception('Service not found for key: ' . $serviceKey, 1319217244);
1247 }
1248
1249 /**
1250 * Check if a given service is available, based on the executable files it depends on
1251 *
1252 * @param string $serviceType Type of service
1253 * @param string $serviceKey Specific key of the service
1254 * @param array $serviceDetails Information about the service
1255 * @return bool Service availability
1256 */
1257 public static function isServiceAvailable($serviceType, $serviceKey, $serviceDetails)
1258 {
1259 // If the service depends on external programs - check if they exists
1260 if (trim($serviceDetails['exec'])) {
1261 $executables = GeneralUtility::trimExplode(',', $serviceDetails['exec'], true);
1262 foreach ($executables as $executable) {
1263 // If at least one executable file is not available, exit early returning FALSE
1264 if (!CommandUtility::checkCommand($executable)) {
1265 self::deactivateService($serviceType, $serviceKey);
1266 return false;
1267 }
1268 }
1269 }
1270 // The service is available
1271 return true;
1272 }
1273
1274 /**
1275 * Deactivate a service
1276 *
1277 * @param string $serviceType Service type
1278 * @param string $serviceKey Service key
1279 * @return void
1280 */
1281 public static function deactivateService($serviceType, $serviceKey)
1282 {
1283 // ... maybe it's better to move non-available services to a different array??
1284 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] = false;
1285 }
1286
1287 /**************************************
1288 *
1289 * Adding FRONTEND features
1290 *
1291 ***************************************/
1292 /**
1293 * Adds an entry to the list of plugins in content elements of type "Insert plugin"
1294 * 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)
1295 * 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.
1296 * 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
1297 * FOR USE IN ext_tables.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1298 *
1299 * @param array $itemArray Numerical array: [0] => Plugin label, [1] => Underscored extension key, [2] => Path to plugin icon relative to TYPO3_mainDir
1300 * @param string $type Type (eg. "list_type") - basically a field from "tt_content" table
1301 * @param string $extensionKey The extension key
1302 * @throws \RuntimeException
1303 * @return void
1304 */
1305 public static function addPlugin($itemArray, $type = 'list_type', $extensionKey = null)
1306 {
1307 $extensionKey = $extensionKey ?: $GLOBALS['_EXTKEY'];
1308 if (!isset($extensionKey)) {
1309 throw new \RuntimeException(
1310 'No extension key could be determined when calling addPlugin()!'
1311 . LF
1312 . 'This method is meant to be called from an ext_tables.php or Configuration/TCA/Overrides file. '
1313 . 'If you call it from Configuration/TCA/Overrides, the extension key needs to be specified as third parameter. '
1314 . 'Calling it from any other place e.g. ext_localconf.php does not work and is not supported.',
1315 1404068038
1316 );
1317 }
1318 if ($extensionKey && !$itemArray[2] && isset($GLOBALS['TYPO3_LOADED_EXT'][$extensionKey]['ext_icon'])) {
1319 $itemArray[2] = 'EXT:' . $extensionKey . '/' . $GLOBALS['TYPO3_LOADED_EXT'][$extensionKey]['ext_icon'];
1320 }
1321 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'])) {
1322 foreach ($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'] as $k => $v) {
1323 if ((string)$v[1] === (string)$itemArray[1]) {
1324 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][$k] = $itemArray;
1325 return;
1326 }
1327 }
1328 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][] = $itemArray;
1329 }
1330 }
1331
1332 /**
1333 * Adds an entry to the "ds" array of the tt_content field "pi_flexform".
1334 * This is used by plugins to add a flexform XML reference / content for use when they are selected as plugin or content element.
1335 *
1336 * @param string $piKeyToMatch Plugin key as used in the list_type field. Use the asterisk * to match all list_type values.
1337 * @param string $value Either a reference to a flex-form XML file (eg. "FILE:EXT:newloginbox/flexform_ds.xml") or the XML directly.
1338 * @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.
1339 * @return void
1340 * @see addPlugin()
1341 */
1342 public static function addPiFlexFormValue($piKeyToMatch, $value, $CTypeToMatch = 'list')
1343 {
1344 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'])) {
1345 $GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'][$piKeyToMatch . ',' . $CTypeToMatch] = $value;
1346 }
1347 }
1348
1349 /**
1350 * Adds the $table tablename to the list of tables allowed to be includes by content element type "Insert records"
1351 * By using $content_table and $content_field you can also use the function for other tables.
1352 * FOR USE IN ext_tables.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1353 *
1354 * @param string $table Table name to allow for "insert record
1355 * @param string $content_table Table name TO WHICH the $table name is applied. See $content_field as well.
1356 * @param string $content_field Field name in the database $content_table in which $table is allowed to be added as a reference ("Insert Record")
1357 * @return void
1358 */
1359 public static function addToInsertRecords($table, $content_table = 'tt_content', $content_field = 'records')
1360 {
1361 if (is_array($GLOBALS['TCA'][$content_table]['columns']) && isset($GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'])) {
1362 $GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'] .= ',' . $table;
1363 }
1364 }
1365
1366 /**
1367 * Add PlugIn to the default template rendering (previously called "Static Template #43")
1368 *
1369 * 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.
1370 *
1371 * The naming of #43 has historic reason and is rooted inside code which is now put into a TER extension called
1372 * "statictemplates". Since the static template with uid 43 is the "content.default" and practically always used
1373 * for rendering the content elements it's very useful to have this function automatically adding the necessary
1374 * TypoScript for calling your plugin. It will also work for the extension "css_styled_content".
1375 * The logic is now generalized and called "defaultContentRendering", see addTypoScript() as well.
1376 *
1377 * $type determines the type of frontend plugin:
1378 * + list_type (default) - the good old "Insert plugin" entry
1379 * + menu_type - a "Menu/Sitemap" entry
1380 * + CType - a new content element type
1381 * + header_layout - an additional header type (added to the selection of layout1-5)
1382 * + includeLib - just includes the library for manual use somewhere in TypoScript.
1383 * (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)
1384 * FOR USE IN ext_localconf.php FILES
1385 *
1386 * @param string $key The extension key
1387 * @param string $_ unused since TYPO3 CMS 8
1388 * @param string $suffix Is used as a suffix of the class name (e.g. "_pi1")
1389 * @param string $type See description above
1390 * @param int $cached If $cached is set as USER content object (cObject) is created - otherwise a USER_INT object is created.
1391 *
1392 * @return void
1393 */
1394 public static function addPItoST43($key, $_, $suffix = '', $type = 'list_type', $cached = 0)
1395 {
1396 $cN = self::getCN($key);
1397 // General plugin
1398 $pluginContent = trim('
1399 plugin.' . $cN . $suffix . ' = USER' . ($cached ? '' : '_INT') . '
1400 plugin.' . $cN . $suffix . '.userFunc = ' . $cN . $suffix . '->main
1401 ');
1402 self::addTypoScript($key, 'setup', '
1403 # Setting ' . $key . ' plugin TypoScript
1404 ' . $pluginContent);
1405 // Add after defaultContentRendering
1406 switch ($type) {
1407 case 'list_type':
1408 $addLine = 'tt_content.list.20.' . $key . $suffix . ' = < plugin.' . $cN . $suffix;
1409 break;
1410 case 'menu_type':
1411 $addLine = 'tt_content.menu.20.' . $key . $suffix . ' = < plugin.' . $cN . $suffix;
1412 break;
1413 case 'CType':
1414 $addLine = trim('
1415 tt_content.' . $key . $suffix . ' = COA
1416 tt_content.' . $key . $suffix . ' {
1417 10 = < lib.stdheader
1418 20 = < plugin.' . $cN . $suffix . '
1419 }
1420 ');
1421 break;
1422 case 'header_layout':
1423 $addLine = 'lib.stdheader.10.' . $key . $suffix . ' = < plugin.' . $cN . $suffix;
1424 break;
1425 case 'includeLib':
1426 $addLine = 'page.1000 = < plugin.' . $cN . $suffix;
1427 break;
1428 default:
1429 $addLine = '';
1430 }
1431 if ($addLine) {
1432 self::addTypoScript($key, 'setup', '
1433 # Setting ' . $key . ' plugin TypoScript
1434 ' . $addLine . '
1435 ', 'defaultContentRendering');
1436 }
1437 }
1438
1439 /**
1440 * Call this method to add an entry in the static template list found in sys_templates
1441 * FOR USE IN ext_tables.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1442 *
1443 * @param string $extKey Is of course the extension key
1444 * @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/
1445 * @param string $title Is the title in the selector box.
1446 * @return void
1447 * @see addTypoScript()
1448 */
1449 public static function addStaticFile($extKey, $path, $title)
1450 {
1451 if ($extKey && $path && is_array($GLOBALS['TCA']['sys_template']['columns'])) {
1452 $value = str_replace(',', '', 'EXT:' . $extKey . '/' . $path);
1453 $itemArray = array(trim($title . ' (' . $extKey . ')'), $value);
1454 $GLOBALS['TCA']['sys_template']['columns']['include_static_file']['config']['items'][] = $itemArray;
1455 }
1456 }
1457
1458 /**
1459 * Call this method to add an entry in the pageTSconfig list found in pages
1460 * FOR USE in files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1461 *
1462 * @param string $extKey The extension key
1463 * @param string $filePath The path where the TSconfig file is located
1464 * @param string $title The title in the selector box
1465 * @return void
1466 */
1467 public static function registerPageTSConfigFile($extKey, $filePath, $title)
1468 {
1469 if (!$extKey) {
1470 throw new \InvalidArgumentException('No extension key given.', 1447789490);
1471 }
1472 if (!$filePath) {
1473 throw new \InvalidArgumentException('No file path given.', 1447789491);
1474 }
1475 if (!isset($GLOBALS['TCA']['pages']['columns']) || !is_array($GLOBALS['TCA']['pages']['columns'])) {
1476 throw new \InvalidArgumentException('No TCA definition for table "pages".', 1447789492);
1477 }
1478
1479 $value = str_replace(',', '', 'EXT:' . $extKey . '/' . $filePath);
1480 $itemArray = array(trim($title . ' (' . $extKey . ')'), $value);
1481 $GLOBALS['TCA']['pages']['columns']['tsconfig_includes']['config']['items'][] = $itemArray;
1482 }
1483
1484 /**
1485 * Adds $content to the default TypoScript setup code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_setup']
1486 * Prefixed with a [GLOBAL] line
1487 * FOR USE IN ext_localconf.php FILES
1488 *
1489 * @param string $content TypoScript Setup string
1490 * @return void
1491 */
1492 public static function addTypoScriptSetup($content)
1493 {
1494 self::appendToTypoConfVars('FE', 'defaultTypoScript_setup', '
1495 [GLOBAL]
1496 ' . $content);
1497 }
1498
1499 /**
1500 * Adds $content to the default TypoScript constants code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_constants']
1501 * Prefixed with a [GLOBAL] line
1502 * FOR USE IN ext_localconf.php FILES
1503 *
1504 * @param string $content TypoScript Constants string
1505 * @return void
1506 */
1507 public static function addTypoScriptConstants($content)
1508 {
1509 self::appendToTypoConfVars('FE', 'defaultTypoScript_constants', '
1510 [GLOBAL]
1511 ' . $content);
1512 }
1513
1514 /**
1515 * Adds $content to the default TypoScript code for either setup or constants as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_*']
1516 * (Basically this function can do the same as addTypoScriptSetup and addTypoScriptConstants - just with a little more hazzle, but also with some more options!)
1517 * FOR USE IN ext_localconf.php FILES
1518 * Note: As of TYPO3 CMS 6.2, static template #43 (content: default) was replaced with "defaultContentRendering" which makes it
1519 * possible that a first extension like css_styled_content registers a "contentRendering" template (= a template that defines default content rendering TypoScript)
1520 * by adding itself to $TYPO3_CONF_VARS[FE][contentRenderingTemplates][] = 'myext/Configuration/TypoScript'.
1521 * An extension calling addTypoScript('myext', 'setup', $typoScript, 'defaultContentRendering') will add its TypoScript directly after;
1522 * For now, "43" and "defaultContentRendering" can be used, but "defaultContentRendering" is more descriptive and
1523 * should be used in the future.
1524 *
1525 * @param string $key Is the extension key (informative only).
1526 * @param string $type Is either "setup" or "constants" and obviously determines which kind of TypoScript code we are adding.
1527 * @param string $content Is the TS content, will be prefixed with a [GLOBAL] line and a comment-header.
1528 * @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.
1529 *
1530 * @return void
1531 */
1532 public static function addTypoScript($key, $type, $content, $afterStaticUid = 0)
1533 {
1534 if ($type === 'setup' || $type === 'constants') {
1535 $content = '
1536
1537 [GLOBAL]
1538 #############################################
1539 ## TypoScript added by extension "' . $key . '"
1540 #############################################
1541
1542 ' . $content;
1543 if ($afterStaticUid) {
1544 // If 'content (default)' is targeted (static uid 43),
1545 // 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
1546 if ($afterStaticUid === 'defaultContentRendering' || $afterStaticUid == 43) {
1547 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.']['defaultContentRendering'] .= $content;
1548 } else {
1549 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.'][$afterStaticUid] .= $content;
1550 }
1551 } else {
1552 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type] .= $content;
1553 }
1554 }
1555 }
1556
1557 /***************************************
1558 *
1559 * Internal extension management methods
1560 *
1561 ***************************************/
1562 /**
1563 * Find extension icon
1564 *
1565 * @param string $extensionPath Path to extension directory.
1566 * @param bool $returnFullPath Return full path of file.
1567 *
1568 * @return string
1569 */
1570 public static function getExtensionIcon($extensionPath, $returnFullPath = false)
1571 {
1572 $icon = '';
1573 $iconFileTypesToCheckFor = array('png', 'svg', 'gif');
1574 foreach ($iconFileTypesToCheckFor as $fileType) {
1575 if (file_exists($extensionPath . 'ext_icon.' . $fileType)) {
1576 $icon = 'ext_icon.' . $fileType;
1577 break;
1578 }
1579 }
1580 return $returnFullPath ? $extensionPath . $icon : $icon;
1581 }
1582
1583 /**
1584 * Execute all ext_localconf.php files of loaded extensions.
1585 * The method implements an optionally used caching mechanism that concatenates all
1586 * ext_localconf.php files in one file.
1587 *
1588 * This is an internal method. It is only used during bootstrap and
1589 * extensions should not use it!
1590 *
1591 * @param bool $allowCaching Whether or not to load / create concatenated cache file
1592 * @return void
1593 * @access private
1594 */
1595 public static function loadExtLocalconf($allowCaching = true)
1596 {
1597 if ($allowCaching) {
1598 $cacheIdentifier = self::getExtLocalconfCacheIdentifier();
1599 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1600 $codeCache = self::getCacheManager()->getCache('cache_core');
1601 if ($codeCache->has($cacheIdentifier)) {
1602 $codeCache->requireOnce($cacheIdentifier);
1603 } else {
1604 self::loadSingleExtLocalconfFiles();
1605 self::createExtLocalconfCacheEntry();
1606 }
1607 } else {
1608 self::loadSingleExtLocalconfFiles();
1609 }
1610 }
1611
1612 /**
1613 * Execute ext_localconf.php files from extensions
1614 *
1615 * @return void
1616 */
1617 protected static function loadSingleExtLocalconfFiles()
1618 {
1619 // This is the main array meant to be manipulated in the ext_localconf.php files
1620 // In general it is recommended to not rely on it to be globally defined in that
1621 // scope but to use $GLOBALS['TYPO3_CONF_VARS'] instead.
1622 // Nevertheless we define it here as global for backwards compatibility.
1623 global $TYPO3_CONF_VARS;
1624 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1625 if ((is_array($extensionInformation) || $extensionInformation instanceof \ArrayAccess) && isset($extensionInformation['ext_localconf.php'])) {
1626 // $_EXTKEY and $_EXTCONF are available in ext_localconf.php
1627 // and are explicitly set in cached file as well
1628 $_EXTCONF = isset($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY]) ? $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY] : null;
1629 require $extensionInformation['ext_localconf.php'];
1630 }
1631 }
1632 }
1633
1634 /**
1635 * Create cache entry for concatenated ext_localconf.php files
1636 *
1637 * @return void
1638 */
1639 protected static function createExtLocalconfCacheEntry()
1640 {
1641 $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1642 $phpCodeToCache = array();
1643 // Set same globals as in loadSingleExtLocalconfFiles()
1644 $phpCodeToCache[] = '/**';
1645 $phpCodeToCache[] = ' * Compiled ext_localconf.php cache file';
1646 $phpCodeToCache[] = ' */';
1647 $phpCodeToCache[] = '';
1648 $phpCodeToCache[] = 'global $TYPO3_CONF_VARS, $T3_SERVICES, $T3_VAR;';
1649 $phpCodeToCache[] = '';
1650 // Iterate through loaded extensions and add ext_localconf content
1651 foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1652 if (isset($extensionDetails['ext_localconf.php']) && $extensionDetails['ext_localconf.php']) {
1653 // Include a header per extension to make the cache file more readable
1654 $phpCodeToCache[] = '/**';
1655 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1656 $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_localconf.php'];
1657 $phpCodeToCache[] = ' */';
1658 $phpCodeToCache[] = '';
1659 // Set $_EXTKEY and $_EXTCONF for this extension
1660 $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1661 $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY];';
1662 $phpCodeToCache[] = '';
1663 // Add ext_localconf.php content of extension
1664 $phpCodeToCache[] = trim(file_get_contents($extensionDetails['ext_localconf.php']));
1665 $phpCodeToCache[] = '';
1666 $phpCodeToCache[] = '';
1667 }
1668 }
1669 $phpCodeToCache = implode(LF, $phpCodeToCache);
1670 // Remove all start and ending php tags from content
1671 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1672 self::getCacheManager()->getCache('cache_core')->set(self::getExtLocalconfCacheIdentifier(), $phpCodeToCache);
1673 }
1674
1675 /**
1676 * Cache identifier of concatenated ext_localconf file
1677 *
1678 * @return string
1679 */
1680 protected static function getExtLocalconfCacheIdentifier()
1681 {
1682 return 'ext_localconf_' . sha1(TYPO3_version . PATH_site . 'extLocalconf' . serialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']));
1683 }
1684
1685 /**
1686 * Wrapper for buildBaseTcaFromSingleFiles handling caching.
1687 *
1688 * This builds 'base' TCA that is later overloaded by ext_tables.php.
1689 *
1690 * Use a cache file if exists and caching is allowed.
1691 *
1692 * This is an internal method. It is only used during bootstrap and
1693 * extensions should not use it!
1694 *
1695 * @param bool $allowCaching Whether or not to load / create concatenated cache file
1696 * @return void
1697 * @access private
1698 */
1699 public static function loadBaseTca($allowCaching = true)
1700 {
1701 if ($allowCaching) {
1702 $cacheIdentifier = static::getBaseTcaCacheIdentifier();
1703 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1704 $codeCache = static::getCacheManager()->getCache('cache_core');
1705 if ($codeCache->has($cacheIdentifier)) {
1706 // substr is necessary, because the php frontend wraps php code around the cache value
1707 $cacheData = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
1708 $GLOBALS['TCA'] = $cacheData['tca'];
1709 GeneralUtility::setSingletonInstance(CategoryRegistry::class, $cacheData['categoryRegistry']);
1710 } else {
1711 static::buildBaseTcaFromSingleFiles();
1712 static::createBaseTcaCacheFile();
1713 }
1714 } else {
1715 static::buildBaseTcaFromSingleFiles();
1716 }
1717 }
1718
1719 /**
1720 * Find all Configuration/TCA/* files of extensions and create base TCA from it.
1721 * The filename must be the table name in $GLOBALS['TCA'], and the content of
1722 * the file should return an array with content of a specific table.
1723 *
1724 * @return void
1725 * @see Extension core, extensionmanager and others for examples.
1726 */
1727 protected static function buildBaseTcaFromSingleFiles()
1728 {
1729 $GLOBALS['TCA'] = array();
1730
1731 $activePackages = static::$packageManager->getActivePackages();
1732
1733 // First load "full table" files from Configuration/TCA
1734 foreach ($activePackages as $package) {
1735 $tcaConfigurationDirectory = $package->getPackagePath() . 'Configuration/TCA';
1736 if (is_dir($tcaConfigurationDirectory)) {
1737 $files = scandir($tcaConfigurationDirectory);
1738 foreach ($files as $file) {
1739 if (
1740 is_file($tcaConfigurationDirectory . '/' . $file)
1741 && ($file !== '.')
1742 && ($file !== '..')
1743 && (substr($file, -4, 4) === '.php')
1744 ) {
1745 $tcaOfTable = require($tcaConfigurationDirectory . '/' . $file);
1746 if (is_array($tcaOfTable)) {
1747 // TCA table name is filename without .php suffix, eg 'sys_notes', not 'sys_notes.php'
1748 $tcaTableName = substr($file, 0, -4);
1749 $GLOBALS['TCA'][$tcaTableName] = $tcaOfTable;
1750 }
1751 }
1752 }
1753 }
1754 }
1755
1756 // Apply category stuff
1757 CategoryRegistry::getInstance()->applyTcaForPreRegisteredTables();
1758
1759 // Execute override files from Configuration/TCA/Overrides
1760 foreach ($activePackages as $package) {
1761 $tcaOverridesPathForPackage = $package->getPackagePath() . 'Configuration/TCA/Overrides';
1762 if (is_dir($tcaOverridesPathForPackage)) {
1763 $files = scandir($tcaOverridesPathForPackage);
1764 foreach ($files as $file) {
1765 if (
1766 is_file($tcaOverridesPathForPackage . '/' . $file)
1767 && ($file !== '.')
1768 && ($file !== '..')
1769 && (substr($file, -4, 4) === '.php')
1770 ) {
1771 require($tcaOverridesPathForPackage . '/' . $file);
1772 }
1773 }
1774 }
1775 }
1776
1777 // TCA migration
1778 // @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.
1779 $tcaMigration = GeneralUtility::makeInstance(TcaMigration::class);
1780 $GLOBALS['TCA'] = $tcaMigration->migrate($GLOBALS['TCA']);
1781 $messages = $tcaMigration->getMessages();
1782 if (!empty($messages)) {
1783 $context = 'Automatic TCA migration done during bootstrap. Please adapt TCA accordingly, these migrations'
1784 . ' will be removed. The backend module "Configuration -> TCA" shows the modified values.'
1785 . ' Please adapt these areas:';
1786 array_unshift($messages, $context);
1787 GeneralUtility::deprecationLog(implode(LF, $messages));
1788 }
1789
1790 static::emitTcaIsBeingBuiltSignal($GLOBALS['TCA']);
1791 }
1792
1793 /**
1794 * Emits the signal and uses the result of slots for the final TCA
1795 * This means, that *all* slots *must* return the complete TCA to
1796 * be effective. If a slot calls methods that manipulate the global array,
1797 * it needs to return the global array in the end. To be future proof,
1798 * a slot should manipulate the signal argument only and return it
1799 * after manipulation.
1800 *
1801 * @param array $tca
1802 */
1803 protected static function emitTcaIsBeingBuiltSignal(array $tca)
1804 {
1805 list($tca) = static::getSignalSlotDispatcher()->dispatch(__CLASS__, 'tcaIsBeingBuilt', array($tca));
1806 $GLOBALS['TCA'] = $tca;
1807 }
1808
1809 /**
1810 * Cache base $GLOBALS['TCA'] to cache file to require the whole thing in one
1811 * file for next access instead of cycling through all extensions again.
1812 *
1813 * @return void
1814 */
1815 protected static function createBaseTcaCacheFile()
1816 {
1817 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1818 $codeCache = self::getCacheManager()->getCache('cache_core');
1819 $codeCache->set(static::getBaseTcaCacheIdentifier(), serialize(array('tca' => $GLOBALS['TCA'], 'categoryRegistry' => CategoryRegistry::getInstance())));
1820 }
1821
1822 /**
1823 * Cache identifier of base TCA cache entry.
1824 *
1825 * @return string
1826 */
1827 protected static function getBaseTcaCacheIdentifier()
1828 {
1829 return 'tca_base_' . sha1(TYPO3_version . PATH_site . 'tca_with_category_registry' . serialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']));
1830 }
1831
1832 /**
1833 * Execute all ext_tables.php files of loaded extensions.
1834 * The method implements an optionally used caching mechanism that concatenates all
1835 * ext_tables.php files in one file.
1836 *
1837 * This is an internal method. It is only used during bootstrap and
1838 * extensions should not use it!
1839 *
1840 * @param bool $allowCaching Whether to load / create concatenated cache file
1841 * @return void
1842 * @access private
1843 */
1844 public static function loadExtTables($allowCaching = true)
1845 {
1846 if ($allowCaching && !self::$extTablesWasReadFromCacheOnce) {
1847 self::$extTablesWasReadFromCacheOnce = true;
1848 $cacheIdentifier = self::getExtTablesCacheIdentifier();
1849 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1850 $codeCache = self::getCacheManager()->getCache('cache_core');
1851 if ($codeCache->has($cacheIdentifier)) {
1852 $codeCache->requireOnce($cacheIdentifier);
1853 } else {
1854 self::loadSingleExtTablesFiles();
1855 self::createExtTablesCacheEntry();
1856 }
1857 } else {
1858 self::loadSingleExtTablesFiles();
1859 }
1860 }
1861
1862 /**
1863 * Load ext_tables.php as single files
1864 *
1865 * @return void
1866 */
1867 protected static function loadSingleExtTablesFiles()
1868 {
1869 // In general it is recommended to not rely on it to be globally defined in that
1870 // scope, but we can not prohibit this without breaking backwards compatibility
1871 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
1872 global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;
1873 global $PAGES_TYPES, $TBE_STYLES;
1874 global $_EXTKEY;
1875 // Load each ext_tables.php file of loaded extensions
1876 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1877 if ((is_array($extensionInformation) || $extensionInformation instanceof \ArrayAccess) && $extensionInformation['ext_tables.php']) {
1878 // $_EXTKEY and $_EXTCONF are available in ext_tables.php
1879 // and are explicitly set in cached file as well
1880 $_EXTCONF = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY];
1881 require $extensionInformation['ext_tables.php'];
1882 }
1883 }
1884 }
1885
1886 /**
1887 * Create concatenated ext_tables.php cache file
1888 *
1889 * @return void
1890 */
1891 protected static function createExtTablesCacheEntry()
1892 {
1893 $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1894 $phpCodeToCache = array();
1895 // Set same globals as in loadSingleExtTablesFiles()
1896 $phpCodeToCache[] = '/**';
1897 $phpCodeToCache[] = ' * Compiled ext_tables.php cache file';
1898 $phpCodeToCache[] = ' */';
1899 $phpCodeToCache[] = '';
1900 $phpCodeToCache[] = 'global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;';
1901 $phpCodeToCache[] = 'global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;';
1902 $phpCodeToCache[] = 'global $PAGES_TYPES, $TBE_STYLES;';
1903 $phpCodeToCache[] = 'global $_EXTKEY;';
1904 $phpCodeToCache[] = '';
1905 // Iterate through loaded extensions and add ext_tables content
1906 foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1907 if (isset($extensionDetails['ext_tables.php']) && $extensionDetails['ext_tables.php']) {
1908 // Include a header per extension to make the cache file more readable
1909 $phpCodeToCache[] = '/**';
1910 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1911 $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_tables.php'];
1912 $phpCodeToCache[] = ' */';
1913 $phpCodeToCache[] = '';
1914 // Set $_EXTKEY and $_EXTCONF for this extension
1915 $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1916 $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY];';
1917 $phpCodeToCache[] = '';
1918 // Add ext_tables.php content of extension
1919 $phpCodeToCache[] = trim(file_get_contents($extensionDetails['ext_tables.php']));
1920 $phpCodeToCache[] = '';
1921 }
1922 }
1923 $phpCodeToCache = implode(LF, $phpCodeToCache);
1924 // Remove all start and ending php tags from content
1925 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1926 self::getCacheManager()->getCache('cache_core')->set(self::getExtTablesCacheIdentifier(), $phpCodeToCache);
1927 }
1928
1929 /**
1930 * Cache identifier for concatenated ext_tables.php files
1931 *
1932 * @return string
1933 */
1934 protected static function getExtTablesCacheIdentifier()
1935 {
1936 return 'ext_tables_' . sha1(TYPO3_version . PATH_site . 'extTables' . serialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']));
1937 }
1938
1939 /**
1940 * Remove cache files from php code cache, grouped by 'system'
1941 *
1942 * This removes the following cache entries:
1943 * - autoloader cache registry
1944 * - cache loaded extension array
1945 * - ext_localconf concatenation
1946 * - ext_tables concatenation
1947 *
1948 * This method is usually only used by extension that fiddle
1949 * with the loaded extensions. An example is the extension
1950 * manager and the install tool.
1951 *
1952 * @return void
1953 */
1954 public static function removeCacheFiles()
1955 {
1956 self::getCacheManager()->flushCachesInGroup('system');
1957 }
1958
1959 /**
1960 * Gets an array of loaded extension keys
1961 *
1962 * @return array Loaded extensions
1963 */
1964 public static function getLoadedExtensionListArray()
1965 {
1966 return array_keys(static::$packageManager->getActivePackages());
1967 }
1968
1969 /**
1970 * Loads given extension
1971 *
1972 * Warning: This method only works if the ugrade wizard to transform
1973 * localconf.php to LocalConfiguration.php was already run
1974 *
1975 * @param string $extensionKey Extension key to load
1976 * @return void
1977 * @throws \RuntimeException
1978 */
1979 public static function loadExtension($extensionKey)
1980 {
1981 if (static::$packageManager->isPackageActive($extensionKey)) {
1982 throw new \RuntimeException('Extension already loaded', 1342345486);
1983 }
1984 static::$packageManager->activatePackage($extensionKey);
1985 }
1986
1987 /**
1988 * Unloads given extension
1989 *
1990 * Warning: This method only works if the ugrade wizard to transform
1991 * localconf.php to LocalConfiguration.php was already run
1992 *
1993 * @param string $extensionKey Extension key to remove
1994 * @return void
1995 * @throws \RuntimeException
1996 */
1997 public static function unloadExtension($extensionKey)
1998 {
1999 if (!static::$packageManager->isPackageActive($extensionKey)) {
2000 throw new \RuntimeException('Extension not loaded', 1342345487);
2001 }
2002 static::$packageManager->deactivatePackage($extensionKey);
2003 }
2004
2005 /**
2006 * Makes a table categorizable by adding value into the category registry.
2007 * FOR USE IN ext_localconf.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
2008 *
2009 * @param string $extensionKey Extension key to be used
2010 * @param string $tableName Name of the table to be categorized
2011 * @param string $fieldName Name of the field to be used to store categories
2012 * @param array $options Additional configuration options
2013 * @param bool $override If TRUE, any category configuration for the same table / field is removed before the new configuration is added
2014 * @see addTCAcolumns
2015 * @see addToAllTCAtypes
2016 */
2017 public static function makeCategorizable($extensionKey, $tableName, $fieldName = 'categories', array $options = array(), $override = false)
2018 {
2019 // Update the category registry
2020 $result = CategoryRegistry::getInstance()->add($extensionKey, $tableName, $fieldName, $options, $override);
2021 if ($result === false) {
2022 $message = CategoryRegistry::class . ': no category registered for table "%s". Key was already registered.';
2023 /** @var $logger \TYPO3\CMS\Core\Log\Logger */
2024 $logger = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Log\LogManager::class)->getLogger(__CLASS__);
2025 $logger->warning(
2026 sprintf($message, $tableName)
2027 );
2028 }
2029 }
2030 }