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