3b3bbbd420746bd54904e67365f4e8afed1328b1
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Extension / ExtensionManager.php
1 <?php
2 namespace TYPO3\CMS\Core\Extension;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the textfile GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29 /**
30 * Extension Management functions
31 *
32 * This class is never instantiated, rather the methods inside is called as functions like
33 * t3lib_extMgm::isLoaded('my_extension');
34 *
35 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
36 * @package TYPO3
37 * @subpackage t3lib
38 */
39 class ExtensionManager {
40
41 static protected $extensionKeyMap;
42
43 /**
44 * TRUE, if ext_tables file was read from cache for this script run.
45 * The frontend tends to do that multiple times, but the caching framework does
46 * not allow this (via a require_once call). This variable is used to track
47 * the access to the cache file to read the single ext_tables.php if it was
48 * already read from cache
49 *
50 * @TODO : See if we can get rid of the 'load multiple times' scenario in fe
51 * @var boolean
52 */
53 static protected $extTablesWasReadFromCacheOnce = FALSE;
54
55 /**************************************
56 *
57 * PATHS and other evaluation
58 *
59 ***************************************/
60 /**
61 * Returns TRUE if the extension with extension key $key is loaded.
62 *
63 * @param string $key Extension key to test
64 * @param boolean $exitOnError If $exitOnError is TRUE and the extension is not loaded the function will die with an error message
65 * @return boolean
66 * @throws \BadFunctionCallException
67 */
68 static public function isLoaded($key, $exitOnError = FALSE) {
69 $isLoaded = in_array($key, static::getLoadedExtensionListArray());
70 if ($exitOnError && !$isLoaded) {
71 throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension "' . $key . '" is not loaded!', 1270853910);
72 }
73 return $isLoaded;
74 }
75
76 /**
77 * Returns the absolute path to the extension with extension key $key
78 * If the extension is not loaded the function will die with an error message
79 * Useful for internal fileoperations
80 *
81 * @param $key string Extension key
82 * @param $script string $script is appended to the output if set.
83 * @throws \BadFunctionCallException
84 * @return string
85 */
86 static public function extPath($key, $script = '') {
87 if (isset($GLOBALS['TYPO3_LOADED_EXT'])) {
88 if (!isset($GLOBALS['TYPO3_LOADED_EXT'][$key])) {
89 throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension key "' . $key . '" is NOT loaded!', 1270853878);
90 }
91 $extensionPath = PATH_site . $GLOBALS['TYPO3_LOADED_EXT'][$key]['siteRelPath'];
92 } else {
93 $loadedExtensions = array_flip(static::getLoadedExtensionListArray());
94 if (!isset($loadedExtensions[$key])) {
95 throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension key "' . $key . '" is NOT loaded!', 1294430950);
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('TYPO3 Fatal Error: Extension "' . $key . '" NOT found!', 1294430951);
105 }
106 }
107 return $extensionPath . $script;
108 }
109
110 /**
111 * Returns the relative path to the extension as measured from from the TYPO3_mainDir
112 * If the extension is not loaded the function will die with an error message
113 * Useful for images and links from backend
114 *
115 * @param string $key Extension key
116 * @return string
117 */
118 static public function extRelPath($key) {
119 if (!isset($GLOBALS['TYPO3_LOADED_EXT'][$key])) {
120 throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension key "' . $key . '" is NOT loaded!', 1270853879);
121 }
122 return $GLOBALS['TYPO3_LOADED_EXT'][$key]['typo3RelPath'];
123 }
124
125 /**
126 * Returns the relative path to the extension as measured from the PATH_site (frontend)
127 * If the extension is not loaded the function will die with an error message
128 * Useful for images and links from the frontend
129 *
130 * @param string $key Extension key
131 * @return string
132 */
133 static public function siteRelPath($key) {
134 return substr(self::extPath($key), strlen(PATH_site));
135 }
136
137 /**
138 * Returns the correct class name prefix for the extension key $key
139 *
140 * @param string $key Extension key
141 * @return string
142 * @internal
143 */
144 static public function getCN($key) {
145 return substr($key, 0, 5) == 'user_' ? 'user_' . str_replace('_', '', substr($key, 5)) : 'tx_' . str_replace('_', '', $key);
146 }
147
148 /**
149 * Returns the real extension key like 'tt_news' from an extension prefix like 'tx_ttnews'.
150 *
151 * @param string $prefix The extension prefix (e.g. 'tx_ttnews')
152 * @return mixed Real extension key (string) or FALSE (boolean) if something went wrong
153 */
154 static public function getExtensionKeyByPrefix($prefix) {
155 $result = FALSE;
156 // Build map of short keys referencing to real keys:
157 if (!isset(self::$extensionKeyMap)) {
158 self::$extensionKeyMap = array();
159 foreach (array_keys($GLOBALS['TYPO3_LOADED_EXT']) as $extensionKey) {
160 $shortKey = str_replace('_', '', $extensionKey);
161 self::$extensionKeyMap[$shortKey] = $extensionKey;
162 }
163 }
164 // Lookup by the given short key:
165 $parts = explode('_', $prefix);
166 if (isset(self::$extensionKeyMap[$parts[1]])) {
167 $result = self::$extensionKeyMap[$parts[1]];
168 }
169 return $result;
170 }
171
172 /**
173 * Clears the extension key map.
174 *
175 * @return void
176 */
177 static public function clearExtensionKeyMap() {
178 self::$extensionKeyMap = NULL;
179 }
180
181 /**
182 * Retrieves the version of an installed extension.
183 * If the extension is not installed, this function returns an empty string.
184 *
185 * @param string $key The key of the extension to look up, must not be empty
186 * @return string The extension version as a string in the format "x.y.z",
187 */
188 static public function getExtensionVersion($key) {
189 if (!is_string($key) || empty($key)) {
190 throw new \InvalidArgumentException('Extension key must be a non-empty string.', 1294586096);
191 }
192 if (!static::isLoaded($key)) {
193 return '';
194 }
195 $runtimeCache = $GLOBALS['typo3CacheManager']->getCache('cache_runtime');
196 $cacheIdentifier = 'extMgmExtVersion-' . $key;
197 if (!($extensionVersion = $runtimeCache->get($cacheIdentifier))) {
198 $EM_CONF = array();
199 $_EXTKEY = $key;
200 include self::extPath($key) . 'ext_emconf.php';
201 $extensionVersion = $EM_CONF[$key]['version'];
202 $runtimeCache->set($cacheIdentifier, $extensionVersion);
203 }
204 return $extensionVersion;
205 }
206
207 /**************************************
208 *
209 * Adding BACKEND features
210 * (related to core features)
211 *
212 ***************************************/
213 /**
214 * Adding fields to an existing table definition in $GLOBALS['TCA']
215 * Adds an array with $GLOBALS['TCA'] column-configuration to the $GLOBALS['TCA']-entry for that table.
216 * 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!
217 * So to have the fields displayed you must also call fx. addToAllTCAtypes or manually add the fields to the types list.
218 * FOR USE IN ext_tables.php FILES
219 *
220 * @param string $table The table name of a table already present in $GLOBALS['TCA'] with a columns section
221 * @param array $columnArray The array with the additional columns (typical some fields an extension wants to add)
222 * @param boolean $addTofeInterface If $addTofeInterface is TRUE the list of fields are also added to the fe_admin_fieldList.
223 * @return void
224 */
225 static public function addTCAcolumns($table, $columnArray, $addTofeInterface = 0) {
226 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA($table);
227 if (is_array($columnArray) && is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'])) {
228 // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
229 $GLOBALS['TCA'][$table]['columns'] = array_merge($GLOBALS['TCA'][$table]['columns'], $columnArray);
230 if ($addTofeInterface) {
231 $GLOBALS['TCA'][$table]['feInterface']['fe_admin_fieldList'] .= ',' . implode(',', array_keys($columnArray));
232 }
233 }
234 }
235
236 /**
237 * Makes fields visible in the TCEforms, adding them to the end of (all) "types"-configurations
238 *
239 * Adds a string $str (comma list of field names) to all ["types"][xxx]["showitem"] entries for table $table (unless limited by $specificTypesList)
240 * This is needed to have new fields shown automatically in the TCEFORMS of a record from $table.
241 * Typically this function is called after having added new columns (database fields) with the addTCAcolumns function
242 * FOR USE IN ext_tables.php FILES
243 *
244 * @param string $table Table name
245 * @param string $str Field list to add.
246 * @param string $specificTypesList List of specific types to add the field list to. (If empty, all type entries are affected)
247 * @param string $position Insert fields before (default) or after one
248 * @return void
249 */
250 static public function addToAllTCAtypes($table, $str, $specificTypesList = '', $position = '') {
251 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA($table);
252 $str = trim($str);
253 $palettesChanged = array();
254 if ($str && is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['types'])) {
255 foreach ($GLOBALS['TCA'][$table]['types'] as $type => &$typeDetails) {
256 if ($specificTypesList === '' || \TYPO3\CMS\Core\Utility\GeneralUtility::inList($specificTypesList, $type)) {
257 $fieldExists = FALSE;
258 if ($position != '' && is_array($GLOBALS['TCA'][$table]['palettes'])) {
259 $positionArray = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(':', $position);
260 if ($positionArray[0] == 'replace') {
261 foreach ($GLOBALS['TCA'][$table]['palettes'] as $palette => $paletteDetails) {
262 if (preg_match('/\\b' . $palette . '\\b/', $typeDetails['showitem']) > 0 && preg_match('/\\b' . $positionArray[1] . '\\b/', $paletteDetails['showitem']) > 0) {
263 self::addFieldsToPalette($table, $palette, $str, $position);
264 // Save that palette in case other types use it
265 $palettesChanged[] = $palette;
266 $fieldExists = TRUE;
267 } elseif (in_array($palette, $palettesChanged)) {
268 $fieldExists = TRUE;
269 }
270 }
271 } else {
272 if (strpos($typeDetails['showitem'], $str) !== FALSE) {
273 $fieldExists = TRUE;
274 } else {
275 foreach ($GLOBALS['TCA'][$table]['palettes'] as $palette => $paletteDetails) {
276 if (preg_match('/\\b' . $palette . '\\b/', $typeDetails['showitem']) > 0 && preg_match('/\\b' . $positionArray[1] . '\\b/', $paletteDetails['showitem']) > 0) {
277 $position = $positionArray[0] . ':--palette--;;' . $palette;
278 }
279 }
280 }
281 }
282 } else {
283 if (strpos($typeDetails['showitem'], $str) !== FALSE) {
284 $fieldExists = TRUE;
285 } elseif (is_array($GLOBALS['TCA'][$table]['palettes'])) {
286 foreach ($GLOBALS['TCA'][$table]['palettes'] as $palette => $paletteDetails) {
287 if (preg_match('/\\b' . $palette . '\\b/', $typeDetails['showitem']) > 0 && strpos($paletteDetails['showitem'], $str) !== FALSE) {
288 $fieldExists = TRUE;
289 }
290 }
291 }
292 }
293 if ($fieldExists === FALSE) {
294 $typeDetails['showitem'] = self::executePositionedStringInsertion($typeDetails['showitem'], $str, $position);
295 }
296 }
297 }
298 unset($typeDetails);
299 }
300 }
301
302 /**
303 * Adds new fields to all palettes of an existing field.
304 * If the field does not have a palette yet, it's created automatically and
305 * gets called "generatedFor-$field".
306 *
307 * @param string $table Name of the table
308 * @param string $field Name of the field that has the palette to be extended
309 * @param string $addFields List of fields to be added to the palette
310 * @param string $insertionPosition Insert fields before (default) or after one
311 * @return void
312 */
313 static public function addFieldsToAllPalettesOfField($table, $field, $addFields, $insertionPosition = '') {
314 $generatedPalette = '';
315 $processedPalettes = array();
316 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA($table);
317 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
318 $types =& $GLOBALS['TCA'][$table]['types'];
319 if (is_array($types)) {
320 // Iterate through all types and search for the field that defines the palette to be extended:
321 foreach (array_keys($types) as $type) {
322 $items = self::explodeItemList($types[$type]['showitem']);
323 if (isset($items[$field])) {
324 // If the field already has a palette, extend it:
325 if ($items[$field]['details']['palette']) {
326 $palette = $items[$field]['details']['palette'];
327 if (!isset($processedPalettes[$palette])) {
328 self::addFieldsToPalette($table, $palette, $addFields, $insertionPosition);
329 $processedPalettes[$palette] = TRUE;
330 }
331 } else {
332 if ($generatedPalette) {
333 $palette = $generatedPalette;
334 } else {
335 $palette = ($generatedPalette = 'generatedFor-' . $field);
336 self::addFieldsToPalette($table, $palette, $addFields, $insertionPosition);
337 }
338 $items[$field]['details']['palette'] = $palette;
339 $types[$type]['showitem'] = self::generateItemList($items);
340 }
341 }
342 }
343 }
344 }
345 }
346
347 /**
348 * Adds new fields to a palette.
349 * If the palette does not exist yet, it's created automatically.
350 *
351 * @param string $table Name of the table
352 * @param string $palette Name of the palette to be extended
353 * @param string $addFields List of fields to be added to the palette
354 * @param string $insertionPosition Insert fields before (default) or after one
355 * @return void
356 */
357 static public function addFieldsToPalette($table, $palette, $addFields, $insertionPosition = '') {
358 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA($table);
359 if (isset($GLOBALS['TCA'][$table])) {
360 $paletteData =& $GLOBALS['TCA'][$table]['palettes'][$palette];
361 // If palette already exists, merge the data:
362 if (is_array($paletteData)) {
363 $paletteData['showitem'] = self::executePositionedStringInsertion($paletteData['showitem'], $addFields, $insertionPosition);
364 } else {
365 $paletteData['showitem'] = self::removeDuplicatesForInsertion($addFields);
366 }
367 }
368 }
369
370 /**
371 * Add an item to a select field item list.
372 *
373 * Warning: Do not use this method for radio or check types, especially not
374 * with $relativeToField and $relativePosition parameters. This would shift
375 * existing database data 'off by one'.
376 *
377 * As an example, this can be used to add an item to tt_content CType select
378 * drop-down after the existing 'mailform' field with these parameters:
379 * - $table = 'tt_content'
380 * - $field = 'CType'
381 * - $item = array(
382 * 'LLL:EXT:cms/locallang_ttc.xml:CType.I.10',
383 * 'login',
384 * 'i/tt_content_login.gif',
385 * ),
386 * - $relativeToField = mailform
387 * - $relativePosition = after
388 *
389 * @throws InvalidArgumentException If given parameters are not of correct
390 * @throws RuntimeException If reference to related position fields can not
391 * @param string $table Name of TCA table
392 * @param string $field Name of TCA field
393 * @param array $item New item to add
394 * @param string $relativeToField Add item relative to existing field
395 * @param string $relativePosition Valid keywords: 'before', 'after'
396 * @return void
397 */
398 static public function addTcaSelectItem($table, $field, array $item, $relativeToField = '', $relativePosition = '') {
399 if (!is_string($table)) {
400 throw new \InvalidArgumentException('Given table is of type "' . gettype($table) . '" but a string is expected.', 1303236963);
401 }
402 if (!is_string($field)) {
403 throw new \InvalidArgumentException('Given field is of type "' . gettype($field) . '" but a string is expected.', 1303236964);
404 }
405 if (!is_string($relativeToField)) {
406 throw new \InvalidArgumentException('Given relative field is of type "' . gettype($relativeToField) . '" but a string is expected.', 1303236965);
407 }
408 if (!is_string($relativePosition)) {
409 throw new \InvalidArgumentException('Given relative position is of type "' . gettype($relativePosition) . '" but a string is expected.', 1303236966);
410 }
411 if ($relativePosition !== '' && $relativePosition !== 'before' && $relativePosition !== 'after' && $relativePosition !== 'replace') {
412 throw new \InvalidArgumentException('Relative position must be either empty or one of "before", "after", "replace".', 1303236967);
413 }
414 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA($table);
415 if (!is_array($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'])) {
416 throw new \RuntimeException('Given select field item list was not found.', 1303237468);
417 }
418 // Make sure item keys are integers
419 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'] = array_values($GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
420 if (strlen($relativePosition) > 0) {
421 // Insert at specified position
422 $matchedPosition = \TYPO3\CMS\Core\Utility\ArrayUtility::filterByValueRecursive($relativeToField, $GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
423 if (count($matchedPosition) > 0) {
424 $relativeItemKey = key($matchedPosition);
425 if ($relativePosition === 'replace') {
426 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][$relativeItemKey] = $item;
427 } else {
428 if ($relativePosition === 'before') {
429 $offset = $relativeItemKey;
430 } else {
431 $offset = $relativeItemKey + 1;
432 }
433 array_splice($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'], $offset, 0, array(0 => $item));
434 }
435 } else {
436 // Insert at new item at the end of the array if relative position was not found
437 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
438 }
439 } else {
440 // Insert at new item at the end of the array
441 $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
442 }
443 }
444
445 /**
446 * Gets the TCA configuration for a field handling (FAL) files.
447 *
448 * @param string $fieldName Name of the field to be used
449 * @param array $customSettingOverride Custom field settings overriding the basics
450 * @param string $allowedFileExtensions Comma list of allowed file extensions (e.g. "jpg,gif,pdf")
451 * @return array
452 */
453 static public function getFileFieldTCAConfig($fieldName, array $customSettingOverride = array(), $allowedFileExtensions = '', $disallowedFileExtensions = '') {
454 $fileFieldTCAConfig = array(
455 'type' => 'inline',
456 'foreign_table' => 'sys_file_reference',
457 'foreign_field' => 'uid_foreign',
458 'foreign_sortby' => 'sorting_foreign',
459 'foreign_table_field' => 'tablenames',
460 'foreign_match_fields' => array(
461 'fieldname' => $fieldName
462 ),
463 'foreign_label' => 'uid_local',
464 'foreign_selector' => 'uid_local',
465 'foreign_selector_fieldTcaOverride' => array(
466 'config' => array(
467 'appearance' => array(
468 'elementBrowserType' => 'file',
469 'elementBrowserAllowed' => $allowedFileExtensions
470 )
471 )
472 ),
473 'filter' => array(
474 array(
475 'userFunc' => 'TYPO3\\CMS\\Core\\Resource\\Filter\\FileExtensionFilter->filterInlineChildren',
476 'parameters' => array(
477 'allowedFileExtensions' => $allowedFileExtensions,
478 'disallowedFileExtensions' => $disallowedFileExtensions
479 )
480 )
481 ),
482 'appearance' => array(
483 'useSortable' => TRUE,
484 'headerThumbnail' => 'uid_local',
485 'enabledControls' => array(
486 'info' => FALSE,
487 'new' => FALSE,
488 'dragdrop' => TRUE,
489 'sort' => FALSE,
490 'hide' => TRUE,
491 'delete' => TRUE
492 )
493 )
494 );
495 return \TYPO3\CMS\Core\Utility\GeneralUtility::array_merge_recursive_overrule($fileFieldTCAConfig, $customSettingOverride);
496 }
497
498 /**
499 * Adds a list of new fields to the TYPO3 USER SETTINGS configuration "showitem" list, the array with
500 * the new fields itself needs to be added additionally to show up in the user setup, like
501 * $GLOBALS['TYPO3_USER_SETTINGS']['columns'] += $tempColumns
502 *
503 * @param string $addFields List of fields to be added to the user settings
504 * @param string $insertionPosition Insert fields before (default) or after one
505 * @return void
506 */
507 static public function addFieldsToUserSettings($addFields, $insertionPosition = '') {
508 $GLOBALS['TYPO3_USER_SETTINGS']['showitem'] = self::executePositionedStringInsertion($GLOBALS['TYPO3_USER_SETTINGS']['showitem'], $addFields, $insertionPosition);
509 }
510
511 /**
512 * Inserts as list of data into an existing list.
513 * The insertion position can be defined accordant before of after existing list items.
514 *
515 * @param string $list The list of items to be extended
516 * @param string $insertionList The list of items to inserted
517 * @param string $insertionPosition Insert fields before (default) or after one
518 * @return string The extended list
519 */
520 static protected function executePositionedStringInsertion($list, $insertionList, $insertionPosition = '') {
521 $list = trim($list);
522 $insertionList = self::removeDuplicatesForInsertion($insertionList, $list);
523 if ($insertionList) {
524 // Append data to the end (default):
525 if ($insertionPosition === '') {
526 $list .= ($list ? ', ' : '') . $insertionList;
527 } else {
528 $positions = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $insertionPosition, TRUE);
529 $items = self::explodeItemList($list);
530 $isInserted = FALSE;
531 // Iterate through all fields an check whether it's possible to inserte there:
532 foreach ($items as $item => &$itemDetails) {
533 $needles = self::getInsertionNeedles($item, $itemDetails['details']);
534 // Insert data before:
535 foreach ($needles['before'] as $needle) {
536 if (in_array($needle, $positions)) {
537 $itemDetails['rawData'] = $insertionList . ', ' . $itemDetails['rawData'];
538 $isInserted = TRUE;
539 break;
540 }
541 }
542 // Insert data after:
543 foreach ($needles['after'] as $needle) {
544 if (in_array($needle, $positions)) {
545 $itemDetails['rawData'] .= ', ' . $insertionList;
546 $isInserted = TRUE;
547 break;
548 }
549 }
550 // Replace with data:
551 foreach ($needles['replace'] as $needle) {
552 if (in_array($needle, $positions)) {
553 $itemDetails['rawData'] = $insertionList;
554 $isInserted = TRUE;
555 break;
556 }
557 }
558 // Break if insertion was already done:
559 if ($isInserted) {
560 break;
561 }
562 }
563 // If insertion point could not be determined, append the data:
564 if (!$isInserted) {
565 $list .= ($list ? ', ' : '') . $insertionList;
566 } else {
567 $list = self::generateItemList($items, TRUE);
568 }
569 }
570 }
571 return $list;
572 }
573
574 /**
575 * Compares an existing list of items and a list of items to be inserted
576 * and returns a duplicate-free variant of that insertion list.
577 *
578 * Example:
579 * + list: 'field_a, field_b;;;;2-2-2, field_c;;;;3-3-3'
580 * + insertion: 'field_b, field_d, field_c;;;4-4-4'
581 * -> new insertion: 'field_d'
582 *
583 * @param string $insertionList The list of items to inserted
584 * @param string $list The list of items to be extended (default: '')
585 * @return string Duplicate-free list of items to be inserted
586 */
587 static protected function removeDuplicatesForInsertion($insertionList, $list = '') {
588 $pattern = '/(^|,)\\s*\\b([^;,]+)\\b[^,]*/';
589 $listItems = array();
590 if ($list && preg_match_all($pattern, $list, $listMatches)) {
591 $listItems = $listMatches[2];
592 }
593 if ($insertionList && preg_match_all($pattern, $insertionList, $insertionListMatches)) {
594 $insertionItems = array();
595 $insertionDuplicates = FALSE;
596 foreach ($insertionListMatches[2] as $insertionIndex => $insertionItem) {
597 if (!isset($insertionItems[$insertionItem]) && !in_array($insertionItem, $listItems)) {
598 $insertionItems[$insertionItem] = TRUE;
599 } else {
600 unset($insertionListMatches[0][$insertionIndex]);
601 $insertionDuplicates = TRUE;
602 }
603 }
604 if ($insertionDuplicates) {
605 $insertionList = implode('', $insertionListMatches[0]);
606 }
607 }
608 return $insertionList;
609 }
610
611 /**
612 * Generates search needles that are used for inserting fields/items into an existing list.
613 *
614 * @see executePositionedStringInsertion
615 * @param string $item The name of the field/item
616 * @param array $itemDetails Additional details of the field/item like e.g. palette information
617 * @return array The needled to be used for inserting content before or after existing fields/items
618 */
619 static protected function getInsertionNeedles($item, array $itemDetails) {
620 if (strstr($item, '--')) {
621 // 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.
622 $item = preg_replace('/[0-9]+$/', '', $item);
623 }
624 $needles = array(
625 'before' => array($item, 'before:' . $item),
626 'after' => array('after:' . $item),
627 'replace' => array('replace:' . $item)
628 );
629 if ($itemDetails['palette']) {
630 $palette = $item . ';;' . $itemDetails['palette'];
631 $needles['before'][] = $palette;
632 $needles['before'][] = 'before:' . $palette;
633 $needles['after'][] = 'after:' . $palette;
634 $needles['replace'][] = 'replace:' . $palette;
635 }
636 return $needles;
637 }
638
639 /**
640 * Generates an array of fields/items with additional information such as e.g. the name of the palette.
641 *
642 * @param string $itemList List of fields/items to be splitted up
643 * @return array An array with the names of the fields/items as keys and additional information
644 */
645 static protected function explodeItemList($itemList) {
646 $items = array();
647 $itemParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $itemList, TRUE);
648 foreach ($itemParts as $itemPart) {
649 $itemDetails = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(';', $itemPart, FALSE, 5);
650 $key = $itemDetails[0];
651 if (strstr($key, '--')) {
652 // 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!
653 $key .= count($items);
654 }
655 if (!isset($items[$key])) {
656 $items[$key] = array(
657 'rawData' => $itemPart,
658 'details' => array(
659 'field' => $itemDetails[0],
660 'label' => $itemDetails[1],
661 'palette' => $itemDetails[2],
662 'special' => $itemDetails[3],
663 'styles' => $itemDetails[4]
664 )
665 );
666 }
667 }
668 return $items;
669 }
670
671 /**
672 * Generates a list of fields/items out of an array provided by the function getFieldsOfFieldList().
673 *
674 * @see explodeItemList
675 * @param array $items The array of fields/items with optional additional information
676 * @param boolean $useRawData Use raw data instead of building by using the details (default: FALSE)
677 * @return string The list of fields/items which gets used for $GLOBALS['TCA'][<table>]['types'][<type>]['showitem']
678 */
679 static protected function generateItemList(array $items, $useRawData = FALSE) {
680 $itemParts = array();
681 foreach ($items as $item => $itemDetails) {
682 if (strstr($item, '--')) {
683 // 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.
684 $item = preg_replace('/[0-9]+$/', '', $item);
685 }
686 if ($useRawData) {
687 $itemParts[] = $itemDetails['rawData'];
688 } else {
689 $itemParts[] = count($itemDetails['details']) > 1 ? implode(';', $itemDetails['details']) : $item;
690 }
691 }
692 return implode(', ', $itemParts);
693 }
694
695 /**
696 * Add tablename to default list of allowed tables on pages (in $PAGES_TYPES)
697 * Will add the $table to the list of tables allowed by default on pages as setup by $PAGES_TYPES['default']['allowedTables']
698 * FOR USE IN ext_tables.php FILES
699 *
700 * @param string $table Table name
701 * @return void
702 */
703 static public function allowTableOnStandardPages($table) {
704 $GLOBALS['PAGES_TYPES']['default']['allowedTables'] .= ',' . $table;
705 }
706
707 /**
708 * Adds a ExtJS module (main or sub) to the backend interface
709 * FOR USE IN ext_tables.php FILES
710 *
711 * @static
712 * @param string $extensionName
713 * @param string $mainModuleName Is the main module key
714 * @param string $subModuleName Is the submodule key, if blank a plain main module is generated
715 * @param string $position Passed to t3lib_extMgm::addModule, see reference there
716 * @param array $moduleConfiguration Icon with array keys: access, icon, labels to configure the module
717 * @throws \InvalidArgumentException
718 */
719 static public function addExtJSModule($extensionName, $mainModuleName, $subModuleName = '', $position = '', array $moduleConfiguration = array()) {
720 if (empty($extensionName)) {
721 throw new \InvalidArgumentException('The extension name must not be empty', 1325938973);
722 }
723 $extensionKey = \TYPO3\CMS\Core\Utility\GeneralUtility::camelCaseToLowerCaseUnderscored($extensionName);
724 $extensionName = str_replace(' ', '', ucwords(str_replace('_', ' ', $extensionName)));
725 $defaultModuleConfiguration = array(
726 'access' => 'admin',
727 'icon' => 'gfx/typo3.png',
728 'labels' => '',
729 'extRelPath' => self::extRelPath($extensionKey) . 'Classes/'
730 );
731 // Add mandatory parameter to use new pagetree
732 if ($mainModuleName === 'web') {
733 $defaultModuleConfiguration['navigationComponentId'] = 'typo3-pagetree';
734 }
735 $moduleConfiguration = \TYPO3\CMS\Core\Utility\GeneralUtility::array_merge_recursive_overrule($defaultModuleConfiguration, $moduleConfiguration);
736 if (strlen($subModuleName) > 0) {
737 $moduleSignature = $mainModuleName . '_' . $subModuleName;
738 } else {
739 $moduleSignature = $mainModuleName;
740 }
741 $moduleConfiguration['name'] = $moduleSignature;
742 $moduleConfiguration['script'] = 'extjspaneldummy.html';
743 $moduleConfiguration['extensionName'] = $extensionName;
744 $moduleConfiguration['configureModuleFunction'] = array('TYPO3\\CMS\\Core\\Extension\\ExtensionManager', 'configureModule');
745 $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature] = $moduleConfiguration;
746 self::addModule($mainModuleName, $subModuleName, $position);
747 }
748
749 /**
750 * This method is called from t3lib_loadModules::checkMod and it replaces old conf.php.
751 *
752 * The original function for is called
753 * Tx_Extbase_Utility_Extension::configureModule, the refered function can
754 * be deprecated now
755 *
756 * @param string $moduleSignature The module name
757 * @param string $modulePath Absolute path to module (not used by Extbase currently)
758 * @return array Configuration of the module
759 */
760 static public function configureModule($moduleSignature, $modulePath) {
761 $moduleConfiguration = $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature];
762 $iconPathAndFilename = $moduleConfiguration['icon'];
763 if (substr($iconPathAndFilename, 0, 4) === 'EXT:') {
764 list($extensionKey, $relativePath) = explode('/', substr($iconPathAndFilename, 4), 2);
765 $iconPathAndFilename = self::extPath($extensionKey) . $relativePath;
766 }
767 // TODO: skin support
768 $moduleLabels = array(
769 'tabs_images' => array(
770 'tab' => $iconPathAndFilename
771 ),
772 'labels' => array(
773 'tablabel' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_labels_tablabel'),
774 'tabdescr' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_labels_tabdescr')
775 ),
776 'tabs' => array(
777 'tab' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_tabs_tab')
778 )
779 );
780 $GLOBALS['LANG']->addModuleLabels($moduleLabels, $moduleSignature . '_');
781 return $moduleConfiguration;
782 }
783
784 /**
785 * Adds a module (main or sub) to the backend interface
786 * FOR USE IN ext_tables.php FILES
787 *
788 * @param string $main 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.
789 * @param string $sub The submodule key. If $sub is not set a blank $main module is created.
790 * @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.
791 * @param string $path 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.
792 * @return void
793 */
794 static public function addModule($main, $sub = '', $position = '', $path = '') {
795 if (isset($GLOBALS['TBE_MODULES'][$main]) && $sub) {
796 // If there is already a main module by this name:
797 // Adding the submodule to the correct position:
798 list($place, $modRef) = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(':', $position, 1);
799 $mods = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $GLOBALS['TBE_MODULES'][$main], 1);
800 if (!in_array($sub, $mods)) {
801 switch (strtolower($place)) {
802 case 'after':
803
804 case 'before':
805 $pointer = 0;
806 $found = FALSE;
807 foreach ($mods as $k => $m) {
808 if (!strcmp($m, $modRef)) {
809 $pointer = strtolower($place) == 'after' ? $k + 1 : $k;
810 $found = TRUE;
811 }
812 }
813 if ($found) {
814 array_splice($mods, $pointer, 0, $sub);
815 } else {
816 // If requested module is not found: Add at the end
817 array_push($mods, $sub);
818 }
819 break;
820 default:
821 if (strtolower($place) == 'top') {
822 array_unshift($mods, $sub);
823 } else {
824 array_push($mods, $sub);
825 }
826 break;
827 }
828 }
829 // Re-inserting the submodule list:
830 $GLOBALS['TBE_MODULES'][$main] = implode(',', $mods);
831 } else {
832 // Create new main modules with only one submodule, $sub (or none if $sub is blank)
833 $GLOBALS['TBE_MODULES'][$main] = $sub;
834 }
835 // Adding path:
836 if ($path) {
837 $GLOBALS['TBE_MODULES']['_PATHS'][$main . ($sub ? '_' . $sub : '')] = $path;
838 }
839 }
840
841 /**
842 * Registers an Ext.Direct component with access restrictions.
843 *
844 * @param string $endpointName
845 * @param string $callbackClass
846 * @param string $moduleName Optional: must be <mainmodule> or <mainmodule>_<submodule>
847 * @param string $accessLevel Optional: can be 'admin' or 'user,group'
848 * @return void
849 */
850 static public function registerExtDirectComponent($endpointName, $callbackClass, $moduleName = NULL, $accessLevel = NULL) {
851 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ExtDirect'][$endpointName] = array(
852 'callbackClass' => $callbackClass,
853 'moduleName' => $moduleName,
854 'accessLevel' => $accessLevel
855 );
856 }
857
858 /**
859 * Adds a module path to $GLOBALS['TBE_MODULES'] for used with the module dispatcher, mod.php
860 * Used only for modules that are not placed in the main/sub menu hierarchy by the traditional mechanism of addModule()
861 * Examples for this is context menu functionality (like import/export) which runs as an independent module through mod.php
862 * FOR USE IN ext_tables.php FILES
863 * Example: t3lib_extMgm::addModulePath('xMOD_tximpexp', t3lib_extMgm::extPath($_EXTKEY).'app/');
864 *
865 * @param string $name The name of the module, refer to conf.php of the module.
866 * @param string $path The absolute path to the module directory inside of which "index.php" and "conf.php" is found.
867 * @return void
868 */
869 static public function addModulePath($name, $path) {
870 $GLOBALS['TBE_MODULES']['_PATHS'][$name] = $path;
871 }
872
873 /**
874 * Adds a "Function menu module" ('third level module') to an existing function menu for some other backend module
875 * The arguments values are generally determined by which function menu this is supposed to interact with
876 * See Inside TYPO3 for information on how to use this function.
877 * FOR USE IN ext_tables.php FILES
878 *
879 * @param string $modname Module name
880 * @param string $className Class name
881 * @param string $classPath Class path
882 * @param string $title Title of module
883 * @param string $MM_key Menu array key - default is "function
884 * @param string $WS Workspace conditions. Blank means all workspaces, any other string can be a comma list of "online", "offline" and "custom
885 * @return void
886 * @see t3lib_SCbase::mergeExternalItems()
887 */
888 static public function insertModuleFunction($modname, $className, $classPath, $title, $MM_key = 'function', $WS = '') {
889 $GLOBALS['TBE_MODULES_EXT'][$modname]['MOD_MENU'][$MM_key][$className] = array(
890 'name' => $className,
891 'path' => $classPath,
892 'title' => $title,
893 'ws' => $WS
894 );
895 }
896
897 /**
898 * Adds some more content to a key of TYPO3_CONF_VARS array.
899 *
900 * This also tracks which content was added by extensions (in TYPO3_CONF_VARS_extensionAdded)
901 * so that they cannot be editted again through the Install Tool.
902 *
903 * @static
904 * @param string $group The group ('FE', 'BE', 'SYS' ...)
905 * @param string $key The key of this setting within the group
906 * @param string $content The text to add (include leading "\n" in case of multi-line entries)
907 * @return void
908 */
909 static public function appendToTypoConfVars($group, $key, $content) {
910 $GLOBALS['TYPO3_CONF_VARS_extensionAdded'][$group][$key] .= $content;
911 $GLOBALS['TYPO3_CONF_VARS'][$group][$key] .= $content;
912 }
913
914 /**
915 * Adds $content to the default Page TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultPageTSconfig']
916 * Prefixed with a [GLOBAL] line
917 * FOR USE IN ext_tables.php/ext_localconf.php FILES
918 *
919 * @param string $content Page TSconfig content
920 * @return void
921 */
922 static public function addPageTSConfig($content) {
923 self::appendToTypoConfVars('BE', 'defaultPageTSconfig', '
924 [GLOBAL]
925 ' . $content);
926 }
927
928 /**
929 * Adds $content to the default User TSconfig as set in $GLOBALS['TYPO3_CONF_VARS'][BE]['defaultUserTSconfig']
930 * Prefixed with a [GLOBAL] line
931 * FOR USE IN ext_tables.php/ext_localconf.php FILES
932 *
933 * @param string $content User TSconfig content
934 * @return void
935 */
936 static public function addUserTSConfig($content) {
937 self::appendToTypoConfVars('BE', 'defaultUserTSconfig', '
938 [GLOBAL]
939 ' . $content);
940 }
941
942 /**
943 * Adds a reference to a locallang file with $GLOBALS['TCA_DESCR'] labels
944 * FOR USE IN ext_tables.php FILES
945 * 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.
946 *
947 * @param string $tca_descr_key Description key. Typically a database table (like "pages") but for applications can be other strings, but prefixed with "_MOD_")
948 * @param string $file_ref File reference to locallang file, eg. "EXT:lang/locallang_csh_pages.php" (or ".xml")
949 * @return void
950 */
951 static public function addLLrefForTCAdescr($tca_descr_key, $file_ref) {
952 if ($tca_descr_key) {
953 if (!is_array($GLOBALS['TCA_DESCR'][$tca_descr_key])) {
954 $GLOBALS['TCA_DESCR'][$tca_descr_key] = array();
955 }
956 if (!is_array($GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'])) {
957 $GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'] = array();
958 }
959 $GLOBALS['TCA_DESCR'][$tca_descr_key]['refs'][] = $file_ref;
960 }
961 }
962
963 /**
964 * Registers a navigation component
965 *
966 * @param string $module
967 * @param string $componentId
968 * @return void
969 */
970 static public function addNavigationComponent($module, $componentId) {
971 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module] = array(
972 'componentId' => $componentId,
973 'extKey' => $GLOBALS['_EXTKEY'],
974 'isCoreComponent' => FALSE
975 );
976 }
977
978 /**
979 * Registers a core navigation component
980 *
981 * @param string $module
982 * @param string $componentId
983 * @return void
984 */
985 static public function addCoreNavigationComponent($module, $componentId) {
986 self::addNavigationComponent($module, $componentId);
987 $GLOBALS['TBE_MODULES']['_navigationComponents'][$module]['isCoreComponent'] = TRUE;
988 }
989
990 /**************************************
991 *
992 * Adding SERVICES features
993 *
994 ***************************************/
995 /**
996 * Adds a service to the global services array
997 *
998 * @param string $extKey Extension key
999 * @param string $serviceType Service type, must not be prefixed "tx_" or "Tx_
1000 * @param string $serviceKey Service key, must be prefixed "tx_", "Tx_" or "user_
1001 * @param array $info Service description array
1002 * @return void
1003 */
1004 static public function addService($extKey, $serviceType, $serviceKey, $info) {
1005 if ($serviceType && is_array($info)) {
1006 $info['priority'] = max(0, min(100, $info['priority']));
1007 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = $info;
1008 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['extKey'] = $extKey;
1009 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceKey'] = $serviceKey;
1010 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceType'] = $serviceType;
1011 // Change the priority (and other values) from $GLOBALS['TYPO3_CONF_VARS']
1012 // $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]['priority']
1013 // even the activation is possible (a unix service might be possible on windows for some reasons)
1014 if (is_array($GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey])) {
1015 // No check is done here - there might be configuration values only the service type knows about, so
1016 // we pass everything
1017 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey] = array_merge($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey], $GLOBALS['TYPO3_CONF_VARS']['T3_SERVICES'][$serviceType][$serviceKey]);
1018 }
1019 // OS check
1020 // Empty $os means 'not limited to one OS', therefore a check is not needed
1021 if ($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] && $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os'] != '') {
1022 // TYPO3_OS is not yet defined
1023 $os_type = stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin') ? 'WIN' : 'UNIX';
1024 $os = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', strtoupper($GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['os']));
1025 if (!in_array($os_type, $os)) {
1026 self::deactivateService($serviceType, $serviceKey);
1027 }
1028 }
1029 // Convert subtype list to array for quicker access
1030 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'] = array();
1031 $serviceSubTypes = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $info['subtype']);
1032 foreach ($serviceSubTypes as $subtype) {
1033 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['serviceSubTypes'][$subtype] = $subtype;
1034 }
1035 }
1036 }
1037
1038 /**
1039 * Find the available service with highest priority
1040 *
1041 * @param string $serviceType Service type
1042 * @param string $serviceSubType Service sub type
1043 * @param mixed $excludeServiceKeys Service keys that should be excluded in the search for a service. Array or comma list.
1044 * @return mixed Service info array if a service was found, FALSE otherwise
1045 */
1046 static public function findService($serviceType, $serviceSubType = '', $excludeServiceKeys = array()) {
1047 $serviceKey = FALSE;
1048 $serviceInfo = FALSE;
1049 $priority = 0;
1050 $quality = 0;
1051 if (!is_array($excludeServiceKeys)) {
1052 $excludeServiceKeys = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $excludeServiceKeys, 1);
1053 }
1054 if (is_array($GLOBALS['T3_SERVICES'][$serviceType])) {
1055 foreach ($GLOBALS['T3_SERVICES'][$serviceType] as $key => $info) {
1056 if (in_array($key, $excludeServiceKeys)) {
1057 continue;
1058 }
1059 // Select a subtype randomly
1060 // Useful to start a service by service key without knowing his subtypes - for testing purposes
1061 if ($serviceSubType == '*') {
1062 $serviceSubType = key($info['serviceSubTypes']);
1063 }
1064 // This matches empty subtype too
1065 if ($info['available'] && ($info['subtype'] == $serviceSubType || $info['serviceSubTypes'][$serviceSubType]) && $info['priority'] >= $priority) {
1066 // Has a lower quality than the already found, therefore we skip this service
1067 if ($info['priority'] == $priority && $info['quality'] < $quality) {
1068 continue;
1069 }
1070 // Check if the service is available
1071 $info['available'] = self::isServiceAvailable($serviceType, $key, $info);
1072 // Still available after exec check?
1073 if ($info['available']) {
1074 $serviceKey = $key;
1075 $priority = $info['priority'];
1076 $quality = $info['quality'];
1077 }
1078 }
1079 }
1080 }
1081 if ($serviceKey) {
1082 $serviceInfo = $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey];
1083 }
1084 return $serviceInfo;
1085 }
1086
1087 /**
1088 * Find a specific service identified by its key
1089 * Note that this completely bypasses the notions of priority and quality
1090 *
1091 * @param string $serviceKey Service key
1092 * @return array Service info array if a service was found
1093 * @throws \TYPO3\CMS\Core\Exception
1094 */
1095 static public function findServiceByKey($serviceKey) {
1096 if (is_array($GLOBALS['T3_SERVICES'])) {
1097 // Loop on all service types
1098 // NOTE: we don't care about the actual type, we are looking for a specific key
1099 foreach ($GLOBALS['T3_SERVICES'] as $serviceType => $servicesPerType) {
1100 if (isset($servicesPerType[$serviceKey])) {
1101 $serviceDetails = $servicesPerType[$serviceKey];
1102 // Test if service is available
1103 if (self::isServiceAvailable($serviceType, $serviceKey, $serviceDetails)) {
1104 // We have found the right service, return its information
1105 return $serviceDetails;
1106 }
1107 }
1108 }
1109 }
1110 throw new \TYPO3\CMS\Core\Exception('Service not found for key: ' . $serviceKey, 1319217244);
1111 }
1112
1113 /**
1114 * Check if a given service is available, based on the executable files it depends on
1115 *
1116 * @param string $serviceType Type of service
1117 * @param string $serviceKey Specific key of the service
1118 * @param array $serviceDetails Information about the service
1119 * @return boolean Service availability
1120 */
1121 static public function isServiceAvailable($serviceType, $serviceKey, $serviceDetails) {
1122 // If the service depends on external programs - check if they exists
1123 if (trim($serviceDetails['exec'])) {
1124 $executables = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $serviceDetails['exec'], 1);
1125 foreach ($executables as $executable) {
1126 // If at least one executable file is not available, exit early returning FALSE
1127 if (!\TYPO3\CMS\Core\Utility\CommandUtility::checkCommand($executable)) {
1128 self::deactivateService($serviceType, $serviceKey);
1129 return FALSE;
1130 }
1131 }
1132 }
1133 // The service is available
1134 return TRUE;
1135 }
1136
1137 /**
1138 * Deactivate a service
1139 *
1140 * @param string $serviceType Service type
1141 * @param string $serviceKey Service key
1142 * @return void
1143 */
1144 static public function deactivateService($serviceType, $serviceKey) {
1145 // ... maybe it's better to move non-available services to a different array??
1146 $GLOBALS['T3_SERVICES'][$serviceType][$serviceKey]['available'] = FALSE;
1147 }
1148
1149 /**************************************
1150 *
1151 * Adding FRONTEND features
1152 * (related specifically to "cms" extension)
1153 *
1154 ***************************************/
1155 /**
1156 * Adds an entry to the list of plugins in content elements of type "Insert plugin"
1157 * 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)
1158 * 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.
1159 * 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
1160 * FOR USE IN ext_tables.php FILES
1161 *
1162 * @param array $itemArray Item Array
1163 * @param string $type Type (eg. "list_type") - basically a field from "tt_content" table
1164 * @return void
1165 */
1166 static public function addPlugin($itemArray, $type = 'list_type') {
1167 $_EXTKEY = $GLOBALS['_EXTKEY'];
1168 if ($_EXTKEY && !$itemArray[2]) {
1169 $itemArray[2] = self::extRelPath($_EXTKEY) . $GLOBALS['TYPO3_LOADED_EXT'][$_EXTKEY]['ext_icon'];
1170 }
1171 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA('tt_content');
1172 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'])) {
1173 foreach ($GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'] as $k => $v) {
1174 if (!strcmp($v[1], $itemArray[1])) {
1175 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][$k] = $itemArray;
1176 return;
1177 }
1178 }
1179 $GLOBALS['TCA']['tt_content']['columns'][$type]['config']['items'][] = $itemArray;
1180 }
1181 }
1182
1183 /**
1184 * Adds an entry to the "ds" array of the tt_content field "pi_flexform".
1185 * This is used by plugins to add a flexform XML reference / content for use when they are selected as plugin or content element.
1186 *
1187 * @param string $piKeyToMatch Plugin key as used in the list_type field. Use the asterisk * to match all list_type values.
1188 * @param string $value Either a reference to a flex-form XML file (eg. "FILE:EXT:newloginbox/flexform_ds.xml") or the XML directly.
1189 * @param string $CTypeToMatch 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.
1190 * @return void
1191 * @see addPlugin()
1192 */
1193 static public function addPiFlexFormValue($piKeyToMatch, $value, $CTypeToMatch = 'list') {
1194 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA('tt_content');
1195 if (is_array($GLOBALS['TCA']['tt_content']['columns']) && is_array($GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'])) {
1196 $GLOBALS['TCA']['tt_content']['columns']['pi_flexform']['config']['ds'][$piKeyToMatch . ',' . $CTypeToMatch] = $value;
1197 }
1198 }
1199
1200 /**
1201 * Adds the $table tablename to the list of tables allowed to be includes by content element type "Insert records"
1202 * By using $content_table and $content_field you can also use the function for other tables.
1203 * FOR USE IN ext_tables.php FILES
1204 *
1205 * @param string $table Table name to allow for "insert record
1206 * @param string $content_table Table name TO WHICH the $table name is applied. See $content_field as well.
1207 * @param string $content_field Field name in the database $content_table in which $table is allowed to be added as a reference ("Insert Record")
1208 * @return void
1209 */
1210 static public function addToInsertRecords($table, $content_table = 'tt_content', $content_field = 'records') {
1211 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA($content_table);
1212 if (is_array($GLOBALS['TCA'][$content_table]['columns']) && isset($GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'])) {
1213 $GLOBALS['TCA'][$content_table]['columns'][$content_field]['config']['allowed'] .= ',' . $table;
1214 }
1215 }
1216
1217 /**
1218 * Add PlugIn to Static Template #43
1219 *
1220 * 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.
1221 * 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"
1222 * $type determines the type of frontend plugin:
1223 * "list_type" (default) - the good old "Insert plugin" entry
1224 * "menu_type" - a "Menu/Sitemap" entry
1225 * "splash_layout" - a "Textbox" entry
1226 * "CType" - a new content element type
1227 * "header_layout" - an additional header type (added to the selection of layout1-5)
1228 * "includeLib" - just includes the library for manual use somewhere in TypoScript.
1229 * (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)
1230 * FOR USE IN ext_localconf.php FILES
1231 *
1232 * @param string $key The extension key
1233 * @param string $classFile The PHP-class filename relative to the extension root directory. If set to blank a default value is chosen according to convensions.
1234 * @param string $prefix Is used as a - yes, suffix - of the class name (fx. "_pi1")
1235 * @param string $type See description above
1236 * @param boolean $cached If $cached is set as USER content object (cObject) is created - otherwise a USER_INT object is created.
1237 * @return void
1238 */
1239 static public function addPItoST43($key, $classFile = '', $prefix = '', $type = 'list_type', $cached = 0) {
1240 $classFile = $classFile ? $classFile : 'pi/class.tx_' . str_replace('_', '', $key) . $prefix . '.php';
1241 $cN = self::getCN($key);
1242 // General plugin
1243 $pluginContent = trim('
1244 plugin.' . $cN . $prefix . ' = USER' . ($cached ? '' : '_INT') . '
1245 plugin.' . $cN . $prefix . ' {
1246 includeLibs = ' . $GLOBALS['TYPO3_LOADED_EXT'][$key]['siteRelPath'] . $classFile . '
1247 userFunc = ' . $cN . $prefix . '->main
1248 }');
1249 self::addTypoScript($key, 'setup', '
1250 # Setting ' . $key . ' plugin TypoScript
1251 ' . $pluginContent);
1252 // After ST43
1253 switch ($type) {
1254 case 'list_type':
1255 $addLine = 'tt_content.list.20.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1256 break;
1257 case 'menu_type':
1258 $addLine = 'tt_content.menu.20.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1259 break;
1260 case 'splash_layout':
1261 $addLine = 'tt_content.splash.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1262 break;
1263 case 'CType':
1264 $addLine = trim('
1265 tt_content.' . $key . $prefix . ' = COA
1266 tt_content.' . $key . $prefix . ' {
1267 10 = < lib.stdheader
1268 20 = < plugin.' . $cN . $prefix . '
1269 }
1270 ');
1271 break;
1272 case 'header_layout':
1273 $addLine = 'lib.stdheader.10.' . $key . $prefix . ' = < plugin.' . $cN . $prefix;
1274 break;
1275 case 'includeLib':
1276 $addLine = 'page.1000 = < plugin.' . $cN . $prefix;
1277 break;
1278 default:
1279 $addLine = '';
1280 break;
1281 }
1282 if ($addLine) {
1283 self::addTypoScript($key, 'setup', '
1284 # Setting ' . $key . ' plugin TypoScript
1285 ' . $addLine . '
1286 ', 43);
1287 }
1288 }
1289
1290 /**
1291 * Call this method to add an entry in the static template list found in sys_templates
1292 * "static template files" are the modern equivalent (provided from extensions) to the traditional records in "static_templates"
1293 * FOR USE IN ext_localconf.php FILES
1294 *
1295 * @param string $extKey Is of course the extension key
1296 * @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, 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/
1297 * @param string $title Is the title in the selector box.
1298 * @return void
1299 * @see addTypoScript()
1300 */
1301 static public function addStaticFile($extKey, $path, $title) {
1302 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA('sys_template');
1303 if ($extKey && $path && is_array($GLOBALS['TCA']['sys_template']['columns'])) {
1304 $value = str_replace(',', '', 'EXT:' . $extKey . '/' . $path);
1305 $itemArray = array(trim($title . ' (' . $extKey . ')'), $value);
1306 $GLOBALS['TCA']['sys_template']['columns']['include_static_file']['config']['items'][] = $itemArray;
1307 }
1308 }
1309
1310 /**
1311 * Adds $content to the default TypoScript setup code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_setup']
1312 * Prefixed with a [GLOBAL] line
1313 * FOR USE IN ext_localconf.php FILES
1314 *
1315 * @param string $content TypoScript Setup string
1316 * @return void
1317 */
1318 static public function addTypoScriptSetup($content) {
1319 self::appendToTypoConfVars('FE', 'defaultTypoScript_setup', '
1320 [GLOBAL]
1321 ' . $content);
1322 }
1323
1324 /**
1325 * Adds $content to the default TypoScript constants code as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_constants']
1326 * Prefixed with a [GLOBAL] line
1327 * FOR USE IN ext_localconf.php FILES
1328 *
1329 * @param string $content TypoScript Constants string
1330 * @return void
1331 */
1332 static public function addTypoScriptConstants($content) {
1333 self::appendToTypoConfVars('FE', 'defaultTypoScript_constants', '
1334 [GLOBAL]
1335 ' . $content);
1336 }
1337
1338 /**
1339 * Adds $content to the default TypoScript code for either setup or constants as set in $GLOBALS['TYPO3_CONF_VARS'][FE]['defaultTypoScript_*']
1340 * (Basically this function can do the same as addTypoScriptSetup and addTypoScriptConstants - just with a little more hazzle, but also with some more options!)
1341 * FOR USE IN ext_localconf.php FILES
1342 *
1343 * @param string $key Is the extension key (informative only).
1344 * @param string $type Is either "setup" or "constants" and obviously determines which kind of TypoScript code we are adding.
1345 * @param string $content Is the TS content, prefixed with a [GLOBAL] line and a comment-header.
1346 * @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.
1347 * @return void
1348 */
1349 static public function addTypoScript($key, $type, $content, $afterStaticUid = 0) {
1350 if ($type == 'setup' || $type == 'constants') {
1351 $content = '
1352
1353 [GLOBAL]
1354 #############################################
1355 ## TypoScript added by extension "' . $key . '"
1356 #############################################
1357
1358 ' . $content;
1359 if ($afterStaticUid) {
1360 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.'][$afterStaticUid] .= $content;
1361 // If 'content (default)' is targeted, also add to other 'content rendering templates', eg. css_styled_content
1362 if ($afterStaticUid == 43 && is_array($GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'])) {
1363 foreach ($GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'] as $templateName) {
1364 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type . '.'][$templateName] .= $content;
1365 }
1366 }
1367 } else {
1368 $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_' . $type] .= $content;
1369 }
1370 }
1371 }
1372
1373 /***************************************
1374 *
1375 * Internal extension management methods
1376 *
1377 ***************************************/
1378 /**
1379 * Load the extension information array. This array is set as
1380 * $GLOBALS['TYPO3_LOADED_EXT'] in bootstrap. It contains basic information
1381 * about every loaded extension.
1382 *
1383 * This is an internal method. It is only used during bootstrap and
1384 * extensions should not use it!
1385 *
1386 * @param boolean $allowCaching If FALSE, the array will not be read / created from cache
1387 * @return array Result array that will be set as $GLOBALS['TYPO3_LOADED_EXT']
1388 * @access private
1389 * @see createTypo3LoadedExtensionInformationArray
1390 */
1391 static public function loadTypo3LoadedExtensionInformation($allowCaching = TRUE) {
1392 if ($allowCaching) {
1393 $cacheIdentifier = self::getTypo3LoadedExtensionInformationCacheIdentifier();
1394 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1395 $codeCache = $GLOBALS['typo3CacheManager']->getCache('cache_core');
1396 if ($codeCache->has($cacheIdentifier)) {
1397 $typo3LoadedExtensionArray = $codeCache->requireOnce($cacheIdentifier);
1398 } else {
1399 $typo3LoadedExtensionArray = self::createTypo3LoadedExtensionInformationArray();
1400 $codeCache->set($cacheIdentifier, 'return ' . var_export($typo3LoadedExtensionArray, TRUE) . ';');
1401 }
1402 } else {
1403 $typo3LoadedExtensionArray = self::createTypo3LoadedExtensionInformationArray();
1404 }
1405 return $typo3LoadedExtensionArray;
1406 }
1407
1408 /**
1409 * Set up array with basic information about loaded extension:
1410 *
1411 * array(
1412 * 'extensionKey' => array(
1413 * 'type' => Either S, L or G, inidicating if the extension is a system, a local or a global extension
1414 * 'siteRelPath' => Relative path to the extension from document root
1415 * 'typo3RelPath' => Relative path to extension from typo3/ subdirectory
1416 * 'ext_localconf.php' => Absolute path to ext_localconf.php file of extension
1417 * 'ext_...' => Further absolute path of extension files, see $extensionFilesToCheckFor var for details
1418 * ),
1419 * );
1420 *
1421 * @return array Result array that will be set as $GLOBALS['TYPO3_LOADED_EXT']
1422 */
1423 static protected function createTypo3LoadedExtensionInformationArray() {
1424 $loadedExtensions = static::getLoadedExtensionListArray();
1425 $loadedExtensionInformation = array();
1426 $extensionFilesToCheckFor = array(
1427 'ext_localconf.php',
1428 'ext_tables.php',
1429 'ext_tables.sql',
1430 'ext_tables_static+adt.sql',
1431 'ext_typoscript_constants.txt',
1432 'ext_typoscript_setup.txt'
1433 );
1434 // Clear file status cache to make sure we get good results from is_dir()
1435 clearstatcache();
1436 foreach ($loadedExtensions as $extensionKey) {
1437 // Determine if extension is installed locally, globally or system (in this order)
1438 if (@is_dir((PATH_typo3conf . 'ext/' . $extensionKey . '/'))) {
1439 // local
1440 $loadedExtensionInformation[$extensionKey] = array(
1441 'type' => 'L',
1442 'siteRelPath' => 'typo3conf/ext/' . $extensionKey . '/',
1443 'typo3RelPath' => '../typo3conf/ext/' . $extensionKey . '/'
1444 );
1445 } elseif (@is_dir((PATH_typo3 . 'ext/' . $extensionKey . '/'))) {
1446 // global
1447 $loadedExtensionInformation[$extensionKey] = array(
1448 'type' => 'G',
1449 'siteRelPath' => TYPO3_mainDir . 'ext/' . $extensionKey . '/',
1450 'typo3RelPath' => 'ext/' . $extensionKey . '/'
1451 );
1452 } elseif (@is_dir((PATH_typo3 . 'sysext/' . $extensionKey . '/'))) {
1453 // system
1454 $loadedExtensionInformation[$extensionKey] = array(
1455 'type' => 'S',
1456 'siteRelPath' => TYPO3_mainDir . 'sysext/' . $extensionKey . '/',
1457 'typo3RelPath' => 'sysext/' . $extensionKey . '/'
1458 );
1459 }
1460 // Register found files in extension array if extension was found
1461 if (isset($loadedExtensionInformation[$extensionKey])) {
1462 foreach ($extensionFilesToCheckFor as $fileName) {
1463 $absolutePathToFile = PATH_site . $loadedExtensionInformation[$extensionKey]['siteRelPath'] . $fileName;
1464 if (@is_file($absolutePathToFile)) {
1465 $loadedExtensionInformation[$extensionKey][$fileName] = $absolutePathToFile;
1466 }
1467 }
1468 }
1469 // Register found extension icon
1470 $loadedExtensionInformation[$extensionKey]['ext_icon'] = self::getExtensionIcon(PATH_site . $loadedExtensionInformation[$extensionKey]['siteRelPath']);
1471 }
1472 return $loadedExtensionInformation;
1473 }
1474
1475 /**
1476 * Find extension icon
1477 *
1478 * @param string $extensionPath Path to extension directory.
1479 * @param string $returnFullPath Return full path of file.
1480 * @return string
1481 * @throws \BadFunctionCallException
1482 */
1483 static public function getExtensionIcon($extensionPath, $returnFullPath = FALSE) {
1484 $icon = '';
1485 $iconFileTypesToCheckFor = array('png', 'gif');
1486 foreach ($iconFileTypesToCheckFor as $fileType) {
1487 if (file_exists($extensionPath . 'ext_icon.' . $fileType)) {
1488 $icon = 'ext_icon.' . $fileType;
1489 break;
1490 }
1491 }
1492 return $returnFullPath ? $extensionPath . $icon : $icon;
1493 }
1494
1495 /**
1496 * Cache identifier of cached Typo3LoadedExtensionInformation array
1497 *
1498 * @return string
1499 */
1500 static protected function getTypo3LoadedExtensionInformationCacheIdentifier() {
1501 return 'loaded_extensions_' . sha1((TYPO3_version . PATH_site . 'loadedExtensions'));
1502 }
1503
1504 /**
1505 * Execute all ext_localconf.php files of loaded extensions.
1506 * The method implements an optionally used caching mechanism that concatenates all
1507 * ext_localconf.php files in one file.
1508 *
1509 * This is an internal method. It is only used during bootstrap and
1510 * extensions should not use it!
1511 *
1512 * @param boolean $allowCaching Whether or not to load / create concatenated cache file
1513 * @return void
1514 * @access private
1515 */
1516 static public function loadExtLocalconf($allowCaching = TRUE) {
1517 if ($allowCaching) {
1518 $cacheIdentifier = self::getExtLocalconfCacheIdentifier();
1519 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1520 $codeCache = $GLOBALS['typo3CacheManager']->getCache('cache_core');
1521 if ($codeCache->has($cacheIdentifier)) {
1522 $codeCache->requireOnce($cacheIdentifier);
1523 } else {
1524 self::loadSingleExtLocalconfFiles();
1525 self::createExtLocalconfCacheEntry();
1526 }
1527 } else {
1528 self::loadSingleExtLocalconfFiles();
1529 }
1530 }
1531
1532 /**
1533 * Execute ext_localconf.php files from extensions
1534 *
1535 * @return void
1536 */
1537 static protected function loadSingleExtLocalconfFiles() {
1538 // This is the main array meant to be manipulated in the ext_localconf.php files
1539 // In general it is recommended to not rely on it to be globally defined in that
1540 // scope but to use $GLOBALS['TYPO3_CONF_VARS'] instead.
1541 // Nevertheless we define it here as global for backwards compatibility.
1542 global $TYPO3_CONF_VARS;
1543 // These globals for internal use only. Manipulating them directly is highly discouraged!
1544 // We set them here as global for backwards compatibility, but this will change in
1545 // future versions.
1546 // @deprecated since 6.0 Will be removed in two versions.
1547 global $T3_SERVICES, $T3_VAR;
1548 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1549 if (is_array($extensionInformation) && $extensionInformation['ext_localconf.php']) {
1550 // $_EXTKEY and $_EXTCONF are available in ext_localconf.php
1551 // and are explicitly set in cached file as well
1552 $_EXTCONF = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY];
1553 require $extensionInformation['ext_localconf.php'];
1554 }
1555 }
1556 }
1557
1558 /**
1559 * Create cache entry for concatenated ext_localconf.php files
1560 *
1561 * @return void
1562 */
1563 static protected function createExtLocalconfCacheEntry() {
1564 $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1565 $phpCodeToCache = array();
1566 // Set same globals as in loadSingleExtLocalconfFiles()
1567 $phpCodeToCache[] = '/**';
1568 $phpCodeToCache[] = ' * Compiled ext_localconf.php cache file';
1569 $phpCodeToCache[] = ' */';
1570 $phpCodeToCache[] = '';
1571 $phpCodeToCache[] = 'global $TYPO3_CONF_VARS, $T3_SERVICES, $T3_VAR;';
1572 $phpCodeToCache[] = '';
1573 // Iterate through loaded extensions and add ext_localconf content
1574 foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1575 // Include a header per extension to make the cache file more readable
1576 $phpCodeToCache[] = '/**';
1577 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1578 $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_localconf.php'];
1579 $phpCodeToCache[] = ' */';
1580 $phpCodeToCache[] = '';
1581 // Set $_EXTKEY and $_EXTCONF for this extension
1582 $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1583 $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY];';
1584 $phpCodeToCache[] = '';
1585 // Add ext_localconf.php content of extension
1586 $phpCodeToCache[] = trim(\TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($extensionDetails['ext_localconf.php']));
1587 $phpCodeToCache[] = '';
1588 $phpCodeToCache[] = '';
1589 }
1590 $phpCodeToCache = implode(LF, $phpCodeToCache);
1591 // Remove all start and ending php tags from content
1592 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1593 $GLOBALS['typo3CacheManager']->getCache('cache_core')->set(self::getExtLocalconfCacheIdentifier(), $phpCodeToCache);
1594 }
1595
1596 /**
1597 * Cache identifier of concatenated ext_localconf file
1598 *
1599 * @return string
1600 */
1601 static protected function getExtLocalconfCacheIdentifier() {
1602 return 'ext_localconf_' . sha1((TYPO3_version . PATH_site . 'extLocalconf'));
1603 }
1604
1605 /**
1606 * Execute all ext_tables.php files of loaded extensions.
1607 * The method implements an optionally used caching mechanism that concatenates all
1608 * ext_tables.php files in one file.
1609 *
1610 * This is an internal method. It is only used during bootstrap and
1611 * extensions should not use it!
1612 *
1613 * @param boolean $allowCaching Whether to load / create concatenated cache file
1614 * @return void
1615 * @access private
1616 */
1617 static public function loadExtTables($allowCaching = TRUE) {
1618 if ($allowCaching && !self::$extTablesWasReadFromCacheOnce) {
1619 self::$extTablesWasReadFromCacheOnce = TRUE;
1620 $cacheIdentifier = self::getExtTablesCacheIdentifier();
1621 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1622 $codeCache = $GLOBALS['typo3CacheManager']->getCache('cache_core');
1623 if ($codeCache->has($cacheIdentifier)) {
1624 $codeCache->requireOnce($cacheIdentifier);
1625 } else {
1626 self::loadSingleExtTablesFiles();
1627 self::createExtTablesCacheEntry();
1628 }
1629 } else {
1630 self::loadSingleExtTablesFiles();
1631 }
1632 }
1633
1634 /**
1635 * Load ext_tables.php as single files
1636 *
1637 * @return void
1638 */
1639 static protected function loadSingleExtTablesFiles() {
1640 // In general it is recommended to not rely on it to be globally defined in that
1641 // scope, but we can not prohibit this without breaking backwards compatibility
1642 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
1643 global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;
1644 global $PAGES_TYPES, $TBE_STYLES, $FILEICONS;
1645 global $_EXTKEY;
1646 // Load each ext_tables.php file of loaded extensions
1647 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $_EXTKEY => $extensionInformation) {
1648 if (is_array($extensionInformation) && $extensionInformation['ext_tables.php']) {
1649 // $_EXTKEY and $_EXTCONF are available in ext_tables.php
1650 // and are explicitly set in cached file as well
1651 $_EXTCONF = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$_EXTKEY];
1652 require $extensionInformation['ext_tables.php'];
1653 }
1654 }
1655 }
1656
1657 /**
1658 * Create concatenated ext_tables.php cache file
1659 *
1660 * @return void
1661 */
1662 static protected function createExtTablesCacheEntry() {
1663 $extensionInformation = $GLOBALS['TYPO3_LOADED_EXT'];
1664 $phpCodeToCache = array();
1665 // Set same globals as in loadSingleExtTablesFiles()
1666 $phpCodeToCache[] = '/**';
1667 $phpCodeToCache[] = ' * Compiled ext_tables.php cache file';
1668 $phpCodeToCache[] = ' */';
1669 $phpCodeToCache[] = '';
1670 $phpCodeToCache[] = 'global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;';
1671 $phpCodeToCache[] = 'global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;';
1672 $phpCodeToCache[] = 'global $PAGES_TYPES, $TBE_STYLES, $FILEICONS;';
1673 $phpCodeToCache[] = 'global $_EXTKEY;';
1674 $phpCodeToCache[] = '';
1675 // Iterate through loaded extensions and add ext_tables content
1676 foreach ($extensionInformation as $extensionKey => $extensionDetails) {
1677 // Include a header per extension to make the cache file more readable
1678 $phpCodeToCache[] = '/**';
1679 $phpCodeToCache[] = ' * Extension: ' . $extensionKey;
1680 $phpCodeToCache[] = ' * File: ' . $extensionDetails['ext_tables.php'];
1681 $phpCodeToCache[] = ' */';
1682 $phpCodeToCache[] = '';
1683 // Set $_EXTKEY and $_EXTCONF for this extension
1684 $phpCodeToCache[] = '$_EXTKEY = \'' . $extensionKey . '\';';
1685 $phpCodeToCache[] = '$_EXTCONF = $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXT\'][\'extConf\'][$_EXTKEY];';
1686 $phpCodeToCache[] = '';
1687 // Add ext_tables.php content of extension
1688 $phpCodeToCache[] = trim(\TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($extensionDetails['ext_tables.php']));
1689 $phpCodeToCache[] = '';
1690 $phpCodeToCache[] = '';
1691 }
1692 $phpCodeToCache = implode(LF, $phpCodeToCache);
1693 // Remove all start and ending php tags from content
1694 $phpCodeToCache = preg_replace('/<\\?php|\\?>/is', '', $phpCodeToCache);
1695 $GLOBALS['typo3CacheManager']->getCache('cache_core')->set(self::getExtTablesCacheIdentifier(), $phpCodeToCache);
1696 }
1697
1698 /**
1699 * Cache identifier for concatenated ext_tables.php files
1700 *
1701 * @return string
1702 */
1703 static protected function getExtTablesCacheIdentifier() {
1704 return 'ext_tables_' . sha1((TYPO3_version . PATH_site . 'extTables'));
1705 }
1706
1707 /**
1708 * Loading extensions configured in $GLOBALS['TYPO3_CONF_VARS']['EXT']['extListArray']
1709 *
1710 * Usages of this function can be seen in bootstrap
1711 * Extensions are always detected in the order local - global - system.
1712 *
1713 * @return array Extension Array
1714 * @internal
1715 * @deprecated since 6.0, will be removed in two versions
1716 */
1717 static public function typo3_loadExtensions() {
1718 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1719 return self::loadTypo3LoadedExtensionInformation(TRUE);
1720 }
1721
1722 /**
1723 * Returns the section headers for the compiled cache-files.
1724 *
1725 * @param string $key Is the extension key
1726 * @param string $file Is the filename (only informative for comment)
1727 * @return string
1728 * @internal
1729 * @deprecated since 6.0, will be removed in two versions
1730 */
1731 static public function _makeIncludeHeader($key, $file) {
1732 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1733 return '';
1734 }
1735
1736 /**
1737 * Returns TRUE if both the localconf and tables cache file exists
1738 * (with $cacheFilePrefix) and if they are not empty
1739 *
1740 * @param $cacheFilePrefix string Prefix of the cache file to check
1741 * @return boolean
1742 * @deprecated since 6.0, will be removed in two versions
1743 */
1744 static public function isCacheFilesAvailable($cacheFilePrefix) {
1745 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1746 return FALSE;
1747 }
1748
1749 /**
1750 * Returns TRUE if configuration files in typo3conf/ are writable
1751 *
1752 * @return boolean TRUE if at least one configuration file in typo3conf/ is writable
1753 * @internal
1754 */
1755 static public function isLocalconfWritable() {
1756 $result = TRUE;
1757 if (!@is_writable(PATH_typo3conf)) {
1758 $result = FALSE;
1759 }
1760 if (!@is_writable((PATH_site . \TYPO3\CMS\Core\Configuration\ConfigurationManager::LOCALCONF_FILE)) && !@is_writable((PATH_site . \TYPO3\CMS\Core\Configuration\ConfigurationManager::LOCAL_CONFIGURATION_FILE))) {
1761 $result = FALSE;
1762 }
1763 return $result;
1764 }
1765
1766 /**
1767 * Returns an error string if typo3conf/ or cache-files with $cacheFilePrefix are NOT writable
1768 * Returns FALSE if no problem.
1769 *
1770 * @param string $cacheFilePrefix Prefix of the cache file to check
1771 * @return string
1772 * @internal
1773 * @deprecated since 6.0, will be removed in two versions
1774 */
1775 static public function cannotCacheFilesWritable($cacheFilePrefix) {
1776 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1777 return '';
1778 }
1779
1780 /**
1781 * Returns an array with the two cache-files (0=>localconf, 1=>tables)
1782 * from typo3conf/ if they (both) exist. Otherwise FALSE.
1783 * Evaluation relies on $GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE']
1784 *
1785 * @param string $cacheFilePrefix Cache file prefix to be used (optional)
1786 * @return array
1787 * @internal
1788 * @deprecated since 6.0, will be removed in versions
1789 */
1790 static public function currentCacheFiles($cacheFilePrefix = NULL) {
1791 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1792 return array();
1793 }
1794
1795 /**
1796 * Compiles/Creates the two cache-files in typo3conf/ based on $cacheFilePrefix
1797 * Returns a array with the key "_CACHEFILE" set to the $cacheFilePrefix value
1798 *
1799 * @param array $extensions Extension information array
1800 * @param string $cacheFilePrefix Prefix for the cache files
1801 * @return array
1802 * @internal
1803 * @deprecated since 6.0, will be removed in two versions
1804 */
1805 static public function writeCacheFiles($extensions, $cacheFilePrefix) {
1806 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1807 return array();
1808 }
1809
1810 /**
1811 * Remove cache files from php code cache, tagged with 'core'
1812 *
1813 * This removes the following cache entries:
1814 * - autoloader cache registry
1815 * - cache loaded extension array
1816 * - ext_localconf concatenation
1817 * - ext_tables concatenation
1818 *
1819 * This method is usually only used by extension that fiddle
1820 * with the loaded extensions. An example is the extension
1821 * manager and the install tool.
1822 *
1823 * @return void
1824 */
1825 static public function removeCacheFiles() {
1826 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1827 $codeCache = $GLOBALS['typo3CacheManager']->getCache('cache_core');
1828 $codeCache->flush();
1829 }
1830
1831 /**
1832 * Gets the behaviour for caching ext_tables.php and ext_localconf.php files
1833 * (see $GLOBALS['TYPO3_CONF_VARS']['EXT']['extCache'] setting in the install tool).
1834 *
1835 * @param boolean $usePlainValue Whether to use the value as it is without modifications
1836 * @return integer
1837 * @deprecated since 6.0, will be removed two versions later
1838 */
1839 static public function getExtensionCacheBehaviour($usePlainValue = FALSE) {
1840 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1841 return 1;
1842 }
1843
1844 /**
1845 * Gets the prefix used for the ext_tables.php and ext_localconf.php cached files.
1846 *
1847 * @return string
1848 * @deprecated since 6.0, will be removed two versions later
1849 */
1850 static public function getCacheFilePrefix() {
1851 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1852 }
1853
1854 /**
1855 * Gets the list of enabled extensions
1856 *
1857 * @return string
1858 * @deprecated since 6.0, will be removed two versions later
1859 */
1860 static public function getEnabledExtensionList() {
1861 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1862 return implode(',', self::getLoadedExtensionListArray());
1863 }
1864
1865 /**
1866 * Gets the list of required extensions.
1867 *
1868 * @return string
1869 * @deprecated since 6.0, will be removed two versions later
1870 */
1871 static public function getRequiredExtensionList() {
1872 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1873 return implode(',', self::getRequiredExtensionListArray());
1874 }
1875
1876 /**
1877 * Get list of extensions to be ignored (not to be loaded).
1878 *
1879 * @return string
1880 * @deprecated since 6.0, will be removed two versions later
1881 */
1882 static public function getIgnoredExtensionList() {
1883 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
1884 return '';
1885 }
1886
1887 /**
1888 * Gets an array of loaded extension keys
1889 *
1890 * @return array Loaded extensions
1891 */
1892 static public function getLoadedExtensionListArray() {
1893 // Extensions in extListArray
1894 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXT']['extListArray'])) {
1895 $loadedExtensions = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extListArray'];
1896 } else {
1897 // Fallback handling if extlist is still a string and not an array
1898 $loadedExtensions = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['EXT']['extList']);
1899 }
1900 // Add required extensions
1901 $loadedExtensions = array_merge(static::getRequiredExtensionListArray(), $loadedExtensions);
1902 $loadedExtensions = array_unique($loadedExtensions);
1903 return $loadedExtensions;
1904 }
1905
1906 /**
1907 * Gets list of required extensions.
1908 * This is the list of extensions from constant REQUIRED_EXTENSIONS defined
1909 * in bootstrap, together with a possible additional list of extensions from
1910 * local configuration
1911 *
1912 * @return array List of required extensions
1913 */
1914 static public function getRequiredExtensionListArray() {
1915 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXT']['requiredExt'])) {
1916 $requiredExtensions = $GLOBALS['TYPO3_CONF_VARS']['EXT']['requiredExt'];
1917 } else {
1918 $requiredExtensions = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['EXT']['requiredExt']);
1919 }
1920 $requiredExtensions = array_merge(\TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', REQUIRED_EXTENSIONS), $requiredExtensions);
1921 $requiredExtensions = array_unique($requiredExtensions);
1922 return $requiredExtensions;
1923 }
1924
1925 /**
1926 * Loads given extension
1927 *
1928 * Warning: This method only works if the ugrade wizard to transform
1929 * localconf.php to LocalConfiguration.php was already run
1930 *
1931 * @param string $extensionKey Extension key to load
1932 * @return void
1933 * @throws \RuntimeException
1934 */
1935 static public function loadExtension($extensionKey) {
1936 if (static::isLoaded($extensionKey)) {
1937 throw new \RuntimeException('Extension already loaded', 1342345486);
1938 }
1939 $extList = \TYPO3\CMS\Core\Configuration\ConfigurationManager::getLocalConfigurationValueByPath('EXT/extListArray');
1940 $extList[] = $extensionKey;
1941 static::writeNewExtensionList($extList);
1942 }
1943
1944 /**
1945 * Unloads given extension
1946 *
1947 * Warning: This method only works if the ugrade wizard to transform
1948 * localconf.php to LocalConfiguration.php was already run
1949 *
1950 * @param string $extensionKey Extension key to remove
1951 * @return void
1952 * @throws \RuntimeException
1953 */
1954 static public function unloadExtension($extensionKey) {
1955 if (!static::isLoaded($extensionKey)) {
1956 throw new \RuntimeException('Extension not loaded', 1342345487);
1957 }
1958 if (in_array($extensionKey, static::getRequiredExtensionListArray())) {
1959 throw new \RuntimeException('Can not unload required extension', 1342348167);
1960 }
1961 $extList = \TYPO3\CMS\Core\Configuration\ConfigurationManager::getLocalConfigurationValueByPath('EXT/extListArray');
1962 $extList = array_diff($extList, array($extensionKey));
1963 static::writeNewExtensionList($extList);
1964 }
1965
1966 /**
1967 * Writes extension list and clear cache files.
1968 *
1969 * @TODO : This method should be protected, but with current em it is hard to do so,
1970 * @param array Extension array to load, loader order is kept
1971 * @return void
1972 * @internal
1973 */
1974 static public function writeNewExtensionList(array $newExtensionList) {
1975 $extensionList = array_unique($newExtensionList);
1976 \TYPO3\CMS\Core\Configuration\ConfigurationManager::setLocalConfigurationValueByPath('EXT/extListArray', $extensionList);
1977 // @deprecated: extList as string is deprecated, the handling will be removed with 6.2
1978 // For now, this value is still set for better backwards compatibility
1979 \TYPO3\CMS\Core\Configuration\ConfigurationManager::setLocalConfigurationValueByPath('EXT/extList', implode(',', $extensionList));
1980 static::removeCacheFiles();
1981 }
1982
1983 /**
1984 * Makes a table categorizable by extending its TCA.
1985 *
1986 * @param string $extensionKey Extension key to be used
1987 * @param string $tableName Name of the table to be categoriezed
1988 * @param string $fieldName Name of the field to be used to store categories
1989 * @param array $options Additional configuration options
1990 * @see addTCAcolumns
1991 * @see addToAllTCAtypes
1992 */
1993 static public function makeCategorizable($extensionKey, $tableName, $fieldName = 'categories', array $options = array()) {
1994 // Load TCA first
1995 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA($tableName);
1996 // Update the category registry
1997 $result = \TYPO3\CMS\Core\Category\CategoryRegistry::getInstance()->add($extensionKey, $tableName, $fieldName);
1998 if ($result === FALSE) {
1999 $message = 't3lib_categoryRegistry: no category registered for table "%s". Double check if there is a TCA configured';
2000 \TYPO3\CMS\Core\Utility\GeneralUtility::devLog(sprintf($message, $tableName), 'Core', 2);
2001 }
2002 // Makes sure to add more TCA to an existing structure
2003 if (isset($GLOBALS['TCA'][$tableName]['columns'])) {
2004 // Forges a new field, default name is "categories"
2005 $fieldConfiguration = array(
2006 'type' => 'select',
2007 'foreign_table' => 'sys_category',
2008 'foreign_table_where' => ' ORDER BY sys_category.title ASC',
2009 'MM' => 'sys_category_record_mm',
2010 'MM_opposite_field' => 'items',
2011 'MM_match_fields' => array('tablenames' => $tableName),
2012 'size' => 10,
2013 'autoSizeMax' => 50,
2014 'maxitems' => 9999,
2015 'renderMode' => 'tree',
2016 'treeConfig' => array(
2017 'parentField' => 'parent',
2018 'appearance' => array(
2019 'expandAll' => TRUE,
2020 'showHeader' => TRUE
2021 )
2022 ),
2023 'wizards' => array(
2024 '_PADDING' => 1,
2025 '_VERTICAL' => 1,
2026 'edit' => array(
2027 'type' => 'popup',
2028 'title' => 'Edit',
2029 'script' => 'wizard_edit.php',
2030 'icon' => 'edit2.gif',
2031 'popup_onlyOpenIfSelected' => 1,
2032 'JSopenParams' => 'height=350,width=580,status=0,menubar=0,scrollbars=1'
2033 ),
2034 'add' => array(
2035 'type' => 'script',
2036 'title' => 'Create new',
2037 'icon' => 'add.gif',
2038 'params' => array(
2039 'table' => 'sys_category',
2040 'pid' => '###CURRENT_PID###',
2041 'setValue' => 'prepend'
2042 ),
2043 'script' => 'wizard_add.php'
2044 )
2045 )
2046 );
2047 if (!empty($options['fieldConfiguration'])) {
2048 $fieldConfiguration = \TYPO3\CMS\Core\Utility\GeneralUtility::array_merge_recursive_overrule($fieldConfiguration, $options['fieldConfiguration']);
2049 }
2050 $columns = array(
2051 $fieldName => array(
2052 'exclude' => 0,
2053 'label' => 'LLL:EXT:lang/locallang_tca.xlf:sys_category.categories',
2054 'config' => $fieldConfiguration
2055 )
2056 );
2057 // Adding fields to an existing table definition
2058 self::addTCAcolumns($tableName, $columns);
2059 $fieldList = '--div--;LLL:EXT:lang/locallang_tca.xlf:sys_category.tabs.category, ' . $fieldName;
2060 if (!empty($options['fieldList'])) {
2061 $fieldList = $options['fieldList'];
2062 }
2063 $typesList = '';
2064 if (!empty($options['typesList'])) {
2065 $typesList = $options['typesList'];
2066 }
2067 $position = '';
2068 if (!empty($options['position'])) {
2069 $position = $options['position'];
2070 }
2071 // Makes the new "categories" field to be visible in TSFE.
2072 self::addToAllTCAtypes($tableName, $fieldList, $typesList, $position);
2073 }
2074 }
2075
2076 }
2077
2078
2079 ?>