/
ExtensionManagementUtility.php
2044 lines (1943 loc) · 92.2 KB
/
ExtensionManagementUtility.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace TYPO3\CMS\Core\Utility;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Core\Category\CategoryRegistry;
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Imaging\IconProvider\BitmapIconProvider;
use TYPO3\CMS\Core\Imaging\IconRegistry;
use TYPO3\CMS\Core\Migrations\TcaMigration;
use TYPO3\CMS\Core\Package\PackageManager;
/**
* Extension Management functions
*
* This class is never instantiated, rather the methods inside is called as functions like
* \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('my_extension');
*/
class ExtensionManagementUtility
{
/**
* @var array
*/
protected static $extensionKeyMap;
/**
* TRUE, if ext_tables file was read from cache for this script run.
* The frontend tends to do that multiple times, but the caching framework does
* not allow this (via a require_once call). This variable is used to track
* the access to the cache file to read the single ext_tables.php if it was
* already read from cache
*
* @todo See if we can get rid of the 'load multiple times' scenario in fe
* @var bool
*/
protected static $extTablesWasReadFromCacheOnce = false;
/**
* @var PackageManager
*/
protected static $packageManager;
/**
* Sets the package manager for all that backwards compatibility stuff,
* so it doesn't have to be fetched through the bootstap.
*
* @param PackageManager $packageManager
* @internal
*/
public static function setPackageManager(PackageManager $packageManager)
{
static::$packageManager = $packageManager;
}
/**
* @var \TYPO3\CMS\Core\Cache\CacheManager
*/
protected static $cacheManager;
/**
* Getter for the cache manager
*
* @return \TYPO3\CMS\Core\Cache\CacheManager
*/
protected static function getCacheManager()
{
if (static::$cacheManager === null) {
static::$cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
}
return static::$cacheManager;
}
/**
* @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
*/
protected static $signalSlotDispatcher;
/**
* Getter for the signal slot dispatcher
*
* @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
*/
protected static function getSignalSlotDispatcher()
{
if (static::$signalSlotDispatcher === null) {
static::$signalSlotDispatcher = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class);
}
return static::$signalSlotDispatcher;
}
/**************************************
*
* PATHS and other evaluation
*
***************************************/
/**
* Returns TRUE if the extension with extension key $key is loaded.
*
* @param string $key Extension key to test
* @param bool $exitOnError If $exitOnError is TRUE and the extension is not loaded the function will die with an error message
* @return bool
* @throws \BadFunctionCallException
*/
public static function isLoaded($key, $exitOnError = false)
{
$isLoaded = static::$packageManager->isPackageActive($key);
if ($exitOnError && !$isLoaded) {
throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension "' . $key . '" is not loaded!', 1270853910);
}
return $isLoaded;
}
/**
* Returns the absolute path to the extension with extension key $key.
*
* @param $key string Extension key
* @param $script string $script is appended to the output if set.
* @throws \BadFunctionCallException
* @return string
*/
public static function extPath($key, $script = '')
{
if (!static::$packageManager->isPackageActive($key)) {
throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension key "' . $key . '" is NOT loaded!', 1365429656);
}
return static::$packageManager->getPackage($key)->getPackagePath() . $script;
}
/**
* Returns the relative path to the extension as measured from from the TYPO3_mainDir
* If the extension is not loaded the function will die with an error message
* Useful for images and links from backend
*
* @param string $key Extension key
*
* @throws \BadFunctionCallException
* @return string
*/
public static function extRelPath($key)
{
if (!static::$packageManager->isPackageActive($key)) {
throw new \BadFunctionCallException('TYPO3 Fatal Error: Extension key "' . $key . '" is NOT loaded!', 1365429673);
}
$relativePathToSiteRoot = self::siteRelPath($key);
$typo3MainDirLength = strlen(TYPO3_mainDir);
if (substr($relativePathToSiteRoot, 0, $typo3MainDirLength) === TYPO3_mainDir) {
$relativePathToSiteRoot = substr($relativePathToSiteRoot, $typo3MainDirLength);
} else {
$relativePathToSiteRoot = '../' . $relativePathToSiteRoot;
}
return $relativePathToSiteRoot;
}
/**
* Returns the relative path to the extension as measured from the PATH_site (frontend)
* If the extension is not loaded the function will die with an error message
* Useful for images and links from the frontend
*
* @param string $key Extension key
* @return string
*/
public static function siteRelPath($key)
{
return PathUtility::stripPathSitePrefix(self::extPath($key));
}
/**
* Returns the correct class name prefix for the extension key $key
*
* @param string $key Extension key
* @return string
* @internal
*/
public static function getCN($key)
{
return strpos($key, 'user_') === 0 ? 'user_' . str_replace('_', '', substr($key, 5)) : 'tx_' . str_replace('_', '', $key);
}
/**
* Returns the real extension key like 'tt_news' from an extension prefix like 'tx_ttnews'.
*
* @param string $prefix The extension prefix (e.g. 'tx_ttnews')
* @return mixed Real extension key (string)or FALSE (bool) if something went wrong
*/
public static function getExtensionKeyByPrefix($prefix)
{
$result = false;
// Build map of short keys referencing to real keys:
if (!isset(self::$extensionKeyMap)) {
self::$extensionKeyMap = array();
foreach (static::$packageManager->getActivePackages() as $package) {
$shortKey = str_replace('_', '', $package->getPackageKey());
self::$extensionKeyMap[$shortKey] = $package->getPackageKey();
}
}
// Lookup by the given short key:
$parts = explode('_', $prefix);
if (isset(self::$extensionKeyMap[$parts[1]])) {
$result = self::$extensionKeyMap[$parts[1]];
}
return $result;
}
/**
* Clears the extension key map.
*
* @return void
*/
public static function clearExtensionKeyMap()
{
self::$extensionKeyMap = null;
}
/**
* Retrieves the version of an installed extension.
* If the extension is not installed, this function returns an empty string.
*
* @param string $key The key of the extension to look up, must not be empty
*
* @throws \InvalidArgumentException
* @throws \TYPO3\CMS\Core\Package\Exception
* @return string The extension version as a string in the format "x.y.z",
*/
public static function getExtensionVersion($key)
{
if (!is_string($key) || empty($key)) {
throw new \InvalidArgumentException('Extension key must be a non-empty string.', 1294586096);
}
if (!static::isLoaded($key)) {
return '';
}
$version = static::$packageManager->getPackage($key)->getPackageMetaData()->getVersion();
if (empty($version)) {
throw new \TYPO3\CMS\Core\Package\Exception('Version number in composer manifest of package "' . $key . '" is missing or invalid', 1395614959);
}
return $version;
}
/**************************************
*
* Adding BACKEND features
* (related to core features)
*
***************************************/
/**
* Adding fields to an existing table definition in $GLOBALS['TCA']
* Adds an array with $GLOBALS['TCA'] column-configuration to the $GLOBALS['TCA']-entry for that table.
* 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!
* So to have the fields displayed you must also call fx. addToAllTCAtypes or manually add the fields to the types list.
* FOR USE IN ext_tables.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
*
* @param string $table The table name of a table already present in $GLOBALS['TCA'] with a columns section
* @param array $columnArray The array with the additional columns (typical some fields an extension wants to add)
* @return void
*/
public static function addTCAcolumns($table, $columnArray)
{
if (is_array($columnArray) && is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'])) {
// Candidate for array_merge() if integer-keys will some day make trouble...
$GLOBALS['TCA'][$table]['columns'] = array_merge($GLOBALS['TCA'][$table]['columns'], $columnArray);
}
}
/**
* Makes fields visible in the TCEforms, adding them to the end of (all) "types"-configurations
*
* Adds a string $string (comma separated list of field names) to all ["types"][xxx]["showitem"] entries for table $table (unless limited by $typeList)
* This is needed to have new fields shown automatically in the TCEFORMS of a record from $table.
* Typically this function is called after having added new columns (database fields) with the addTCAcolumns function
* FOR USE IN ext_tables.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
*
* @param string $table Table name
* @param string $newFieldsString Field list to add.
* @param string $typeList List of specific types to add the field list to. (If empty, all type entries are affected)
* @param string $position Insert fields before (default) or after one, or replace a field
* @return void
*/
public static function addToAllTCAtypes($table, $newFieldsString, $typeList = '', $position = '')
{
$newFieldsString = trim($newFieldsString);
if ($newFieldsString === '' || !is_array($GLOBALS['TCA'][$table]['types'])) {
return;
}
list($positionIdentifier, $entityName) = GeneralUtility::trimExplode(':', $position);
$palettesChanged = array();
foreach ($GLOBALS['TCA'][$table]['types'] as $type => &$typeDetails) {
// skip if we don't want to add the field for this type
if ($typeList !== '' && !GeneralUtility::inList($typeList, $type)) {
continue;
}
// skip if fields were already added
if (!isset($typeDetails['showitem']) || strpos($typeDetails['showitem'], $newFieldsString) !== false) {
continue;
}
$fieldExists = false;
$newPosition = '';
if (is_array($GLOBALS['TCA'][$table]['palettes'])) {
// Get the palette names used in current showitem
$paletteCount = preg_match_all('/(?:^|,) # Line start or a comma
(?:
\\s*\\-\\-palette\\-\\-;[^;]*;([^,$]*)| # --palette--;label;paletteName
\\s*\\b[^;,]+\\b(?:;[^;]*;([^;,]+))?[^,]* # field;label;paletteName
)/x', $typeDetails['showitem'], $paletteMatches);
if ($paletteCount > 0) {
$paletteNames = array_filter(array_merge($paletteMatches[1], $paletteMatches[2]));
if (!empty($paletteNames)) {
foreach ($paletteNames as $paletteName) {
$palette = $GLOBALS['TCA'][$table]['palettes'][$paletteName];
switch ($positionIdentifier) {
case 'after':
case 'before':
if (preg_match('/\\b' . $entityName . '\\b/', $palette['showitem']) > 0) {
$newPosition = $positionIdentifier . ':--palette--;;' . $paletteName;
}
break;
case 'replace':
// check if fields have been added to palette before
if (isset($palettesChanged[$paletteName])) {
$fieldExists = true;
continue;
}
if (preg_match('/\\b' . $entityName . '\\b/', $palette['showitem']) > 0) {
self::addFieldsToPalette($table, $paletteName, $newFieldsString, $position);
// Memorize that we already changed this palette, in case other types also use it
$palettesChanged[$paletteName] = true;
$fieldExists = true;
continue;
}
break;
default:
// Intentionally left blank
}
}
}
}
}
if ($fieldExists === false) {
$typeDetails['showitem'] = self::executePositionedStringInsertion(
$typeDetails['showitem'],
$newFieldsString,
$newPosition !== '' ? $newPosition : $position
);
}
}
unset($typeDetails);
}
/**
* Adds new fields to all palettes that is defined after an existing field.
* If the field does not have a following palette yet, it's created automatically
* and gets called "generatedFor-$field".
*
* See unit tests for more examples and edge cases.
*
* Example:
*
* 'aTable' => array(
* 'types' => array(
* 'aType' => array(
* 'showitem' => 'aField, --palette--;;aPalette',
* ),
* ),
* 'palettes' => array(
* 'aPallete' => array(
* 'showitem' => 'fieldB, fieldC',
* ),
* ),
* ),
*
* Calling addFieldsToAllPalettesOfField('aTable', 'aField', 'newA', 'before: fieldC') results in:
*
* 'aTable' => array(
* 'types' => array(
* 'aType' => array(
* 'showitem' => 'aField, --palette--;;aPalette',
* ),
* ),
* 'palettes' => array(
* 'aPallete' => array(
* 'showitem' => 'fieldB, newA, fieldC',
* ),
* ),
* ),
*
* @param string $table Name of the table
* @param string $field Name of the field that has the palette to be extended
* @param string $addFields List of fields to be added to the palette
* @param string $insertionPosition Insert fields before (default) or after one
* @return void
*/
public static function addFieldsToAllPalettesOfField($table, $field, $addFields, $insertionPosition = '')
{
if (!isset($GLOBALS['TCA'][$table]['columns'][$field])) {
return;
}
if (!is_array($GLOBALS['TCA'][$table]['types'])) {
return;
}
// Iterate through all types and search for the field that defines the palette to be extended
foreach ($GLOBALS['TCA'][$table]['types'] as $typeName => $typeArray) {
// Continue if types has no showitem at all or if requested field is not in it
if (!isset($typeArray['showitem']) || strpos($typeArray['showitem'], $field) === false) {
continue;
}
$fieldArrayWithOptions = GeneralUtility::trimExplode(',', $typeArray['showitem']);
// Find the field we're handling
$newFieldStringArray = array();
foreach ($fieldArrayWithOptions as $fieldNumber => $fieldString) {
$newFieldStringArray[] = $fieldString;
$fieldArray = GeneralUtility::trimExplode(';', $fieldString);
if ($fieldArray[0] !== $field) {
continue;
}
if (
isset($fieldArrayWithOptions[$fieldNumber + 1])
&& StringUtility::beginsWith($fieldArrayWithOptions[$fieldNumber + 1], '--palette--')
) {
// Match for $field and next field is a palette - add fields to this one
$paletteName = GeneralUtility::trimExplode(';', $fieldArrayWithOptions[$fieldNumber + 1]);
$paletteName = $paletteName[2];
self::addFieldsToPalette($table, $paletteName, $addFields, $insertionPosition);
} else {
// Match for $field but next field is no palette - create a new one
$newPaletteName = 'generatedFor-' . $field;
self::addFieldsToPalette($table, 'generatedFor-' . $field, $addFields, $insertionPosition);
$newFieldStringArray[] = '--palette--;;' . $newPaletteName;
}
}
$GLOBALS['TCA'][$table]['types'][$typeName]['showitem'] = implode(', ', $newFieldStringArray);
}
}
/**
* Adds new fields to a palette.
* If the palette does not exist yet, it's created automatically.
*
* @param string $table Name of the table
* @param string $palette Name of the palette to be extended
* @param string $addFields List of fields to be added to the palette
* @param string $insertionPosition Insert fields before (default) or after one
* @return void
*/
public static function addFieldsToPalette($table, $palette, $addFields, $insertionPosition = '')
{
if (isset($GLOBALS['TCA'][$table])) {
$paletteData = &$GLOBALS['TCA'][$table]['palettes'][$palette];
// If palette already exists, merge the data:
if (is_array($paletteData)) {
$paletteData['showitem'] = self::executePositionedStringInsertion($paletteData['showitem'], $addFields, $insertionPosition);
} else {
$paletteData['showitem'] = self::removeDuplicatesForInsertion($addFields);
}
}
}
/**
* Add an item to a select field item list.
*
* Warning: Do not use this method for radio or check types, especially not
* with $relativeToField and $relativePosition parameters. This would shift
* existing database data 'off by one'.
*
* As an example, this can be used to add an item to tt_content CType select
* drop-down after the existing 'mailform' field with these parameters:
* - $table = 'tt_content'
* - $field = 'CType'
* - $item = array(
* 'LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:CType.I.10',
* 'login',
* 'i/imagename.gif',
* ),
* - $relativeToField = mailform
* - $relativePosition = after
*
* @throws \InvalidArgumentException If given parameters are not of correct
* @throws \RuntimeException If reference to related position fields can not
* @param string $table Name of TCA table
* @param string $field Name of TCA field
* @param array $item New item to add
* @param string $relativeToField Add item relative to existing field
* @param string $relativePosition Valid keywords: 'before', 'after'
* @return void
*/
public static function addTcaSelectItem($table, $field, array $item, $relativeToField = '', $relativePosition = '')
{
if (!is_string($table)) {
throw new \InvalidArgumentException('Given table is of type "' . gettype($table) . '" but a string is expected.', 1303236963);
}
if (!is_string($field)) {
throw new \InvalidArgumentException('Given field is of type "' . gettype($field) . '" but a string is expected.', 1303236964);
}
if (!is_string($relativeToField)) {
throw new \InvalidArgumentException('Given relative field is of type "' . gettype($relativeToField) . '" but a string is expected.', 1303236965);
}
if (!is_string($relativePosition)) {
throw new \InvalidArgumentException('Given relative position is of type "' . gettype($relativePosition) . '" but a string is expected.', 1303236966);
}
if ($relativePosition !== '' && $relativePosition !== 'before' && $relativePosition !== 'after' && $relativePosition !== 'replace') {
throw new \InvalidArgumentException('Relative position must be either empty or one of "before", "after", "replace".', 1303236967);
}
if (!is_array($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'])) {
throw new \RuntimeException('Given select field item list was not found.', 1303237468);
}
// Make sure item keys are integers
$GLOBALS['TCA'][$table]['columns'][$field]['config']['items'] = array_values($GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
if ($relativePosition !== '') {
// Insert at specified position
$matchedPosition = ArrayUtility::filterByValueRecursive($relativeToField, $GLOBALS['TCA'][$table]['columns'][$field]['config']['items']);
if (!empty($matchedPosition)) {
$relativeItemKey = key($matchedPosition);
if ($relativePosition === 'replace') {
$GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][$relativeItemKey] = $item;
} else {
if ($relativePosition === 'before') {
$offset = $relativeItemKey;
} else {
$offset = $relativeItemKey + 1;
}
array_splice($GLOBALS['TCA'][$table]['columns'][$field]['config']['items'], $offset, 0, array(0 => $item));
}
} else {
// Insert at new item at the end of the array if relative position was not found
$GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
}
} else {
// Insert at new item at the end of the array
$GLOBALS['TCA'][$table]['columns'][$field]['config']['items'][] = $item;
}
}
/**
* Gets the TCA configuration for a field handling (FAL) files.
*
* @param string $fieldName Name of the field to be used
* @param array $customSettingOverride Custom field settings overriding the basics
* @param string $allowedFileExtensions Comma list of allowed file extensions (e.g. "jpg,gif,pdf")
* @param string $disallowedFileExtensions
*
* @return array
*/
public static function getFileFieldTCAConfig($fieldName, array $customSettingOverride = array(), $allowedFileExtensions = '', $disallowedFileExtensions = '')
{
$fileFieldTCAConfig = array(
'type' => 'inline',
'foreign_table' => 'sys_file_reference',
'foreign_field' => 'uid_foreign',
'foreign_sortby' => 'sorting_foreign',
'foreign_table_field' => 'tablenames',
'foreign_match_fields' => array(
'fieldname' => $fieldName
),
'foreign_label' => 'uid_local',
'foreign_selector' => 'uid_local',
'foreign_selector_fieldTcaOverride' => array(
'config' => array(
'appearance' => array(
'elementBrowserType' => 'file',
'elementBrowserAllowed' => $allowedFileExtensions
)
)
),
'filter' => array(
array(
'userFunc' => \TYPO3\CMS\Core\Resource\Filter\FileExtensionFilter::class . '->filterInlineChildren',
'parameters' => array(
'allowedFileExtensions' => $allowedFileExtensions,
'disallowedFileExtensions' => $disallowedFileExtensions
)
)
),
'appearance' => array(
'useSortable' => true,
'headerThumbnail' => array(
'field' => 'uid_local',
'width' => '45',
'height' => '45c',
),
'showPossibleLocalizationRecords' => false,
'showRemovedLocalizationRecords' => false,
'showSynchronizationLink' => false,
'showAllLocalizationLink' => false,
'enabledControls' => array(
'info' => true,
'new' => false,
'dragdrop' => true,
'sort' => false,
'hide' => true,
'delete' => true,
'localize' => true,
),
),
'behaviour' => array(
'localizationMode' => 'select',
'localizeChildrenAtParentLocalization' => true,
),
);
ArrayUtility::mergeRecursiveWithOverrule($fileFieldTCAConfig, $customSettingOverride);
return $fileFieldTCAConfig;
}
/**
* Adds a list of new fields to the TYPO3 USER SETTINGS configuration "showitem" list, the array with
* the new fields itself needs to be added additionally to show up in the user setup, like
* $GLOBALS['TYPO3_USER_SETTINGS']['columns'] += $tempColumns
*
* @param string $addFields List of fields to be added to the user settings
* @param string $insertionPosition Insert fields before (default) or after one
* @return void
*/
public static function addFieldsToUserSettings($addFields, $insertionPosition = '')
{
$GLOBALS['TYPO3_USER_SETTINGS']['showitem'] = self::executePositionedStringInsertion($GLOBALS['TYPO3_USER_SETTINGS']['showitem'], $addFields, $insertionPosition);
}
/**
* Inserts as list of data into an existing list.
* The insertion position can be defined accordant before of after existing list items.
*
* Example:
* + list: 'field_a, field_b, field_c'
* + insertionList: 'field_d, field_e'
* + insertionPosition: 'after:field_b'
* -> 'field_a, field_b, field_d, field_e, field_c'
*
* $insertPosition may contain ; and - characters: after:--palette--;;title
*
* @param string $list The list of items to be extended
* @param string $insertionList The list of items to inserted
* @param string $insertionPosition Insert fields before (default) or after one
* @return string The extended list
*/
protected static function executePositionedStringInsertion($list, $insertionList, $insertionPosition = '')
{
$list = $newList = trim($list, ", \t\n\r\0\x0B");
list($location, $positionName) = GeneralUtility::trimExplode(':', $insertionPosition);
if ($location !== 'replace') {
$insertionList = self::removeDuplicatesForInsertion($insertionList, $list);
}
if ($insertionList === '') {
return $list;
}
if ($list === '') {
return $insertionList;
}
if ($insertionPosition === '') {
return $list . ', ' . $insertionList;
}
// The $insertPosition may be a palette: after:--palette--;;title
// In the $list the palette may contain a LLL string in between the ;;
// Adjust the regex to match that
if (strpos($positionName, ';;') !== false) {
$positionName = str_replace(';;', ';[^;]*;', $positionName);
}
$pattern = ('/(^|,\\s*)(' . $positionName . ')(;[^,$]+)?(,|$)/');
switch ($location) {
case 'after':
$newList = preg_replace($pattern, '$1$2$3, ' . $insertionList . '$4', $list);
break;
case 'before':
$newList = preg_replace($pattern, '$1' . $insertionList . ', $2$3$4', $list);
break;
case 'replace':
$newList = preg_replace($pattern, '$1' . $insertionList . '$4', $list);
break;
default:
}
// When preg_replace did not replace anything; append the $insertionList.
if ($list === $newList) {
return $list . ', ' . $insertionList;
}
return $newList;
}
/**
* Compares an existing list of items and a list of items to be inserted
* and returns a duplicate-free variant of that insertion list.
*
* Example:
* + list: 'field_a, field_b, field_c'
* + insertion: 'field_b, field_d, field_c'
* -> new insertion: 'field_d'
*
* Duplicate values in $insertionList are removed.
*
* @param string $insertionList The list of items to inserted
* @param string $list The list of items to be extended (default: '')
* @return string Duplicate-free list of items to be inserted
*/
protected static function removeDuplicatesForInsertion($insertionList, $list = '')
{
$insertionListParts = preg_split('/\\s*,\\s*/', $insertionList);
$listMatches = array();
if ($list !== '') {
preg_match_all('/(?:^|,)\\s*\\b([^;,]+)\\b[^,]*/', $list, $listMatches);
$listMatches = $listMatches[1];
}
$cleanInsertionListParts = array();
foreach ($insertionListParts as $fieldName) {
$fieldNameParts = explode(';', $fieldName, 2);
$cleanFieldName = $fieldNameParts[0];
if (
$cleanFieldName === '--linebreak--'
|| (
!in_array($cleanFieldName, $cleanInsertionListParts, true)
&& !in_array($cleanFieldName, $listMatches, true)
)
) {
$cleanInsertionListParts[] = $fieldName;
}
}
return implode(', ', $cleanInsertionListParts);
}
/**
* Generates an array of fields/items with additional information such as e.g. the name of the palette.
*
* @param string $itemList List of fields/items to be splitted up
* @return array An array with the names of the fields/items as keys and additional information
*/
protected static function explodeItemList($itemList)
{
$items = array();
$itemParts = GeneralUtility::trimExplode(',', $itemList, true);
foreach ($itemParts as $itemPart) {
$itemDetails = GeneralUtility::trimExplode(';', $itemPart, false, 5);
$key = $itemDetails[0];
if (strpos($key, '--') !== false) {
// 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!
$key .= count($items);
}
if (!isset($items[$key])) {
$items[$key] = array(
'rawData' => $itemPart,
'details' => array()
);
$details = array(0 => 'field', 1 => 'label', 2 => 'palette');
foreach ($details as $id => $property) {
$items[$key]['details'][$property] = isset($itemDetails[$id]) ? $itemDetails[$id] : '';
}
}
}
return $items;
}
/**
* Generates a list of fields/items out of an array provided by the function getFieldsOfFieldList().
*
* @see explodeItemList
* @param array $items The array of fields/items with optional additional information
* @param bool $useRawData Use raw data instead of building by using the details (default: FALSE)
* @return string The list of fields/items which gets used for $GLOBALS['TCA'][<table>]['types'][<type>]['showitem']
*/
protected static function generateItemList(array $items, $useRawData = false)
{
$itemParts = array();
foreach ($items as $item => $itemDetails) {
if (strpos($item, '--') !== false) {
// 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.
$item = str_replace(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), '', $item);
}
if ($useRawData) {
$itemParts[] = $itemDetails['rawData'];
} else {
if (count($itemDetails['details']) > 1) {
$details = array('palette', 'label', 'field');
$elements = array();
$addEmpty = false;
foreach ($details as $property) {
if ($itemDetails['details'][$property] !== '' || $addEmpty) {
$addEmpty = true;
array_unshift($elements, $itemDetails['details'][$property]);
}
}
$item = implode(';', $elements);
}
$itemParts[] = $item;
}
}
return implode(', ', $itemParts);
}
/**
* Add tablename to default list of allowed tables on pages (in $PAGES_TYPES)
* Will add the $table to the list of tables allowed by default on pages as setup by $PAGES_TYPES['default']['allowedTables']
* FOR USE IN ext_tables.php FILES
*
* @param string $table Table name
* @return void
*/
public static function allowTableOnStandardPages($table)
{
$GLOBALS['PAGES_TYPES']['default']['allowedTables'] .= ',' . $table;
}
/**
* Adds an ExtJS module (main or sub) to the backend interface
* FOR USE IN ext_tables.php FILES
*
* @static
* @param string $extensionName
* @param string $mainModuleName Is the main module key
* @param string $subModuleName Is the submodule key, if blank a plain main module is generated
* @param string $position Passed to \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModule, see reference there
* @param array $moduleConfiguration Icon with array keys: access, icon, labels to configure the module
* @throws \InvalidArgumentException
*/
public static function addExtJSModule($extensionName, $mainModuleName, $subModuleName = '', $position = '', array $moduleConfiguration = array())
{
if (empty($extensionName)) {
throw new \InvalidArgumentException('The extension name must not be empty', 1325938973);
}
$extensionKey = GeneralUtility::camelCaseToLowerCaseUnderscored($extensionName);
$extensionName = str_replace(' ', '', ucwords(str_replace('_', ' ', $extensionName)));
$defaultModuleConfiguration = array(
'access' => 'admin',
'icon' => self::extRelPath('backend') . 'Resources/Public/Images/Logo.png',
'labels' => '',
'extRelPath' => self::extRelPath($extensionKey) . 'Classes/'
);
// Add mandatory parameter to use new pagetree
if ($mainModuleName === 'web') {
$defaultModuleConfiguration['navigationComponentId'] = 'typo3-pagetree';
}
ArrayUtility::mergeRecursiveWithOverrule($defaultModuleConfiguration, $moduleConfiguration);
$moduleConfiguration = $defaultModuleConfiguration;
if ($subModuleName !== '') {
$moduleSignature = $mainModuleName . '_' . $subModuleName;
} else {
$moduleSignature = $mainModuleName;
}
$moduleConfiguration['name'] = $moduleSignature;
$moduleConfiguration['script'] = 'extjspaneldummy.html';
$moduleConfiguration['extensionName'] = $extensionName;
$moduleConfiguration['configureModuleFunction'] = array(ExtensionManagementUtility::class, 'configureModule');
$GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature] = $moduleConfiguration;
self::addModule($mainModuleName, $subModuleName, $position);
}
/**
* This method is called from \TYPO3\CMS\Backend\Module\ModuleLoader::checkMod
* and it replaces old conf.php.
*
* @param string $moduleSignature The module name
* @return array Configuration of the module
*/
public static function configureModule($moduleSignature)
{
$moduleConfiguration = $GLOBALS['TBE_MODULES']['_configuration'][$moduleSignature];
if (!empty($moduleConfiguration['labels']['tabs_images']['tab'])) {
GeneralUtility::deprecationLog('Module registration for backend module "' . $moduleSignature . '" uses old referencing for the icon. Use the configuration option "icon" directly instead of [labels][tabs_images][tab]. The old option is removed with TYPO3 v9.');
$moduleConfiguration['icon'] = $moduleConfiguration['labels']['tabs_images']['tab'];
unset($moduleConfiguration['labels']['tabs_images']['tab']);
}
// Register the icon and move it too "iconIdentifier"
if (!empty($moduleConfiguration['icon'])) {
$iconIdentifier = 'module-' . $moduleSignature;
$iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
$iconRegistry->registerIcon($iconIdentifier, BitmapIconProvider::class, [
'source' => GeneralUtility::getFileAbsFileName($moduleConfiguration['icon'], false, true)
]);
$moduleConfiguration['iconIdentifier'] = $iconIdentifier;
unset($moduleConfiguration['icon']);
}
$moduleLabels = array(
'labels' => array(
'tablabel' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_labels_tablabel'),
'tabdescr' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_labels_tabdescr')
),
'tabs' => array(
'tab' => $GLOBALS['LANG']->sL($moduleConfiguration['labels'] . ':mlang_tabs_tab')
)
);
$GLOBALS['LANG']->addModuleLabels($moduleLabels, $moduleSignature . '_');
return $moduleConfiguration;
}
/**
* Adds a module (main or sub) to the backend interface
* FOR USE IN ext_tables.php FILES
*
* @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.
* @param string $sub The submodule key. If $sub is not set a blank $main module is created.
* @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.
* @param string $path The absolute path to the module. Was used prior to TYPO3 v8, use $moduleConfiguration[routeTarget] now
* @param array $moduleConfiguration additional configuration, previously put in "conf.php" of the module directory
* @return void
*/
public static function addModule($main, $sub = '', $position = '', $path = null, $moduleConfiguration = array())
{
// If there is already a main module by this name:
// Adding the submodule to the correct position:
if (isset($GLOBALS['TBE_MODULES'][$main]) && $sub) {
list($place, $modRef) = GeneralUtility::trimExplode(':', $position, true);
$modules = ',' . $GLOBALS['TBE_MODULES'][$main] . ',';
if ($place === null || ($modRef !== null && !GeneralUtility::inList($modules, $modRef))) {
$place = 'bottom';
}
$modRef = ',' . $modRef . ',';
if (!GeneralUtility::inList($modules, $sub)) {
switch (strtolower($place)) {
case 'after':
$modules = str_replace($modRef, $modRef . $sub . ',', $modules);
break;
case 'before':
$modules = str_replace($modRef, ',' . $sub . $modRef, $modules);
break;
case 'top':
$modules = $sub . $modules;
break;
case 'bottom':
default:
$modules = $modules . $sub;
}
}
// Re-inserting the submodule list:
$GLOBALS['TBE_MODULES'][$main] = trim($modules, ',');
} else {
// Create new main modules with only one submodule, $sub (or none if $sub is blank)
$GLOBALS['TBE_MODULES'][$main] = $sub;
}
// add additional configuration
if (is_array($moduleConfiguration) && !empty($moduleConfiguration)) {
$fullModuleSignature = $main . ($sub ? '_' . $sub : '');
if (!empty($moduleConfiguration['labels']['tabs_images']['tab'])) {
GeneralUtility::deprecationLog('Module registration for module "' . $fullModuleSignature . '" uses old referencing for the icon. Use the configuration option "icon" directly instead of [labels][tabs_images][tab]. The old option is removed with TYPO3 v9.');
$moduleConfiguration['icon'] = $moduleConfiguration['labels']['tabs_images']['tab'];
unset($moduleConfiguration['labels']['tabs_images']['tab']);
}
if (!empty($moduleConfiguration['icon'])) {
$iconIdentifier = 'module-' . $fullModuleSignature;
$iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
$iconRegistry->registerIcon($iconIdentifier, BitmapIconProvider::class, [
'source' => GeneralUtility::getFileAbsFileName($moduleConfiguration['icon'], false, true)
]);
$moduleConfiguration['iconIdentifier'] = $iconIdentifier;
unset($moduleConfiguration['icon']);
}
$GLOBALS['TBE_MODULES']['_configuration'][$fullModuleSignature] = $moduleConfiguration;
}
}
/**
* Registers an Ext.Direct component with access restrictions.
*
* @param string $endpointName
* @param string $callbackClass
* @param string $moduleName Optional: must be <mainmodule> or <mainmodule>_<submodule>
* @param string $accessLevel Optional: can be 'admin' or 'user,group'
* @return void
*/
public static function registerExtDirectComponent($endpointName, $callbackClass, $moduleName = null, $accessLevel = null)
{
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ExtDirect'][$endpointName] = array(
'callbackClass' => $callbackClass,
'moduleName' => $moduleName,
'accessLevel' => $accessLevel
);
}
/**
* Registers an Ajax Handler
*
* @param string $ajaxId Identifier of the handler, that is used in the request
* @param string $callbackMethod TYPO3 callback method (className->methodName).
* @param bool $csrfTokenCheck Only set this to FALSE if you are sure that the registered handler does not modify any data!
* @deprecated since TYPO3 v8, will be removed in TYPO3 v9
*/
public static function registerAjaxHandler($ajaxId, $callbackMethod, $csrfTokenCheck = true)
{
GeneralUtility::logDeprecatedFunction();
$GLOBALS['TYPO3_CONF_VARS']['BE']['AJAX'][$ajaxId] = array(
'callbackMethod' => $callbackMethod,