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