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