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