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