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