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