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