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