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