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