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