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