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