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