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