[TASK] Use "int" or "bool" in @var notation
[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 (boolean) 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 search needles that are used for inserting fields/items into an existing list.
665 *
666 * @see executePositionedStringInsertion
667 * @param string $item The name of the field/item
668 * @param array $itemDetails Additional details of the field/item like e.g. palette information
669 * @return array The needled to be used for inserting content before or after existing fields/items
670 * @deprecated since 6.2, will be removed two versions later. This method was only used by executePositionedStringInsertion().
671 */
672 static protected function getInsertionNeedles($item, array $itemDetails) {
673 if (strpos($item, '--') !== FALSE) {
674 // 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.
675 $item = str_replace(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), '', $item);
676 }
677 $needles = array(
678 'before' => array($item, 'before:' . $item),
679 'after' => array('after:' . $item),
680 'replace' => array('replace:' . $item)
681 );
682 if ($itemDetails['palette']) {
683 $palette = $item . ';;' . $itemDetails['palette'];
684 $needles['before'][] = $palette;
685 $needles['before'][] = 'before:' . $palette;
686 $needles['after'][] = 'after:' . $palette;
687 $needles['replace'][] = 'replace:' . $palette;
688 }
689 return $needles;
690 }
691
692 /**
693 * Generates an array of fields/items with additional information such as e.g. the name of the palette.
694 *
695 * @param string $itemList List of fields/items to be splitted up
696 * @return array An array with the names of the fields/items as keys and additional information
697 */
698 static protected function explodeItemList($itemList) {
699 $items = array();
700 $itemParts = GeneralUtility::trimExplode(',', $itemList, TRUE);
701 foreach ($itemParts as $itemPart) {
702 $itemDetails = GeneralUtility::trimExplode(';', $itemPart, FALSE, 5);
703 $key = $itemDetails[0];
704 if (strpos($key, '--') !== FALSE) {
705 // 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!
706 $key .= count($items);
707 }
708 if (!isset($items[$key])) {
709 $items[$key] = array(
710 'rawData' => $itemPart,
711 'details' => array(
712 'field' => $itemDetails[0],
713 'label' => $itemDetails[1],
714 'palette' => $itemDetails[2],
715 'special' => $itemDetails[3],
716 'styles' => $itemDetails[4]
717 )
718 );
719 }
720 }
721 return $items;
722 }
723
724 /**
725 * Generates a list of fields/items out of an array provided by the function getFieldsOfFieldList().
726 *
727 * @see explodeItemList
728 * @param array $items The array of fields/items with optional additional information
729 * @param bool $useRawData Use raw data instead of building by using the details (default: FALSE)
730 * @return string The list of fields/items which gets used for $GLOBALS['TCA'][<table>]['types'][<type>]['showitem']
731 */
732 static protected function generateItemList(array $items, $useRawData = FALSE) {
733 $itemParts = array();
734 foreach ($items as $item => $itemDetails) {
735 if (strpos($item, '--') !== FALSE) {
736 // 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.
737 $item = str_replace(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), '', $item);
738 }
739 if ($useRawData) {
740 $itemParts[] = $itemDetails['rawData'];
741 } else {
742 $itemParts[] = count($itemDetails['details']) > 1 ? implode(';', $itemDetails['details']) : $item;
743 }
744 }
745 return implode(', ', $itemParts);
746 }
747
748 /**
749 * Add tablename to default list of allowed tables on pages (in $PAGES_TYPES)
750 * Will add the $table to the list of tables allowed by default on pages as setup by $PAGES_TYPES['default']['allowedTables']
751 * FOR USE IN ext_tables.php FILES
752 *
753 * @param string $table Table name
754 * @return void
755 */
756 static public function allowTableOnStandardPages($table) {
757 $GLOBALS['PAGES_TYPES']['default']['allowedTables'] .= ',' . $table;
758 }
759
760 /**
761 * Adds a ExtJS module (main or sub) to the backend interface
762 * FOR USE IN ext_tables.php FILES
763 *
764 * @static
765 * @param string $extensionName
766 * @param string $mainModuleName Is the main module key
767 * @param string $subModuleName Is the submodule key, if blank a plain main module is generated
768 * @param string $position Passed to \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModule, see reference there
769 * @param array $moduleConfiguration Icon with array keys: access, icon, labels to configure the module
770 * @throws \InvalidArgumentException
771 */
772 static public function addExtJSModule($extensionName, $mainModuleName, $subModuleName = '', $position = '', array $moduleConfiguration = array()) {
773 if (empty($extensionName)) {
774 throw new \InvalidArgumentException('The extension name must not be empty', 1325938973);
775 }
776 $extensionKey = GeneralUtility::camelCaseToLowerCaseUnderscored($extensionName);
777 $extensionName = str_replace(' ', '', ucwords(str_replace('_', ' ', $extensionName)));
778 $defaultModuleConfiguration = array(
779 'access' => 'admin',
780 'icon' => 'gfx/typo3.png',
781 'labels' => '',
782 'extRelPath' => self::extRelPath($extensionKey) . 'Classes/'
783 );
784 // Add mandatory parameter to use new pagetree
785 if ($mainModuleName === 'web') {
786 $defaultModuleConfiguration['navigationComponentId'] = 'typo3-pagetree';
787 }
788 ArrayUtility::mergeRecursiveWithOverrule($defaultModuleConfiguration, $moduleConfiguration);
789 $moduleConfiguration = $defaultModuleConfiguration;
790 if (strlen($subModuleName) > 0) {
791 $moduleSignature = $mainModuleName . '_' . $subModuleName;
792 } else {
793 $moduleSignature = $mainModuleName;
794 }
795 $moduleConfiguration['name'] = $moduleSignature;
796 $moduleConfiguration['script'] = 'extjspaneldummy.html';
797 $moduleConfiguration['extensionName'] = $extensionName;
798 $moduleConfiguration['configureModuleFunction'] = array('TYPO3\\CMS\\Core\\Utility\\ExtensionManagementUtility', 'configureModule');
799 $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature] = $moduleConfiguration;
800 self::addModule($mainModuleName, $subModuleName, $position);
801 }
802
803 /**
804 * This method is called from \TYPO3\CMS\Backend\Module\ModuleLoader::checkMod
805 * and it replaces old conf.php.
806 *
807 * The original function for is called
808 * Tx_Extbase_Utility_Extension::configureModule, the refered function can
809 * be deprecated now
810 *
811 * @param string $moduleSignature The module name
812 * @param string $modulePath Absolute path to module (not used by Extbase currently)
813 * @return array Configuration of the module
814 */
815 static public function configureModule($moduleSignature, $modulePath) {
816 $moduleConfiguration = $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature];
817 $iconPathAndFilename = $moduleConfiguration['icon'];
818 if (substr($iconPathAndFilename, 0, 4) === 'EXT:') {
819 list($extensionKey, $relativePath) = explode('/', substr($iconPathAndFilename, 4), 2);
820 $iconPathAndFilename = self::extPath($extensionKey) . $relativePath;
821 }
822 // TODO: skin support
823 $moduleLabels = array(
824 'tabs_images' => array(
825 'tab' => $iconPathAndFilename
826 ),
827 'labels' => array(
828 'tablabel' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_labels_tablabel'),
829 'tabdescr' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_labels_tabdescr')
830 ),
831 'tabs' => array(
832 'tab' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_tabs_tab')
833 )
834 );
835 $GLOBALS['LANG']->addModuleLabels($moduleLabels, $moduleSignature . '_');
836 return $moduleConfiguration;
837 }
838
839 /**
840 * Adds a module (main or sub) to the backend interface
841 * FOR USE IN ext_tables.php FILES
842 *
843 * @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.
844 * @param string $sub The submodule key. If $sub is not set a blank $main module is created.
845 * @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.
846 * @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.
847 * @param array $moduleConfiguration additional configuration, previously put in "conf.php" of the module directory
848 * @return void
849 */
850 static public function addModule($main, $sub = '', $position = '', $path = '', $moduleConfiguration = array()) {
851 // If there is already a main module by this name:
852 // Adding the submodule to the correct position:
853 if (isset($GLOBALS['TBE_MODULES'][$main]) && $sub) {
854 list($place, $modRef) = GeneralUtility::trimExplode(':', $position, TRUE);
855 $modules = ',' . $GLOBALS['TBE_MODULES'][$main] . ',';
856 if ($place === NULL || ($modRef !== NULL && !GeneralUtility::inList($modules, $modRef))) {
857 $place = 'bottom';
858 }
859 $modRef = ',' . $modRef . ',';
860 if (!GeneralUtility::inList($modules, $sub)) {
861 switch (strtolower($place)) {
862 case 'after':
863 $modules = str_replace($modRef, $modRef . $sub . ',', $modules);
864 break;
865 case 'before':
866 $modules = str_replace($modRef, ',' . $sub . $modRef, $modules);
867 break;
868 case 'top':
869 $modules = $sub . $modules;
870 break;
871 case 'bottom':
872 default:
873 $modules = $modules . $sub;
874 }
875 }
876 // Re-inserting the submodule list:
877 $GLOBALS['TBE_MODULES'][$main] = trim($modules, ',');
878 } else {
879 // Create new main modules with only one submodule, $sub (or none if $sub is blank)
880 $GLOBALS['TBE_MODULES'][$main] = $sub;
881 }
882 $fullModuleSignature = $main . ($sub ? '_' . $sub : '');
883 // Adding path:
884 if ($path) {
885 $GLOBALS['TBE_MODULES']['_PATHS'][$fullModuleSignature] = $path;
886 }
887
888 // add additional configuration
889 if (is_array($moduleConfiguration) && count($moduleConfiguration) > 0) {
890 $GLOBALS['TBE_MODULES']['_configuration'][$fullModuleSignature] = $moduleConfiguration;
891 }
892 }
893
894 /**
895 * Registers an Ext.Direct component with access restrictions.
896 *
897 * @param string $endpointName
898 * @param string $callbackClass
899 * @param string $moduleName Optional: must be <mainmodule> or <mainmodule>_<submodule>
900 * @param string $accessLevel Optional: can be 'admin' or 'user,group'
901 * @return void
902 */
903 static public function registerExtDirectComponent($endpointName, $callbackClass, $moduleName = NULL, $accessLevel = NULL) {
904 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ExtDirect'][$endpointName] = array(
905 'callbackClass' => $callbackClass,
906 'moduleName' => $moduleName,
907 'accessLevel' => $accessLevel
908 );
909 }
910
911 /**
912 * Registers an Ajax Handler
913 *
914 * @param string $ajaxId Identifier of the handler, that is used in the request
915 * @param string $callbackMethod TYPO3 callback method (className->methodName).
916 * @param bool $csrfTokenCheck Only set this to FALSE if you are sure that the registered handler does not modify any data!
917 */
918 static public function registerAjaxHandler($ajaxId, $callbackMethod, $csrfTokenCheck = TRUE) {
919 $GLOBALS['TYPO3_CONF_VARS']['BE']['AJAX'][$ajaxId] = array(
920 'callbackMethod' => $callbackMethod,
921 'csrfTokenCheck' => $csrfTokenCheck
922 );
923 }
924
925 /**
926 * Adds a module path to $GLOBALS['TBE_MODULES'] for used with the module dispatcher, mod.php
927 * Used only for modules that are not placed in the main/sub menu hierarchy by the traditional mechanism of addModule()
928 * Examples for this is context menu functionality (like import/export) which runs as an independent module through mod.php
929 * FOR USE IN ext_tables.php FILES
930 * Example: \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModulePath('xMOD_tximpexp', \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY).'app/');
931 *
932 * @param string $name The name of the module, refer to conf.php of the module.
933 * @param string $path The absolute path to the module directory inside of which "index.php" and "conf.php" is found.
934 * @return void
935 */
936 static public function addModulePath($name, $path) {
937 $GLOBALS['TBE_MODULES']['_PATHS'][$name] = $path;
938 }
939
940 /**
941 * Adds a "Function menu module" ('third level module') to an existing function menu for some other backend module
942 * The arguments values are generally determined by which function menu this is supposed to interact with
943 * See Inside TYPO3 for information on how to use this function.
944 * FOR USE IN ext_tables.php FILES
945 *
946 * @param string $modname Module name
947 * @param string $className Class name
948 * @param string $classPath Class path, deprecated since 6.2, use auto-loading instead
949 * @param string $title Title of module
950 * @param string $MM_key Menu array key - default is "function
951 * @param string $WS Workspace conditions. Blank means all workspaces, any other string can be a comma list of "online", "offline" and "custom
952 * @return void
953 * @see \TYPO3\CMS\Backend\Module\BaseScriptClass::mergeExternalItems()
954 */
955 static public function insertModuleFunction($modname, $className, $classPath, $title, $MM_key = 'function', $WS = '') {
956 if (!empty($classPath)) {
957 GeneralUtility::deprecationLog(
958 sprintf('insertModuleFunction(%s, %s, ...): Use auto-loading for the class and pass NULL as $classPath since 6.2.',
959 $modname,
960 $className
961 )
962 );
963 }
964 $GLOBALS['TBE_MODULES_EXT'][$modname]['MOD_MENU'][$MM_key][$className] = array(
965 'name' => $className,
966 'path' => $classPath,
967 'title' => $title,
968 'ws' => $WS
969 );
970 }
971
972 /**
973 * Adds some more content to a key of TYPO3_CONF_VARS array.
974 *
975 * This also tracks which content was added by extensions (in TYPO3_CONF_VARS_extensionAdded)
976 * so that they cannot be editted again through the Install Tool.
977 *
978 * @static
979 * @param string $group The group ('FE', 'BE', 'SYS' ...)
980 * @param string $key The key of this setting within the group
981 * @param string $content The text to add (include leading "\n" in case of multi-line entries)
982 * @return void
983 */
984 static public function appendToTypoConfVars($group, $key, $content) {
985 $GLOBALS['TYPO3_CONF_VARS_extensionAdded'][$group][$key] .= $content;
986 $GLOBALS['TYPO3_CONF_VARS'][$group][$key] .= $content;
987 }
988
989 /**
990 * Adds $content to the default Page TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultPageTSconfig']
991 * Prefixed with a [GLOBAL] line
992 * FOR USE IN ext_tables.php/ext_localconf.php FILES
993 *
994 * @param string $content Page TSconfig content
995 * @return void
996 */
997 static public function addPageTSConfig($content) {
998 self::appendToTypoConfVars('BE', 'defaultPageTSconfig', '
999 [GLOBAL]
1000 ' . $content);
1001 }
1002
1003 /**
1004 * Adds $content to the default User TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultUserTSconfig']
1005 * Prefixed with a [GLOBAL] line
1006 * FOR USE IN ext_tables.php/ext_localconf.php FILES
1007 *
1008 * @param string $content User TSconfig content
1009 * @return void
1010 */
1011 static public function addUserTSConfig($content) {
1012 self::appendToTypoConfVars('BE', 'defaultUserTSconfig', '
1013 [GLOBAL]
1014 ' . $content);
1015 }
1016
1017 /**
1018 * Adds a reference to a locallang file with $GLOBALS['TCA_DESCR'] labels
1019 * FOR USE IN ext_tables.php FILES
1020 * 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.
1021 *
1022 * @param string $tca_descr_key Description key. Typically a database table (like "pages") but for applications can be other strings, but prefixed with "_MOD_")
1023 * @param string $file_ref File reference to locallang file, eg. "EXT:lang/locallang_csh_pages.xlf" (or ".xml")
1024 * @return void
1025 */
1026 static public function addLLrefForTCAdescr($tca_descr_key, $file_ref) {
1027 if ($tca_descr_key) {
1028 if (!is_array($GLOBALS['TCA_DESCR'][$tca_descr_key])) {
1029 $GLOBALS['TCA_DESCR'][$tca_descr_key] = array();
1030 }
1031 if (!is_array($GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'])) {
1032 $GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'] = array();
1033 }
1034 $GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'][] = $file_ref;
1035 }
1036 }
1037
1038 /**
1039 * Registers a navigation component
1040 *
1041 * @param string $module
1042 * @param string $componentId
1043 * @param string $extensionKey
1044 * @throws \RuntimeException
1045 *@return void
1046 */
1047 static public function addNavigationComponent($module, $componentId, $extensionKey = NULL) {
1048 $extensionKey = $extensionKey ?: $GLOBALS['_EXTKEY'];
1049 if (!isset($extensionKey)) {
1050 throw new \RuntimeException('No extensionKey set in addNavigationComponent(). Provide it as third Parameter', 1404068039);
1051 }
1052 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module] = array(
1053 'componentId' => $componentId,
1054 'extKey' => $extensionKey,
1055 'isCoreComponent' => FALSE
1056 );
1057 }
1058
1059 /**
1060 * Registers a core navigation component
1061 *
1062 * @param string $module
1063 * @param string $componentId
1064 * @return void
1065 */
1066 static public function addCoreNavigationComponent($module, $componentId) {
1067 self::addNavigationComponent($module, $componentId);
1068 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module]['isCoreComponent'] = TRUE;
1069 }
1070
1071 /**************************************
1072 *
1073 * Adding SERVICES features
1074 *
1075 ***************************************/
1076 /**
1077 * Adds a service to the global services array
1078 *
1079 * @param string $extKey Extension key
1080 * @param string $serviceType Service type, must not be prefixed "tx_" or "Tx_
1081 * @param string $serviceKey Service key, must be prefixed "tx_", "Tx_" or "user_
1082 * @param array $info Service description array
1083 * @return void
1084 */
1085 static public function addService($extKey, $serviceType, $serviceKey, $info) {
1086 if ($serviceType && is_array($info)) {
1087 $info['priority'] = max(0, min(100, $info['priority']));
1088 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = $info;
1089 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['extKey'] = $extKey;
1090 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceKey'] = $serviceKey;
1091 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceType'] = $serviceType;
1092 // Change the priority (and other values) from $GLOBALS['TYPO3_CONF_VARS']
1093 // $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]['priority']
1094 // even the activation is possible (a unix service might be possible on windows for some reasons)
1095 if (is_array($GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey])) {
1096 // No check is done here - there might be configuration values only the service type knows about, so
1097 // we pass everything
1098 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = array_merge($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey], $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]);
1099 }
1100 // OS check
1101 // Empty $os means 'not limited to one OS', therefore a check is not needed
1102 if ($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] && $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os'] != '') {
1103 // TYPO3_OS is not yet defined
1104 $os_type = stripos(PHP_OS, 'win') !== FALSE && !stripos(PHP_OS, 'darwin') !== FALSE ? 'WIN' : 'UNIX';
1105 $os = GeneralUtility::trimExplode(',', strtoupper($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os']));
1106 if (!in_array($os_type, $os)) {
1107 self::deactivateService($serviceType, $serviceKey);
1108 }
1109 }
1110 // Convert subtype list to array for quicker access
1111 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'] = array();
1112 $serviceSubTypes = GeneralUtility::trimExplode(',', $info['subtype']);
1113 foreach ($serviceSubTypes as $subtype) {
1114 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'][$subtype] = $subtype;
1115 }
1116 }
1117 }
1118
1119 /**
1120 * Find the available service with highest priority
1121 *
1122 * @param string $serviceType Service type
1123 * @param string $serviceSubType Service sub type
1124 * @param mixed $excludeServiceKeys Service keys that should be excluded in the search for a service. Array or comma list.
1125 * @return mixed Service info array if a service was found, FALSE otherwise
1126 */
1127 static public function findService($serviceType, $serviceSubType = '', $excludeServiceKeys = array()) {
1128 $serviceKey = FALSE;
1129 $serviceInfo = FALSE;
1130 $priority = 0;
1131 $quality = 0;
1132 if (!is_array($excludeServiceKeys)) {
1133 $excludeServiceKeys = GeneralUtility::trimExplode(',', $excludeServiceKeys, TRUE);
1134 }
1135 if (is_array($GLOBALS['T3_SERVICES'][$serviceType])) {
1136 foreach ($GLOBALS['T3_SERVICES'][$serviceType] as $key => $info) {
1137 if (in_array($key, $excludeServiceKeys)) {
1138 continue;
1139 }
1140 // Select a subtype randomly
1141 // Useful to start a service by service key without knowing his subtypes - for testing purposes
1142 if ($serviceSubType == '*') {
1143 $serviceSubType = key($info['serviceSubTypes']);
1144 }
1145 // This matches empty subtype too
1146 if ($info['available'] && ($info['subtype'] == $serviceSubType || $info['serviceSubTypes'][$serviceSubType]) && $info['priority'] >= $priority) {
1147 // Has a lower quality than the already found, therefore we skip this service
1148 if ($info['priority'] == $priority && $info['quality'] < $quality) {
1149 continue;
1150 }
1151 // Check if the service is available
1152 $info['available'] = self::isServiceAvailable($serviceType, $key, $info);
1153 // Still available after exec check?
1154 if ($info['available']) {
1155 $serviceKey = $key;
1156 $priority = $info['priority'];
1157 $quality = $info['quality'];
1158 }
1159 }
1160 }
1161 }
1162 if ($serviceKey) {
1163 $serviceInfo = $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey];
1164 }
1165 return $serviceInfo;
1166 }
1167
1168 /**
1169 * Find a specific service identified by its key
1170 * Note that this completely bypasses the notions of priority and quality
1171 *
1172 * @param string $serviceKey Service key
1173 * @return array Service info array if a service was found
1174 * @throws \TYPO3\CMS\Core\Exception
1175 */
1176 static public function findServiceByKey($serviceKey) {
1177 if (is_array($GLOBALS['T3_SERVICES'])) {
1178 // Loop on all service types
1179 // NOTE: we don't care about the actual type, we are looking for a specific key
1180 foreach ($GLOBALS['T3_SERVICES'] as $serviceType => $servicesPerType) {
1181 if (isset($servicesPerType[$serviceKey])) {
1182 $serviceDetails = $servicesPerType[$serviceKey];
1183 // Test if service is available
1184 if (self::isServiceAvailable($serviceType, $serviceKey, $serviceDetails)) {
1185 // We have found the right service, return its information
1186 return $serviceDetails;
1187 }
1188 }
1189 }
1190 }
1191 throw new \TYPO3\CMS\Core\Exception('Service not found for key: ' . $serviceKey, 1319217244);
1192 }
1193
1194 /**
1195 * Check if a given service is available, based on the executable files it depends on
1196 *
1197 * @param string $serviceType Type of service
1198 * @param string $serviceKey Specific key of the service
1199 * @param array $serviceDetails Information about the service
1200 * @return bool Service availability
1201 */
1202 static public function isServiceAvailable($serviceType, $serviceKey, $serviceDetails) {
1203 // If the service depends on external programs - check if they exists
1204 if (trim($serviceDetails['exec'])) {
1205 $executables = GeneralUtility::trimExplode(',', $serviceDetails['exec'], TRUE);
1206 foreach ($executables as $executable) {
1207 // If at least one executable file is not available, exit early returning FALSE
1208 if (!CommandUtility::checkCommand($executable)) {
1209 self::deactivateService($serviceType, $serviceKey);
1210 return FALSE;
1211 }
1212 }
1213 }
1214 // The service is available
1215 return TRUE;
1216 }
1217
1218 /**
1219 * Deactivate a service
1220 *
1221 * @param string $serviceType Service type
1222 * @param string $serviceKey Service key
1223 * @return void
1224 */
1225 static public function deactivateService($serviceType, $serviceKey) {
1226 // ... maybe it's better to move non-available services to a different array??
1227 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] = FALSE;
1228 }
1229
1230 /**************************************
1231 *
1232 * Adding FRONTEND features
1233 * (related specifically to "cms" extension)
1234 *
1235 ***************************************/
1236 /**
1237 * Adds an entry to the list of plugins in content elements of type "Insert plugin"
1238 * 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)
1239 * 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.
1240 * 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
1241 * FOR USE IN ext_tables.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1242 *
1243 * @param array $itemArray Numerical array: [0] => Plugin label, [1] => Underscored extension key, [2] => Path to plugin icon relative to TYPO3_mainDir
1244 * @param string $type Type (eg. "list_type") - basically a field from "tt_content" table
1245 * @param string $extensionKey The extension key
1246 * @throws \RuntimeException
1247 * @return void
1248 */
1249 static public function addPlugin($itemArray, $type = 'list_type', $extensionKey = NULL) {
1250 $extensionKey = $extensionKey ?: $GLOBALS['_EXTKEY'];
1251 if (!isset($extensionKey)) {
1252 throw new \RuntimeException(
1253 'No extension key could be determined when calling addPlugin()!'
1254 . LF
1255 . 'This method is meant to be called from an ext_tables.php or Configuration/TCA/Overrides file. '
1256 . 'If you call it from Configuration/TCA/Overrides, the extension key needs to be specified as third parameter. '
1257 . 'Calling it from any other place e.g. ext_localconf.php does not work and is not supported.',
1258 1404068038
1259 );
1260 }
1261 if ($extensionKey && !$itemArray[2] && isset($GLOBALS['TYPO3_LOADED_EXT'][$extensionKey]['ext_icon'])) {
1262 $itemArray[2] = self::extRelPath($extensionKey) . $GLOBALS['TYPO3_LOADED_EXT'][$extensionKey]['ext_icon'];
1263 }
1264 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'])) {
1265 foreach ($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'] as $k => $v) {
1266 if ((string)$v[1] === (string)$itemArray[1]) {
1267 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][$k] = $itemArray;
1268 return;
1269 }
1270 }
1271 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][] = $itemArray;
1272 }
1273 }
1274
1275 /**
1276 * Adds an entry to the "ds" array of the tt_content field "pi_flexform".
1277 * This is used by plugins to add a flexform XML reference / content for use when they are selected as plugin or content element.
1278 *
1279 * @param string $piKeyToMatch Plugin key as used in the list_type field. Use the asterisk * to match all list_type values.
1280 * @param string $value Either a reference to a flex-form XML file (eg. "FILE:EXT:newloginbox/flexform_ds.xml") or the XML directly.
1281 * @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.
1282 * @return void
1283 * @see addPlugin()
1284 */
1285 static public function addPiFlexFormValue($piKeyToMatch, $value, $CTypeToMatch = 'list') {
1286 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'])) {
1287 $GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'][$piKeyToMatch . ',' . $CTypeToMatch] = $value;
1288 }
1289 }
1290
1291 /**
1292 * Adds the $table tablename to the list of tables allowed to be includes by content element type "Insert records"
1293 * By using $content_table and $content_field you can also use the function for other tables.
1294 * FOR USE IN ext_tables.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1295 *
1296 * @param string $table Table name to allow for "insert record
1297 * @param string $content_table Table name TO WHICH the $table name is applied. See $content_field as well.
1298 * @param string $content_field Field name in the database $content_table in which $table is allowed to be added as a reference ("Insert Record")
1299 * @return void
1300 */
1301 static public function addToInsertRecords($table, $content_table = 'tt_content', $content_field = 'records') {
1302 if (is_array($GLOBALS['TCA'][$content_table]['columns']) && isset($GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'])) {
1303 $GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'] .= ',' . $table;
1304 }
1305 }
1306
1307 /**
1308 * Add PlugIn to Static Template #43
1309 *
1310 * 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.
1311 * 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"
1312 * $type determines the type of frontend plugin:
1313 * + list_type (default) - the good old "Insert plugin" entry
1314 * + menu_type - a "Menu/Sitemap" entry
1315 * + CType - a new content element type
1316 * + header_layout - an additional header type (added to the selection of layout1-5)
1317 * + includeLib - just includes the library for manual use somewhere in TypoScript.
1318 * (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)
1319 * FOR USE IN ext_localconf.php FILES
1320 *
1321 * @param string $key The extension key
1322 * @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.
1323 * @param string $prefix Is used as a - yes, suffix - of the class name (fx. "_pi1")
1324 * @param string $type See description above
1325 * @param int $cached If $cached is set as USER content object (cObject) is created - otherwise a USER_INT object is created.
1326 *
1327 * @return void
1328 */
1329 static public function addPItoST43($key, $classFile = '', $prefix = '', $type = 'list_type', $cached = 0) {
1330 $classFile = $classFile ? $classFile : 'pi/class.tx_' . str_replace('_', '', $key) . $prefix . '.php';
1331 $cN = self::getCN($key);
1332 // General plugin
1333 $pluginContent = trim('
1334 plugin.' . $cN . $prefix . ' = USER' . ($cached ? '' : '_INT') . '
1335 plugin.' . $cN . $prefix . ' {
1336 includeLibs = ' . $GLOBALS['TYPO3_LOADED_EXT'][$key]['siteRelPath'] . $classFile . '
1337 userFunc = ' . $cN . $prefix . '->main
1338 }');
1339 self::addTypoScript($key, 'setup', '
1340 # Setting ' . $key . ' plugin TypoScript
1341 ' . $pluginContent);
1342 // After ST43
1343 switch ($type) {
1344 case 'list_type':
1345 $addLine = 'tt_content.list.20.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1346 break;
1347 case 'menu_type':
1348 $addLine = 'tt_content.menu.20.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1349 break;
1350 case 'CType':
1351 $addLine = trim('
1352 tt_content.' . $key . $prefix . ' = COA
1353 tt_content.' . $key . $prefix . ' {
1354 10 = < lib.stdheader
1355 20 = < plugin.' . $cN . $prefix . '
1356 }
1357 ');
1358 break;
1359 case 'header_layout':
1360 $addLine = 'lib.stdheader.10.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1361 break;
1362 case 'includeLib':
1363 $addLine = 'page.1000 = < plugin.' . $cN . $prefix;
1364 break;
1365 default:
1366 $addLine = '';
1367 }
1368 if ($addLine) {
1369 self::addTypoScript($key, 'setup', '
1370 # Setting ' . $key . ' plugin TypoScript
1371 ' . $addLine . '
1372 ', 43);
1373 }
1374 }
1375
1376 /**
1377 * Call this method to add an entry in the static template list found in sys_templates
1378 * FOR USE IN ext_tables.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1379 *
1380 * @param string $extKey Is of course the extension key
1381 * @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/
1382 * @param string $title Is the title in the selector box.
1383 * @return void
1384 * @see addTypoScript()
1385 */
1386 static public function addStaticFile($extKey, $path, $title) {
1387 if ($extKey && $path && is_array($GLOBALS['TCA']['sys_template']['columns'])) {
1388 $value = str_replace(',', '', 'EXT:' . $extKey . '/' . $path);
1389 $itemArray = array(trim($title . ' (' . $extKey . ')'), $value);
1390 $GLOBALS['TCA']['sys_template']['columns']['include_static_file']['config']['items'][] = $itemArray;
1391 }
1392 }
1393
1394 /**
1395 * Adds $content to the default TypoScript setup code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_setup']
1396 * Prefixed with a [GLOBAL] line
1397 * FOR USE IN ext_localconf.php FILES
1398 *
1399 * @param string $content TypoScript Setup string
1400 * @return void
1401 */
1402 static public function addTypoScriptSetup($content) {
1403 self::appendToTypoConfVars('FE', 'defaultTypoScript_setup', '
1404 [GLOBAL]
1405 ' . $content);
1406 }
1407
1408 /**
1409 * Adds $content to the default TypoScript constants code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_constants']
1410 * Prefixed with a [GLOBAL] line
1411 * FOR USE IN ext_localconf.php FILES
1412 *
1413 * @param string $content TypoScript Constants string
1414 * @return void
1415 */
1416 static public function addTypoScriptConstants($content) {
1417 self::appendToTypoConfVars('FE', 'defaultTypoScript_constants', '
1418 [GLOBAL]
1419 ' . $content);
1420 }
1421
1422 /**
1423 * Adds $content to the default TypoScript code for either setup or constants as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_*']
1424 * (Basically this function can do the same as addTypoScriptSetup and addTypoScriptConstants - just with a little more hazzle, but also with some more options!)
1425 * FOR USE IN ext_localconf.php FILES
1426 * Note: As of TYPO3 CMS 6.2, static template #43 (content: default) was replaced with "defaultContentRendering" which makes it
1427 * possible that a first extension like css_styled_content registers a "contentRendering" template (= a template that defines default content rendering TypoScript)
1428 * by adding itself to $TYPO3_CONF_VARS[FE][contentRenderingTemplates][] = 'myext/Configuration/TypoScript'.
1429 * An extension calling addTypoScript('myext', 'setup', $typoScript, 'defaultContentRendering') will add its TypoScript directly after;
1430 * For now, "43" and "defaultContentRendering" can be used, but defaultContentRendering is more descriptive and should be used in the future
1431 *
1432 * @param string $key Is the extension key (informative only).
1433 * @param string $type Is either "setup" or "constants" and obviously determines which kind of TypoScript code we are adding.
1434 * @param string $content Is the TS content, will be prefixed with a [GLOBAL] line and a comment-header.
1435 * @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.
1436 *
1437 * @return void
1438 */
1439 static public function addTypoScript($key, $type, $content, $afterStaticUid = 0) {
1440 if ($type === 'setup' || $type === 'constants') {
1441 $content = '
1442
1443 [GLOBAL]
1444 #############################################
1445 ## TypoScript added by extension "' . $key . '"
1446 #############################################
1447
1448 ' . $content;
1449 if ($afterStaticUid) {
1450 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.'][$afterStaticUid] .= $content;
1451 // If 'content (default)' is targeted (static uid 43),
1452 // the content is added after typoscript of type contentRendering, eg. css_styled_content, see EXT:frontend/TemplateService for that
1453 if ($afterStaticUid == 43 || $afterStaticUid === 'defaultContentRendering') {
1454 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.']['defaultContentRendering'] .= $content;
1455 }
1456 } else {
1457 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type] .= $content;
1458 }
1459 }
1460 }
1461
1462 /***************************************
1463 *
1464 * Internal extension management methods
1465 *
1466 ***************************************/
1467 /**
1468 * Find extension icon
1469 *
1470 * @param string $extensionPath Path to extension directory.
1471 * @param bool $returnFullPath Return full path of file.
1472 *
1473 * @return string
1474 */
1475 static public function getExtensionIcon($extensionPath, $returnFullPath = FALSE) {
1476 $icon = '';
1477 $iconFileTypesToCheckFor = array('png', 'svg', 'gif');
1478 foreach ($iconFileTypesToCheckFor as $fileType) {
1479 if (file_exists($extensionPath . 'ext_icon.' . $fileType)) {
1480 $icon = 'ext_icon.' . $fileType;
1481 break;
1482 }
1483 }
1484 return $returnFullPath ? $extensionPath . $icon : $icon;
1485 }
1486
1487 /**
1488 * Execute all ext_localconf.php files of loaded extensions.
1489 * The method implements an optionally used caching mechanism that concatenates all
1490 * ext_localconf.php files in one file.
1491 *
1492 * This is an internal method. It is only used during bootstrap and
1493 * extensions should not use it!
1494 *
1495 * @param bool $allowCaching Whether or not to load / create concatenated cache file
1496 * @return void
1497 * @access private
1498 */
1499 static public function loadExtLocalconf($allowCaching = TRUE) {
1500 if ($allowCaching) {
1501 $cacheIdentifier = self::getExtLocalconfCacheIdentifier();
1502 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1503 $codeCache = self::getCacheManager()->getCache('cache_core');
1504 if ($codeCache->has($cacheIdentifier)) {
1505 $codeCache->requireOnce($cacheIdentifier);
1506 } else {
1507 self::loadSingleExtLocalconfFiles();
1508 self::createExtLocalconfCacheEntry();
1509 }
1510 } else {
1511 self::loadSingleExtLocalconfFiles();
1512 }
1513 }
1514
1515 /**
1516 * Execute ext_localconf.php files from extensions
1517 *
1518 * @return void
1519 */
1520 static protected function loadSingleExtLocalconfFiles() {
1521 // This is the main array meant to be manipulated in the ext_localconf.php files
1522 // In general it is recommended to not rely on it to be globally defined in that
1523 // scope but to use $GLOBALS['TYPO3_CONF_VARS'] instead.
1524 // Nevertheless we define it here as global for backwards compatibility.
1525 global $TYPO3_CONF_VARS;
1526 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1527 if ((is_array($extensionInformation) || $extensionInformation instanceof \ArrayAccess) && isset($extensionInformation['ext_localconf.php'])) {
1528 // $_EXTKEY and $_EXTCONF are available in ext_localconf.php
1529 // and are explicitly set in cached file as well
1530 $_EXTCONF = isset($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY]) ? $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY] : NULL;
1531 require $extensionInformation['ext_localconf.php'];
1532 }
1533 }
1534 }
1535
1536 /**
1537 * Create cache entry for concatenated ext_localconf.php files
1538 *
1539 * @return void
1540 */
1541 static protected function createExtLocalconfCacheEntry() {
1542 $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1543 $phpCodeToCache = array();
1544 // Set same globals as in loadSingleExtLocalconfFiles()
1545 $phpCodeToCache[] = '/**';
1546 $phpCodeToCache[] = ' * Compiled ext_localconf.php cache file';
1547 $phpCodeToCache[] = ' */';
1548 $phpCodeToCache[] = '';
1549 $phpCodeToCache[] = 'global $TYPO3_CONF_VARS, $T3_SERVICES, $T3_VAR;';
1550 $phpCodeToCache[] = '';
1551 // Iterate through loaded extensions and add ext_localconf content
1552 foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1553 if (isset($extensionDetails['ext_localconf.php']) && $extensionDetails['ext_localconf.php']) {
1554 // Include a header per extension to make the cache file more readable
1555 $phpCodeToCache[] = '/**';
1556 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1557 $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_localconf.php'];
1558 $phpCodeToCache[] = ' */';
1559 $phpCodeToCache[] = '';
1560 // Set $_EXTKEY and $_EXTCONF for this extension
1561 $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1562 $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY];';
1563 $phpCodeToCache[] = '';
1564 // Add ext_localconf.php content of extension
1565 $phpCodeToCache[] = trim(GeneralUtility::getUrl($extensionDetails['ext_localconf.php']));
1566 $phpCodeToCache[] = '';
1567 $phpCodeToCache[] = '';
1568 }
1569 }
1570 $phpCodeToCache = implode(LF, $phpCodeToCache);
1571 // Remove all start and ending php tags from content
1572 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1573 self::getCacheManager()->getCache('cache_core')->set(self::getExtLocalconfCacheIdentifier(), $phpCodeToCache);
1574 }
1575
1576 /**
1577 * Cache identifier of concatenated ext_localconf file
1578 *
1579 * @return string
1580 */
1581 static protected function getExtLocalconfCacheIdentifier() {
1582 return 'ext_localconf_' . sha1((TYPO3_version . PATH_site . 'extLocalconf'));
1583 }
1584
1585 /**
1586 * Wrapper for buildBaseTcaFromSingleFiles handling caching.
1587 *
1588 * This builds 'base' TCA that is later overloaded by ext_tables.php.
1589 *
1590 * Use a cache file if exists and caching is allowed.
1591 *
1592 * This is an internal method. It is only used during bootstrap and
1593 * extensions should not use it!
1594 *
1595 * @param bool $allowCaching Whether or not to load / create concatenated cache file
1596 * @return void
1597 * @access private
1598 */
1599 static public function loadBaseTca($allowCaching = TRUE) {
1600 if ($allowCaching) {
1601 $cacheIdentifier = static::getBaseTcaCacheIdentifier();
1602 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1603 $codeCache = static::getCacheManager()->getCache('cache_core');
1604 if ($codeCache->has($cacheIdentifier)) {
1605 // substr is necessary, because the php frontend wraps php code around the cache value
1606 $GLOBALS['TCA'] = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
1607 } else {
1608 static::buildBaseTcaFromSingleFiles();
1609 static::createBaseTcaCacheFile();
1610 }
1611 } else {
1612 static::buildBaseTcaFromSingleFiles();
1613 }
1614 }
1615
1616 /**
1617 * Find all Configuration/TCA/* files of extensions and create base TCA from it.
1618 * The filename must be the table name in $GLOBALS['TCA'], and the content of
1619 * the file should return an array with content of a specific table.
1620 *
1621 * @return void
1622 * @see Extension core, cms, extensionmanager and others for examples.
1623 */
1624 static protected function buildBaseTcaFromSingleFiles() {
1625 $GLOBALS['TCA'] = array();
1626
1627 $activePackages = static::$packageManager->getActivePackages();
1628
1629 // First load "full table" files from Configuration/TCA
1630 foreach ($activePackages as $package) {
1631 $tcaConfigurationDirectory = $package->getPackagePath() . 'Configuration/TCA';
1632 if (is_dir($tcaConfigurationDirectory)) {
1633 $files = scandir($tcaConfigurationDirectory);
1634 foreach ($files as $file) {
1635 if (
1636 is_file($tcaConfigurationDirectory . '/' . $file)
1637 && ($file !== '.')
1638 && ($file !== '..')
1639 && (substr($file, -4, 4) === '.php')
1640 ) {
1641 $tcaOfTable = require($tcaConfigurationDirectory . '/' . $file);
1642 if (is_array($tcaOfTable)) {
1643 // TCA table name is filename without .php suffix, eg 'sys_notes', not 'sys_notes.php'
1644 $tcaTableName = substr($file, 0, -4);
1645 $GLOBALS['TCA'][$tcaTableName] = $tcaOfTable;
1646 }
1647 }
1648 }
1649 }
1650 }
1651
1652 // Apply category stuff
1653 CategoryRegistry::getInstance()->applyTcaForPreRegisteredTables();
1654
1655 // Execute override files from Configuration/TCA/Overrides
1656 foreach ($activePackages as $package) {
1657 $tcaOverridesPathForPackage = $package->getPackagePath() . 'Configuration/TCA/Overrides';
1658 if (is_dir($tcaOverridesPathForPackage)) {
1659 $files = scandir($tcaOverridesPathForPackage);
1660 foreach ($files as $file) {
1661 if (
1662 is_file($tcaOverridesPathForPackage . '/' . $file)
1663 && ($file !== '.')
1664 && ($file !== '..')
1665 && (substr($file, -4, 4) === '.php')
1666 ) {
1667 require($tcaOverridesPathForPackage . '/' . $file);
1668 }
1669 }
1670 }
1671 }
1672
1673 static::emitTcaIsBeingBuiltSignal($GLOBALS['TCA']);
1674 }
1675
1676 /**
1677 * Emits the signal and uses the result of slots for the final TCA
1678 * This means, that *all* slots *must* return the complete TCA to
1679 * be effective. If a slot calls methods that manipulate the global array,
1680 * it needs to return the global array in the end. To be future proof,
1681 * a slot should manipulate the signal argument only and return it
1682 * after manipulation.
1683 *
1684 * @param array $tca
1685 */
1686 static protected function emitTcaIsBeingBuiltSignal(array $tca) {
1687 list($tca) = static::getSignalSlotDispatcher()->dispatch(__CLASS__, 'tcaIsBeingBuilt', array($tca));
1688 $GLOBALS['TCA'] = $tca;
1689 }
1690
1691 /**
1692 * Cache base $GLOBALS['TCA'] to cache file to require the whole thing in one
1693 * file for next access instead of cycling through all extensions again.
1694 *
1695 * @return void
1696 */
1697 static protected function createBaseTcaCacheFile() {
1698 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1699 $codeCache = self::getCacheManager()->getCache('cache_core');
1700 $codeCache->set(static::getBaseTcaCacheIdentifier(), serialize($GLOBALS['TCA']));
1701 }
1702
1703 /**
1704 * Cache identifier of base TCA cache entry.
1705 *
1706 * @return string
1707 */
1708 static protected function getBaseTcaCacheIdentifier() {
1709 return 'tca_base_' . sha1((TYPO3_version . PATH_site . 'tca'));
1710 }
1711
1712 /**
1713 * Execute all ext_tables.php files of loaded extensions.
1714 * The method implements an optionally used caching mechanism that concatenates all
1715 * ext_tables.php files in one file.
1716 *
1717 * This is an internal method. It is only used during bootstrap and
1718 * extensions should not use it!
1719 *
1720 * @param bool $allowCaching Whether to load / create concatenated cache file
1721 * @return void
1722 * @access private
1723 */
1724 static public function loadExtTables($allowCaching = TRUE) {
1725 if ($allowCaching && !self::$extTablesWasReadFromCacheOnce) {
1726 self::$extTablesWasReadFromCacheOnce = TRUE;
1727 $cacheIdentifier = self::getExtTablesCacheIdentifier();
1728 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1729 $codeCache = self::getCacheManager()->getCache('cache_core');
1730 if ($codeCache->has($cacheIdentifier)) {
1731 $codeCache->requireOnce($cacheIdentifier);
1732 } else {
1733 self::loadSingleExtTablesFiles();
1734 self::createExtTablesCacheEntry();
1735 }
1736 } else {
1737 self::loadSingleExtTablesFiles();
1738 }
1739 }
1740
1741 /**
1742 * Load ext_tables.php as single files
1743 *
1744 * @return void
1745 */
1746 static protected function loadSingleExtTablesFiles() {
1747 // In general it is recommended to not rely on it to be globally defined in that
1748 // scope, but we can not prohibit this without breaking backwards compatibility
1749 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
1750 global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;
1751 global $PAGES_TYPES, $TBE_STYLES, $FILEICONS;
1752 global $_EXTKEY;
1753 // Load each ext_tables.php file of loaded extensions
1754 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1755 if ((is_array($extensionInformation) || $extensionInformation instanceof \ArrayAccess) && $extensionInformation['ext_tables.php']) {
1756 // $_EXTKEY and $_EXTCONF are available in ext_tables.php
1757 // and are explicitly set in cached file as well
1758 $_EXTCONF = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY];
1759 require $extensionInformation['ext_tables.php'];
1760 static::loadNewTcaColumnsConfigFiles();
1761 }
1762 }
1763 }
1764
1765 /**
1766 * Create concatenated ext_tables.php cache file
1767 *
1768 * @return void
1769 */
1770 static protected function createExtTablesCacheEntry() {
1771 $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1772 $phpCodeToCache = array();
1773 // Set same globals as in loadSingleExtTablesFiles()
1774 $phpCodeToCache[] = '/**';
1775 $phpCodeToCache[] = ' * Compiled ext_tables.php cache file';
1776 $phpCodeToCache[] = ' */';
1777 $phpCodeToCache[] = '';
1778 $phpCodeToCache[] = 'global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;';
1779 $phpCodeToCache[] = 'global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;';
1780 $phpCodeToCache[] = 'global $PAGES_TYPES, $TBE_STYLES, $FILEICONS;';
1781 $phpCodeToCache[] = 'global $_EXTKEY;';
1782 $phpCodeToCache[] = '';
1783 // Iterate through loaded extensions and add ext_tables content
1784 foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1785 if (isset($extensionDetails['ext_tables.php']) && $extensionDetails['ext_tables.php']) {
1786 // Include a header per extension to make the cache file more readable
1787 $phpCodeToCache[] = '/**';
1788 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1789 $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_tables.php'];
1790 $phpCodeToCache[] = ' */';
1791 $phpCodeToCache[] = '';
1792 // Set $_EXTKEY and $_EXTCONF for this extension
1793 $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1794 $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY];';
1795 $phpCodeToCache[] = '';
1796 // Add ext_tables.php content of extension
1797 $phpCodeToCache[] = trim(GeneralUtility::getUrl($extensionDetails['ext_tables.php']));
1798 $phpCodeToCache[] = '';
1799 $phpCodeToCache[] = '\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::loadNewTcaColumnsConfigFiles();';
1800 $phpCodeToCache[] = '';
1801 }
1802 }
1803 $phpCodeToCache = implode(LF, $phpCodeToCache);
1804 // Remove all start and ending php tags from content
1805 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1806 self::getCacheManager()->getCache('cache_core')->set(self::getExtTablesCacheIdentifier(), $phpCodeToCache);
1807 }
1808
1809 /**
1810 * Loads "columns" of a $TCA table definition if extracted
1811 * to a "dynamicConfigFile". This method is called after each
1812 * single ext_tables.php files was included to immediately have
1813 * the full $TCA ready for the next extension.
1814 *
1815 * $TCA[$tableName]['ctrl']['dynamicConfigFile'] must be the
1816 * absolute path to a file.
1817 *
1818 * Be aware that 'dynamicConfigFile' is obsolete, and all TCA
1819 * table definitions should be moved to Configuration/TCA/tablename.php
1820 * to be fully loaded automatically.
1821 *
1822 * Example:
1823 * dynamicConfigFile = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY) . 'SysNote.php',
1824 *
1825 * @return void
1826 * @throws \RuntimeException
1827 * @internal Internal use ONLY. It is called by cache files and can not be protected. Do not call yourself!
1828 */
1829 static public function loadNewTcaColumnsConfigFiles() {
1830 global $TCA;
1831
1832 foreach (array_keys($TCA) as $tableName) {
1833 if (!isset($TCA[$tableName]['columns'])) {
1834 $columnsConfigFile = $TCA[$tableName]['ctrl']['dynamicConfigFile'];
1835 if ($columnsConfigFile) {
1836 if (GeneralUtility::isAbsPath($columnsConfigFile)) {
1837 include($columnsConfigFile);
1838 } else {
1839 throw new \RuntimeException(
1840 'Columns configuration file not found',
1841 1341151261
1842 );
1843 }
1844 }
1845 }
1846 }
1847 }
1848
1849 /**
1850 * Cache identifier for concatenated ext_tables.php files
1851 *
1852 * @return string
1853 */
1854 static protected function getExtTablesCacheIdentifier() {
1855 return 'ext_tables_' . sha1((TYPO3_version . PATH_site . 'extTables'));
1856 }
1857
1858 /**
1859 * Remove cache files from php code cache, grouped by 'system'
1860 *
1861 * This removes the following cache entries:
1862 * - autoloader cache registry
1863 * - cache loaded extension array
1864 * - ext_localconf concatenation
1865 * - ext_tables concatenation
1866 *
1867 * This method is usually only used by extension that fiddle
1868 * with the loaded extensions. An example is the extension
1869 * manager and the install tool.
1870 *
1871 * @return void
1872 */
1873 static public function removeCacheFiles() {
1874 self::getCacheManager()->flushCachesInGroup('system');
1875 }
1876
1877 /**
1878 * Gets an array of loaded extension keys
1879 *
1880 * @return array Loaded extensions
1881 */
1882 static public function getLoadedExtensionListArray() {
1883 return array_keys(static::$packageManager->getActivePackages());
1884 }
1885
1886 /**
1887 * Returns REQUIRED_EXTENSIONS constant set by package manager as array.
1888 *
1889 * @return array List of required extensions
1890 * @deprecated since 6,2, will be removed two versions later.
1891 */
1892 static public function getRequiredExtensionListArray() {
1893 GeneralUtility::logDeprecatedFunction();
1894 return GeneralUtility::trimExplode(',', REQUIRED_EXTENSIONS);
1895 }
1896
1897 /**
1898 * Loads given extension
1899 *
1900 * Warning: This method only works if the ugrade wizard to transform
1901 * localconf.php to LocalConfiguration.php was already run
1902 *
1903 * @param string $extensionKey Extension key to load
1904 * @return void
1905 * @throws \RuntimeException
1906 */
1907 static public function loadExtension($extensionKey) {
1908 if (static::$packageManager->isPackageActive($extensionKey)) {
1909 throw new \RuntimeException('Extension already loaded', 1342345486);
1910 }
1911 static::$packageManager->activatePackage($extensionKey);
1912 }
1913
1914 /**
1915 * Unloads given extension
1916 *
1917 * Warning: This method only works if the ugrade wizard to transform
1918 * localconf.php to LocalConfiguration.php was already run
1919 *
1920 * @param string $extensionKey Extension key to remove
1921 * @return void
1922 * @throws \RuntimeException
1923 */
1924 static public function unloadExtension($extensionKey) {
1925 if (!static::$packageManager->isPackageActive($extensionKey)) {
1926 throw new \RuntimeException('Extension not loaded', 1342345487);
1927 }
1928 static::$packageManager->deactivatePackage($extensionKey);
1929 }
1930
1931 /**
1932 * Writes extension list and clear cache files.
1933 *
1934 * @TODO: This method should be protected, but with current em it is hard to do so,
1935 * @TODO: Find out if we may remove this already
1936 * @param array $newExtensionList Extension array to load, loader order is kept
1937 * @return void
1938 * @internal
1939 * @deprecated since 6.2, will be removed two versions later
1940 */
1941 static public function writeNewExtensionList(array $newExtensionList) {
1942 GeneralUtility::logDeprecatedFunction();
1943 }
1944
1945 /**
1946 * Makes a table categorizable by adding value into the category registry.
1947 * FOR USE IN ext_localconf.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
1948 *
1949 * @param string $extensionKey Extension key to be used
1950 * @param string $tableName Name of the table to be categorized
1951 * @param string $fieldName Name of the field to be used to store categories
1952 * @param array $options Additional configuration options
1953 * @see addTCAcolumns
1954 * @see addToAllTCAtypes
1955 */
1956 static public function makeCategorizable($extensionKey, $tableName, $fieldName = 'categories', array $options = array()) {
1957 // Update the category registry
1958 $result = CategoryRegistry::getInstance()->add($extensionKey, $tableName, $fieldName, $options);
1959 if ($result === FALSE) {
1960 $message = '\TYPO3\CMS\Core\Category\CategoryRegistry: no category registered for table "%s". Key was already registered.';
1961 /** @var $logger \TYPO3\CMS\Core\Log\Logger */
1962 $logger = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Log\\LogManager')->getLogger(__CLASS__);
1963 $logger->warning(
1964 sprintf($message, $tableName)
1965 );
1966 }
1967 }
1968 }