-
Notifications
You must be signed in to change notification settings - Fork 5
/
ContentObjectRenderer.php
5945 lines (5614 loc) · 259 KB
/
ContentObjectRenderer.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
/*
* 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!
*/
namespace TYPO3\CMS\Frontend\ContentObject;
use Doctrine\DBAL\Exception as DBALException;
use Doctrine\DBAL\Result;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LogLevel;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Context\LanguageAspect;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Database\Query\QueryHelper;
use TYPO3\CMS\Core\Database\Query\Restriction\DocumentTypeExclusionRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
use TYPO3\CMS\Core\Html\HtmlCropper;
use TYPO3\CMS\Core\Html\HtmlParser;
use TYPO3\CMS\Core\Html\SanitizerBuilderFactory;
use TYPO3\CMS\Core\Html\SanitizerInitiator;
use TYPO3\CMS\Core\Imaging\ImageManipulation\Area;
use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
use TYPO3\CMS\Core\Localization\DateFormatter;
use TYPO3\CMS\Core\Localization\LanguageServiceFactory;
use TYPO3\CMS\Core\Localization\Locales;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\Page\DefaultJavaScriptAssetTrait;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Resource\Exception;
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Core\Resource\Folder;
use TYPO3\CMS\Core\Resource\ProcessedFile;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Service\FlexFormService;
use TYPO3\CMS\Core\Text\TextCropper;
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
use TYPO3\CMS\Core\Type\BitSet;
use TYPO3\CMS\Core\TypoScript\TypoScriptService;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Core\Utility\DebugUtility;
use TYPO3\CMS\Core\Utility\Exception\MissingArrayPathException;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Utility\StringUtility;
use TYPO3\CMS\Core\Versioning\VersionState;
use TYPO3\CMS\Frontend\ContentObject\Exception\ContentRenderingException;
use TYPO3\CMS\Frontend\ContentObject\Exception\ExceptionHandlerInterface;
use TYPO3\CMS\Frontend\ContentObject\Exception\ProductionExceptionHandler;
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
use TYPO3\CMS\Frontend\Imaging\GifBuilder;
use TYPO3\CMS\Frontend\Page\PageLayoutResolver;
use TYPO3\CMS\Frontend\Resource\FilePathSanitizer;
use TYPO3\CMS\Frontend\Typolink\EmailLinkBuilder;
use TYPO3\CMS\Frontend\Typolink\LinkFactory;
use TYPO3\CMS\Frontend\Typolink\LinkResult;
use TYPO3\CMS\Frontend\Typolink\LinkResultInterface;
use TYPO3\CMS\Frontend\Typolink\UnableToLinkException;
use TYPO3\HtmlSanitizer\Builder\BuilderInterface;
/**
* This class contains all main TypoScript features, is the backbone of TypoScript
* rendering, include stdWrap and TypoScript content objects, usually referred to as "cObj".
*
* When you call your own PHP-code typically through a USER or USER_INT cObject then it is this
* class that instantiates the object and calls the main method.
*/
class ContentObjectRenderer implements LoggerAwareInterface
{
use LoggerAwareTrait;
use DefaultJavaScriptAssetTrait;
/**
* @var ContainerInterface|null
*/
protected $container;
/**
* stdWrap functions in their correct order
*
* @see stdWrap()
* @var string[]
*/
public array $stdWrapOrder = [
'stdWrapPreProcess' => 'hook',
// this is a placeholder for the first Hook
'cacheRead' => 'hook',
// this is a placeholder for checking if the content is available in cache
'setContentToCurrent' => 'boolean',
'setContentToCurrent.' => 'array',
'addPageCacheTags' => 'string',
'addPageCacheTags.' => 'array',
'setCurrent' => 'string',
'setCurrent.' => 'array',
'lang.' => 'array',
'data' => 'getText',
'data.' => 'array',
'field' => 'fieldName',
'field.' => 'array',
'current' => 'boolean',
'current.' => 'array',
'cObject' => 'cObject',
'cObject.' => 'array',
'numRows.' => 'array',
'preUserFunc' => 'functionName',
'stdWrapOverride' => 'hook',
// this is a placeholder for the second Hook
'override' => 'string',
'override.' => 'array',
'preIfEmptyListNum' => 'listNum',
'preIfEmptyListNum.' => 'array',
'ifNull' => 'string',
'ifNull.' => 'array',
'ifEmpty' => 'string',
'ifEmpty.' => 'array',
'ifBlank' => 'string',
'ifBlank.' => 'array',
'listNum' => 'listNum',
'listNum.' => 'array',
'trim' => 'boolean',
'trim.' => 'array',
'strPad.' => 'array',
'stdWrap' => 'stdWrap',
'stdWrap.' => 'array',
'stdWrapProcess' => 'hook',
// this is a placeholder for the third Hook
'required' => 'boolean',
'required.' => 'array',
'if.' => 'array',
'fieldRequired' => 'fieldName',
'fieldRequired.' => 'array',
'csConv' => 'string',
'csConv.' => 'array',
'parseFunc' => 'objectpath',
'parseFunc.' => 'array',
'HTMLparser' => 'boolean',
'HTMLparser.' => 'array',
'split.' => 'array',
'replacement.' => 'array',
'prioriCalc' => 'boolean',
'prioriCalc.' => 'array',
'char' => 'integer',
'char.' => 'array',
'intval' => 'boolean',
'intval.' => 'array',
'hash' => 'string',
'hash.' => 'array',
'round' => 'boolean',
'round.' => 'array',
'numberFormat.' => 'array',
'expandList' => 'boolean',
'expandList.' => 'array',
'date' => 'dateconf',
'date.' => 'array',
'strtotime' => 'strtotimeconf',
'strtotime.' => 'array',
'strftime' => 'strftimeconf',
'strftime.' => 'array',
'formattedDate' => 'formattedDateconf',
'formattedDate.' => 'array',
'age' => 'boolean',
'age.' => 'array',
'case' => 'case',
'case.' => 'array',
'bytes' => 'boolean',
'bytes.' => 'array',
'substring' => 'parameters',
'substring.' => 'array',
'cropHTML' => 'crop',
'cropHTML.' => 'array',
'stripHtml' => 'boolean',
'stripHtml.' => 'array',
'crop' => 'crop',
'crop.' => 'array',
'rawUrlEncode' => 'boolean',
'rawUrlEncode.' => 'array',
'htmlSpecialChars' => 'boolean',
'htmlSpecialChars.' => 'array',
'encodeForJavaScriptValue' => 'boolean',
'encodeForJavaScriptValue.' => 'array',
'doubleBrTag' => 'string',
'doubleBrTag.' => 'array',
'br' => 'boolean',
'br.' => 'array',
'brTag' => 'string',
'brTag.' => 'array',
'encapsLines.' => 'array',
'keywords' => 'boolean',
'keywords.' => 'array',
'innerWrap' => 'wrap',
'innerWrap.' => 'array',
'innerWrap2' => 'wrap',
'innerWrap2.' => 'array',
'preCObject' => 'cObject',
'preCObject.' => 'array',
'postCObject' => 'cObject',
'postCObject.' => 'array',
'wrapAlign' => 'align',
'wrapAlign.' => 'array',
'typolink.' => 'array',
'wrap' => 'wrap',
'wrap.' => 'array',
'noTrimWrap' => 'wrap',
'noTrimWrap.' => 'array',
'wrap2' => 'wrap',
'wrap2.' => 'array',
'dataWrap' => 'dataWrap',
'dataWrap.' => 'array',
'prepend' => 'cObject',
'prepend.' => 'array',
'append' => 'cObject',
'append.' => 'array',
'wrap3' => 'wrap',
'wrap3.' => 'array',
'orderedStdWrap' => 'stdWrap',
'orderedStdWrap.' => 'array',
'outerWrap' => 'wrap',
'outerWrap.' => 'array',
'insertData' => 'boolean',
'insertData.' => 'array',
'postUserFunc' => 'functionName',
'postUserFuncInt' => 'functionName',
'prefixComment' => 'string',
'prefixComment.' => 'array',
'htmlSanitize' => 'boolean',
'htmlSanitize.' => 'array',
'cacheStore' => 'hook',
// this is a placeholder for storing the content in cache
'stdWrapPostProcess' => 'hook',
// this is a placeholder for the last Hook
'debug' => 'boolean',
'debug.' => 'array',
'debugFunc' => 'boolean',
'debugFunc.' => 'array',
'debugData' => 'boolean',
'debugData.' => 'array',
];
/**
* Loaded with the current data-record.
*
* If the instance of this class is used to render records from the database those records are found in this array.
* The function stdWrap has TypoScript properties that fetch field-data from this array.
*
* @var array
* @see start()
*/
public $data = [];
/**
* @var string
*/
protected $table = '';
/**
* Used by the parseFunc function and is loaded with tag-parameters when parsing tags.
*
* @var array
*/
public $parameters = [];
/**
* @var string
*/
public $currentValKey = 'currentValue_kidjls9dksoje';
/**
* This is set to the [table]:[uid] of the record delivered in the $data-array, if the cObjects CONTENT or RECORD is in operation.
* Note that $GLOBALS['TSFE']->currentRecord is set to an equal value but always indicating the latest record rendered.
*
* @var string
*/
public $currentRecord = '';
/**
* Incremented in RecordsContentObject and ContentContentObject before each record rendering.
*
* @var int
*/
public $currentRecordNumber = 0;
/**
* Incremented in RecordsContentObject and ContentContentObject before each record rendering.
*
* @var int
*/
public $parentRecordNumber = 0;
/**
* If the ContentObjectRender was started from ContentContentObject, RecordsContentObject or SearchResultContentObject this array has two keys, 'data' and 'currentRecord' which indicates the record and data for the parent cObj.
*
* @var array
*/
public $parentRecord = [];
/**
* @var string|int
*/
public $checkPid_badDoktypeList = PageRepository::DOKTYPE_RECYCLER;
/**
* This will be set by typoLink() to the url of the most recent link created.
*
* @var string
* @deprecated will be removed in TYPO3 v13.0. Use $this->lastTypoLinkResult or call LinkFactory directly
*/
public $lastTypoLinkUrl = '';
/**
* DO. link target.
*
* @var string
* @deprecated will be removed in TYPO3 v13.0. Use $this->lastTypoLinkResult or call LinkFactory directly
*/
public $lastTypoLinkTarget = '';
/**
* @var array
* @deprecated will be removed in TYPO3 v13.0. Use $this->lastTypoLinkResult or call LinkFactory directly
*/
public $lastTypoLinkLD = [];
public ?LinkResultInterface $lastTypoLinkResult = null;
/**
* Containing hook objects for stdWrap
*
* @var array
*/
protected $stdWrapHookObjects = [];
/**
* Containing hook objects for getImgResource
*
* @var array
*/
protected $getImgResourceHookObjects;
/**
* @var File|FileReference|Folder|string|null Current file objects (during iterations over files)
*/
protected $currentFile;
/**
* Set to TRUE by doConvertToUserIntObject() if USER object wants to become USER_INT
* @var bool
*/
public $doConvertToUserIntObject = false;
/**
* Indicates current object type. Can hold one of OBJECTTYPE_ constants or FALSE.
* The value is set and reset inside USER() function. Any time outside of
* USER() it is FALSE.
* @var int|bool
*/
protected $userObjectType = false;
/**
* @var array
*/
protected $stopRendering = [];
/**
* @var int
*/
protected $stdWrapRecursionLevel = 0;
/**
* @var TypoScriptFrontendController|null
*/
protected $typoScriptFrontendController;
/**
* Request pointer, if injected. Use getRequest() instead of reading this property directly.
*/
private ?ServerRequestInterface $request = null;
/**
* Indicates that object type is USER.
*
* @see ContentObjectRender::$userObjectType
*/
public const OBJECTTYPE_USER_INT = 1;
/**
* Indicates that object type is USER.
*
* @see ContentObjectRender::$userObjectType
*/
public const OBJECTTYPE_USER = 2;
public function __construct(?TypoScriptFrontendController $typoScriptFrontendController = null, ?ContainerInterface $container = null)
{
$this->typoScriptFrontendController = $typoScriptFrontendController;
$this->container = $container;
}
public function setRequest(?ServerRequestInterface $request): void
{
$this->request = $request;
}
/**
* Prevent several objects from being serialized.
* If currentFile is set, it is either a File or a FileReference object. As the object itself can't be serialized,
* we have store a hash and restore the object in __wakeup()
*
* @return array
*/
public function __sleep()
{
$vars = get_object_vars($this);
unset($vars['typoScriptFrontendController'], $vars['logger'], $vars['container'], $vars['request']);
if ($this->currentFile instanceof FileReference) {
$this->currentFile = 'FileReference:' . $this->currentFile->getUid();
} elseif ($this->currentFile instanceof File) {
$this->currentFile = 'File:' . $this->currentFile->getIdentifier();
} else {
unset($vars['currentFile']);
}
return array_keys($vars);
}
/**
* Restore currentFile from hash.
* If currentFile references a File, the identifier equals file identifier.
* If it references a FileReference the identifier equals the uid of the reference.
*/
public function __wakeup()
{
if (isset($GLOBALS['TSFE'])) {
$this->typoScriptFrontendController = $GLOBALS['TSFE'];
}
if (is_string($this->currentFile)) {
[$objectType, $identifier] = explode(':', $this->currentFile, 2);
try {
if ($objectType === 'File') {
$this->currentFile = GeneralUtility::makeInstance(ResourceFactory::class)->retrieveFileOrFolderObject($identifier);
} elseif ($objectType === 'FileReference') {
$this->currentFile = GeneralUtility::makeInstance(ResourceFactory::class)->getFileReferenceObject($identifier);
}
} catch (ResourceDoesNotExistException $e) {
$this->currentFile = null;
}
}
$this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
$this->container = GeneralUtility::getContainer();
// We do not derive $this->request from globals here. The request is expected to be injected
// using setRequest(), a fallback to $GLOBALS['TYPO3_REQUEST'] is available in getRequest() for BC.
}
/**
* Class constructor.
* Well, it has to be called manually since it is not a real constructor function.
* So after making an instance of the class, call this function and pass to it a database record and the tablename from where the record is from. That will then become the "current" record loaded into memory and accessed by the .fields property found in eg. stdWrap.
*
* @param array $data The record data that is rendered.
* @param string $table The table that the data record is from.
*/
public function start($data, $table = '', ?ServerRequestInterface $request = null)
{
if ($request !== null) {
// @deprecated since TYPO3 v12, will be removed with v13: Remove third method argument and remove if() with body.
trigger_error(
'Do not provide $request as third argument to start(). Call setRequest() before, instead.',
E_USER_DEPRECATED
);
$this->request = $request;
}
$this->data = $data;
$this->table = $table;
$this->currentRecord = $table !== ''
? $table . ':' . ($this->data['uid'] ?? '')
: '';
$this->parameters = [];
$this->stdWrapHookObjects = [];
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['stdWrap'] ?? [] as $className) {
$hookObject = GeneralUtility::makeInstance($className);
if (!$hookObject instanceof ContentObjectStdWrapHookInterface) {
throw new \UnexpectedValueException($className . ' must implement interface ' . ContentObjectStdWrapHookInterface::class, 1195043965);
}
$this->stdWrapHookObjects[] = $hookObject;
}
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['postInit'] ?? [] as $className) {
$postInitializationProcessor = GeneralUtility::makeInstance($className);
if (!$postInitializationProcessor instanceof ContentObjectPostInitHookInterface) {
throw new \UnexpectedValueException($className . ' must implement interface ' . ContentObjectPostInitHookInterface::class, 1274563549);
}
$postInitializationProcessor->postProcessContentObjectInitialization($this);
}
}
/**
* Returns the current table
*
* @return string
*/
public function getCurrentTable()
{
return $this->table;
}
/**
* Gets the 'getImgResource' hook objects.
* The first call initializes the accordant objects.
*
* @return array The 'getImgResource' hook objects (if any)
*/
protected function getGetImgResourceHookObjects()
{
if (!isset($this->getImgResourceHookObjects)) {
$this->getImgResourceHookObjects = [];
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['getImgResource'] ?? [] as $className) {
$hookObject = GeneralUtility::makeInstance($className);
if (!$hookObject instanceof ContentObjectGetImageResourceHookInterface) {
throw new \UnexpectedValueException('$hookObject must implement interface ' . ContentObjectGetImageResourceHookInterface::class, 1218636383);
}
$this->getImgResourceHookObjects[] = $hookObject;
}
}
return $this->getImgResourceHookObjects;
}
/**
* Sets the internal variable parentRecord with information about current record.
* If the ContentObjectRender was started from CONTENT, RECORD or SEARCHRESULT cObject's this array has two keys, 'data' and 'currentRecord' which indicates the record and data for the parent cObj.
*
* @param array $data The record array
* @param string $currentRecord This is set to the [table]:[uid] of the record delivered in the $data-array, if the cObjects CONTENT or RECORD is in operation. Note that $GLOBALS['TSFE']->currentRecord is set to an equal value but always indicating the latest record rendered.
* @internal
*/
public function setParent($data, $currentRecord)
{
$this->parentRecord = [
'data' => $data,
'currentRecord' => $currentRecord,
];
}
/***********************************************
*
* CONTENT_OBJ:
*
***********************************************/
/**
* Returns the "current" value.
* The "current" value is just an internal variable that can be used by functions to pass a single value on to another function later in the TypoScript processing.
* It's like "load accumulator" in the good old C64 days... basically a "register" you can use as you like.
* The TSref will tell if functions are setting this value before calling some other object so that you know if it holds any special information.
*
* @return mixed The "current" value
*/
public function getCurrentVal()
{
return $this->data[$this->currentValKey] ?? null;
}
/**
* Sets the "current" value.
*
* @param mixed $value The variable that you want to set as "current
* @see getCurrentVal()
*/
public function setCurrentVal($value)
{
$this->data[$this->currentValKey] = $value;
}
/**
* Rendering of a "numerical array" of cObjects from TypoScript
* Will call ->cObjGetSingle() for each cObject found and accumulate the output.
*
* @param array $setup array with cObjects as values.
* @param string $addKey A prefix for the debugging information
* @return string Rendered output from the cObjects in the array.
* @see cObjGetSingle()
*/
public function cObjGet($setup, $addKey = '')
{
if (!is_array($setup)) {
return '';
}
return implode('', $this->cObjGetSeparated($setup, $addKey));
}
/**
* Rendering of a "numerical array" of cObjects from TypoScript
* Will call ->cObjGetSingle() for each cObject found.
*
* @return list<string>
*/
public function cObjGetSeparated(?array $setup, string $addKey = ''): array
{
if ($setup === null || $setup === []) {
return [];
}
$sKeyArray = ArrayUtility::filterAndSortByNumericKeys($setup);
$contentObjects = [];
foreach ($sKeyArray as $theKey) {
$theValue = $setup[$theKey];
if ((int)$theKey && !str_contains($theKey, '.')) {
$conf = $setup[$theKey . '.'] ?? [];
$contentObjects[] = $this->cObjGetSingle($theValue, $conf, $addKey . $theKey);
}
}
return $contentObjects;
}
/**
* Renders a content object
*
* @param string $name The content object name, eg. "TEXT" or "USER" or "IMAGE"
* @param array $conf The array with TypoScript properties for the content object
* @param string $TSkey A string label used for the internal debugging tracking.
* @return string cObject output
* @throws \UnexpectedValueException
*/
public function cObjGetSingle(string $name, $conf, $TSkey = '__')
{
$timeTracker = $this->getTimeTracker();
$name = trim($name);
if ($timeTracker->LR) {
$timeTracker->push($TSkey, $name);
}
$fullConfigArray = [
'tempKey' => $name,
'tempKey.' => is_array($conf) ? $conf : [],
];
// Resolve '=<' operator if needed
$fullConfigArray = $this->mergeTSRef($fullConfigArray, 'tempKey');
$contentObject = $this->getContentObject($fullConfigArray['tempKey']);
$content = '';
if ($contentObject) {
$content = $this->render($contentObject, $fullConfigArray['tempKey.']);
}
if ($timeTracker->LR) {
$timeTracker->pull($content);
}
return $content;
}
/**
* Returns a new content object of type $name.
*
* @param string $name
* @throws ContentRenderingException
*/
public function getContentObject($name): ?AbstractContentObject
{
$contentObjectFactory = $this->container
? $this->container->get(ContentObjectFactory::class)
: GeneralUtility::makeInstance(ContentObjectFactory::class);
return $contentObjectFactory->getContentObject($name, $this->getRequest(), $this);
}
/********************************************
*
* Functions rendering content objects (cObjects)
*
********************************************/
/**
* Renders a content object by taking exception and cache handling
* into consideration
*
* @param AbstractContentObject $contentObject Content object instance
* @param array $configuration Array of TypoScript properties
*
* @throws ContentRenderingException
* @throws \Exception
*/
public function render(AbstractContentObject $contentObject, $configuration = []): string
{
$content = '';
// Evaluate possible cache and return
$cacheConfiguration = $configuration['cache.'] ?? null;
if ($cacheConfiguration !== null) {
unset($configuration['cache.']);
$cache = $this->getFromCache($cacheConfiguration);
if ($cache !== false) {
return $cache;
}
}
// Render content
try {
$content .= $contentObject->render($configuration);
} catch (ContentRenderingException $exception) {
// Content rendering Exceptions indicate a critical problem which should not be
// caught e.g. when something went wrong with Exception handling itself
throw $exception;
} catch (\Throwable $exception) {
$exceptionHandler = $this->createExceptionHandler($configuration);
if ($exceptionHandler === null) {
throw $exception;
}
// Ensure that the exception handler receives an \Exception instance,
// which is required by the \ExceptionHandlerInterface.
if (!$exception instanceof \Exception) {
$exception = new \Exception($exception->getMessage(), 1698347363, $exception);
}
$content = $exceptionHandler->handle($exception, $contentObject, $configuration);
}
// Store cache
if ($cacheConfiguration !== null && !$this->getTypoScriptFrontendController()->no_cache) {
$key = $this->calculateCacheKey($cacheConfiguration);
if (!empty($key)) {
$cacheFrontend = GeneralUtility::makeInstance(CacheManager::class)->getCache('hash');
$tags = $this->calculateCacheTags($cacheConfiguration);
$lifetime = $this->calculateCacheLifetime($cacheConfiguration);
$cachedData = [
'content' => $content,
'cacheTags' => $tags,
];
$cacheFrontend->set($key, $cachedData, $tags, $lifetime);
$this->getTypoScriptFrontendController()->addCacheTags($tags);
}
}
return $content;
}
/**
* Creates the content object exception handler from local content object configuration
* or, from global configuration if not explicitly disabled in local configuration
*
* @param array $configuration
* @return ExceptionHandlerInterface|null
* @throws ContentRenderingException
*/
protected function createExceptionHandler($configuration = [])
{
$exceptionHandler = null;
$exceptionHandlerClassName = $this->determineExceptionHandlerClassName($configuration);
if (!empty($exceptionHandlerClassName)) {
$exceptionHandler = GeneralUtility::makeInstance($exceptionHandlerClassName);
if (!$exceptionHandler instanceof ExceptionHandlerInterface) {
throw new ContentRenderingException('An exception handler was configured but the class does not exist or does not implement the ExceptionHandlerInterface', 1403653369);
}
$exceptionHandler->setConfiguration($this->mergeExceptionHandlerConfiguration($configuration));
}
return $exceptionHandler;
}
/**
* Determine exception handler class name from global and content object configuration
*
* @param array $configuration
* @return string|null
*/
protected function determineExceptionHandlerClassName($configuration)
{
$exceptionHandlerClassName = null;
$tsfe = $this->getTypoScriptFrontendController();
if (!isset($tsfe->config['config']['contentObjectExceptionHandler'])) {
if (Environment::getContext()->isProduction()) {
$exceptionHandlerClassName = '1';
}
} else {
$exceptionHandlerClassName = $tsfe->config['config']['contentObjectExceptionHandler'];
}
if (isset($configuration['exceptionHandler'])) {
$exceptionHandlerClassName = $configuration['exceptionHandler'];
}
if ($exceptionHandlerClassName === '1') {
$exceptionHandlerClassName = ProductionExceptionHandler::class;
}
return $exceptionHandlerClassName;
}
/**
* Merges global exception handler configuration with the one from the content object
* and returns the merged exception handler configuration
*
* @param array $configuration
* @return array
*/
protected function mergeExceptionHandlerConfiguration($configuration)
{
$exceptionHandlerConfiguration = [];
$tsfe = $this->getTypoScriptFrontendController();
if (!empty($tsfe->config['config']['contentObjectExceptionHandler.'])) {
$exceptionHandlerConfiguration = $tsfe->config['config']['contentObjectExceptionHandler.'];
}
if (!empty($configuration['exceptionHandler.'])) {
$exceptionHandlerConfiguration = array_replace_recursive($exceptionHandlerConfiguration, $configuration['exceptionHandler.']);
}
return $exceptionHandlerConfiguration;
}
/**
* Retrieves a type of object called as USER or USER_INT. Object can detect their
* type by using this call. It returns OBJECTTYPE_USER_INT or OBJECTTYPE_USER depending on the
* current object execution. In all other cases it will return FALSE to indicate
* a call out of context.
*
* @return mixed One of OBJECTTYPE_ class constants or FALSE
*/
public function getUserObjectType()
{
return $this->userObjectType;
}
/**
* Sets the user object type
*
* @param mixed $userObjectType
*/
public function setUserObjectType($userObjectType)
{
$this->userObjectType = $userObjectType;
}
/**
* Requests the current USER object to be converted to USER_INT.
*/
public function convertToUserIntObject()
{
if ($this->userObjectType !== self::OBJECTTYPE_USER) {
$this->getTimeTracker()->setTSlogMessage(self::class . '::convertToUserIntObject() is called in the wrong context or for the wrong object type', LogLevel::WARNING);
} else {
$this->doConvertToUserIntObject = true;
}
}
/************************************
*
* Various helper functions for content objects:
*
************************************/
/**
* Converts a given config in Flexform to a conf-array
*
* @param string|array $flexData Flexform data
* @param array $conf Array to write the data into, by reference
* @param bool $recursive Is set if called recursive. Don't call function with this parameter, it's used inside the function only
*/
public function readFlexformIntoConf($flexData, &$conf, $recursive = false)
{
if ($recursive === false && is_string($flexData)) {
$flexData = GeneralUtility::xml2array($flexData, 'T3');
}
if (is_array($flexData) && isset($flexData['data']['sDEF']['lDEF'])) {
$flexData = $flexData['data']['sDEF']['lDEF'];
}
if (!is_array($flexData)) {
return;
}
foreach ($flexData as $key => $value) {
if (!is_array($value)) {
continue;
}
if (isset($value['el'])) {
if (is_array($value['el']) && !empty($value['el'])) {
foreach ($value['el'] as $ekey => $element) {
if (isset($element['vDEF'])) {
$conf[$ekey] = $element['vDEF'];
} else {
if (is_array($element)) {
$this->readFlexformIntoConf($element, $conf[$key][key($element)][$ekey], true);
} else {
$this->readFlexformIntoConf($element, $conf[$key][$ekey], true);
}
}
}
} else {
$this->readFlexformIntoConf($value['el'], $conf[$key], true);
}
}
if (isset($value['vDEF'])) {
$conf[$key] = $value['vDEF'];
}
}
}
/**
* Returns all parents of the given PID (Page UID) list
*
* @param string $pidList A list of page Content-Element PIDs (Page UIDs) / stdWrap
* @param array $pidConf stdWrap array for the list
* @return string A list of PIDs
* @internal
*/
public function getSlidePids($pidList, $pidConf)
{
// todo: phpstan states that $pidConf always exists and is not nullable. At the moment, this is a false positive
// as null can be passed into this method via $pidConf. As soon as more strict types are used, this isset
// check must be replaced with a more appropriate check like empty or count.
$pidList = isset($pidConf) ? trim((string)$this->stdWrap($pidList, $pidConf)) : trim($pidList);
if ($pidList === '') {
$pidList = 'this';
}
$tsfe = $this->getTypoScriptFrontendController();
$listArr = null;
if (trim($pidList)) {
$listArr = GeneralUtility::intExplode(',', str_replace('this', (string)$tsfe->contentPid, $pidList));
$listArr = $this->checkPidArray($listArr);
}
$pidList = [];
if (is_array($listArr) && !empty($listArr)) {
foreach ($listArr as $uid) {
$page = $tsfe->sys_page->getPage($uid);
if (!$page['is_siteroot']) {
$pidList[] = $page['pid'];
}
}
}
return implode(',', $pidList);
}
/**
* Wraps the input string in link-tags that opens the image in a new window.
*
* @param string $string String to wrap, probably an <img> tag
* @param string|File|FileReference $imageFile The original image file
* @param array $conf TypoScript properties for the "imageLinkWrap" function
* @return string The input string, $string, wrapped as configured.
* @internal This method should be used within TYPO3 Core only
*/
public function imageLinkWrap($string, $imageFile, $conf)
{
$string = (string)$string;
$enable = $this->stdWrapValue('enable', $conf ?? []);
if (!$enable) {
return $string;
}
$content = (string)$this->typoLink($string, $conf['typolink.'] ?? []);
if (isset($conf['file.']) && is_scalar($imageFile)) {
$imageFile = $this->stdWrap((string)$imageFile, $conf['file.']);
}
if ($imageFile instanceof File) {
$file = $imageFile;
} elseif ($imageFile instanceof FileReference) {
$file = $imageFile->getOriginalFile();
} else {
if (MathUtility::canBeInterpretedAsInteger($imageFile)) {
$file = GeneralUtility::makeInstance(ResourceFactory::class)->getFileObject((int)$imageFile);
} else {
$file = GeneralUtility::makeInstance(ResourceFactory::class)->getFileObjectFromCombinedIdentifier($imageFile);
}
}
// Create imageFileLink if not created with typolink
if ($content === $string && $file !== null) {
$parameterNames = ['width', 'height', 'effects', 'bodyTag', 'title', 'wrap', 'crop'];
$parameters = [];
$sample = $this->stdWrapValue('sample', $conf ?? []);
if ($sample) {
$parameters['sample'] = 1;
}
foreach ($parameterNames as $parameterName) {
if (isset($conf[$parameterName . '.'])) {
$conf[$parameterName] = $this->stdWrap($conf[$parameterName] ?? '', $conf[$parameterName . '.'] ?? []);
}
if (isset($conf[$parameterName]) && $conf[$parameterName]) {
$parameters[$parameterName] = $conf[$parameterName];
}
}
$parametersEncoded = base64_encode((string)json_encode($parameters));
$hmac = GeneralUtility::hmac(implode('|', [$file->getUid(), $parametersEncoded]));
$params = '&md5=' . $hmac;
foreach (str_split($parametersEncoded, 64) as $index => $chunk) {
$params .= '¶meters' . rawurlencode('[') . $index . rawurlencode(']') . '=' . rawurlencode($chunk);
}
$url = $this->getTypoScriptFrontendController()->absRefPrefix . 'index.php?eID=tx_cms_showpic&file=' . $file->getUid() . $params;
$directImageLink = $this->stdWrapValue('directImageLink', $conf ?? []);
if ($directImageLink) {
$imgResourceConf = [
'file' => $imageFile,
'file.' => $conf,
];