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