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