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