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