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