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