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