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