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