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