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