ContentObjectRenderer.php 304 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * 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.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
15

16
17
namespace TYPO3\CMS\Frontend\ContentObject;

18
use Doctrine\DBAL\Exception as DBALException;
19
use Doctrine\DBAL\Result;
20
use Psr\Container\ContainerInterface;
21
use Psr\Http\Message\ServerRequestInterface;
22
23
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
24
use Psr\Log\LogLevel;
25
use TYPO3\CMS\Core\Authentication\AbstractUserAuthentication;
26
use TYPO3\CMS\Core\Cache\CacheManager;
27
use TYPO3\CMS\Core\Configuration\Features;
28
use TYPO3\CMS\Core\Context\Context;
29
use TYPO3\CMS\Core\Context\LanguageAspect;
30
use TYPO3\CMS\Core\Core\Environment;
31
use TYPO3\CMS\Core\Database\ConnectionPool;
32
use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
33
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
34
35
use TYPO3\CMS\Core\Database\Query\QueryHelper;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
36
use TYPO3\CMS\Core\Database\Query\Restriction\DocumentTypeExclusionRestriction;
37
use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
38
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
39
use TYPO3\CMS\Core\Html\HtmlParser;
40
use TYPO3\CMS\Core\Html\SanitizerBuilderFactory;
41
use TYPO3\CMS\Core\Html\SanitizerInitiator;
42
use TYPO3\CMS\Core\Imaging\ImageManipulation\Area;
43
use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
44
use TYPO3\CMS\Core\LinkHandling\Exception\UnknownLinkHandlerException;
45
use TYPO3\CMS\Core\LinkHandling\LinkService;
46
use TYPO3\CMS\Core\Localization\Locales;
47
use TYPO3\CMS\Core\Log\LogManager;
48
use TYPO3\CMS\Core\Page\DefaultJavaScriptAssetTrait;
49
use TYPO3\CMS\Core\Resource\Exception;
50
use TYPO3\CMS\Core\Resource\Exception\InvalidPathException;
51
52
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
use TYPO3\CMS\Core\Resource\File;
53
use TYPO3\CMS\Core\Resource\FileInterface;
54
use TYPO3\CMS\Core\Resource\FileReference;
55
use TYPO3\CMS\Core\Resource\Folder;
56
use TYPO3\CMS\Core\Resource\ProcessedFile;
57
use TYPO3\CMS\Core\Resource\ResourceFactory;
58
use TYPO3\CMS\Core\Service\DependencyOrderingService;
59
use TYPO3\CMS\Core\Service\FlexFormService;
60
use TYPO3\CMS\Core\Site\SiteFinder;
61
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
62
use TYPO3\CMS\Core\Type\BitSet;
63
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
64
use TYPO3\CMS\Core\TypoScript\TemplateService;
65
use TYPO3\CMS\Core\TypoScript\TypoScriptService;
66
use TYPO3\CMS\Core\Utility\ArrayUtility;
67
use TYPO3\CMS\Core\Utility\DebugUtility;
68
use TYPO3\CMS\Core\Utility\Exception\MissingArrayPathException;
69
use TYPO3\CMS\Core\Utility\GeneralUtility;
70
use TYPO3\CMS\Core\Utility\HttpUtility;
71
use TYPO3\CMS\Core\Utility\MathUtility;
72
use TYPO3\CMS\Core\Utility\StringUtility;
73
use TYPO3\CMS\Core\Versioning\VersionState;
74
use TYPO3\CMS\Frontend\ContentObject\Exception\ContentRenderingException;
75
use TYPO3\CMS\Frontend\ContentObject\Exception\ExceptionHandlerInterface;
76
use TYPO3\CMS\Frontend\ContentObject\Exception\ProductionExceptionHandler;
77
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
78
use TYPO3\CMS\Frontend\Http\UrlProcessorInterface;
79
use TYPO3\CMS\Frontend\Imaging\GifBuilder;
80
use TYPO3\CMS\Frontend\Page\PageLayoutResolver;
81
use TYPO3\CMS\Frontend\Resource\FilePathSanitizer;
82
use TYPO3\CMS\Frontend\Service\TypoLinkCodecService;
83
use TYPO3\CMS\Frontend\Typolink\AbstractTypolinkBuilder;
84
85
use TYPO3\CMS\Frontend\Typolink\LinkResult;
use TYPO3\CMS\Frontend\Typolink\LinkResultInterface;
86
use TYPO3\CMS\Frontend\Typolink\UnableToLinkException;
87
use TYPO3\HtmlSanitizer\Builder\BuilderInterface;
88

89
90
91
92
93
94
/**
 * This class contains all main TypoScript features.
 * This includes the rendering of TypoScript content objects (cObjects).
 * Is the backbone of TypoScript Template rendering.
 *
 * There are lots of functions you can use from your include-scripts.
95
 * The class is normally instantiated and referred to as "cObj".
96
97
 * 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. Before it does so it will set (if you are using classes) a reference to itself in the internal variable "cObj" of the object. Thus you can access all functions and data from this class by $this->cObj->... from within you classes written to be USER or USER_INT content objects.
 */
98
class ContentObjectRenderer implements LoggerAwareInterface
99
{
100
    use LoggerAwareTrait;
101
    use DefaultJavaScriptAssetTrait;
102

103
    /**
104
     * @var ContainerInterface|null
105
106
107
     */
    protected $container;

108
109
    /**
     * @var array
110
     * @deprecated since v11, will be removed in v12. Unused.
111
     */
112
    public $align = [
113
114
        'center',
        'right',
115
        'left',
116
    ];
117
118
119
120
121

    /**
     * stdWrap functions in their correct order
     *
     * @see stdWrap()
122
     * @var string[]
123
     */
124
    public $stdWrapOrder = [
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
        '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',
        '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',
263
264
265
266
        'editIcons' => 'string', // @deprecated since v11, will be removed with v12. Drop together with other editIcon removals.
        'editIcons.' => 'array', // @deprecated since v11, will be removed with v12. Drop together with other editIcon removals.
        'editPanel' => 'boolean', // @deprecated since v11, will be removed with v12. Drop together with other editPanel removals.
        'editPanel.' => 'array', // @deprecated since v11, will be removed with v12. Drop together with other editPanel removals.
267
268
        'htmlSanitize' => 'boolean',
        'htmlSanitize.' => 'array',
269
270
271
272
273
274
275
276
277
        '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',
278
        'debugData.' => 'array',
279
    ];
280
281
282
283
284
285

    /**
     * Class names for accordant content object names
     *
     * @var array
     */
286
    protected $contentObjectClassMap = [];
287
288
289
290
291
292
293
294

    /**
     * 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
295
     * @see start()
296
     */
297
    public $data = [];
298
299
300
301
302
303
304

    /**
     * @var string
     */
    protected $table = '';

    /**
305
     * Used for backup
306
307
     *
     * @var array
308
     * @deprecated since v11, will be removed in v12. Unused.
309
     */
310
    public $oldData = [];
311
312
313
314
315

    /**
     * If this is set with an array before stdWrap, it's used instead of $this->data in the data-property in stdWrap
     *
     * @var string
316
     * @deprecated since v11, will be removed in v12. Drop together with usages in this class.
317
318
319
320
321
322
323
324
     */
    public $alternativeData = '';

    /**
     * Used by the parseFunc function and is loaded with tag-parameters when parsing tags.
     *
     * @var array
     */
325
    public $parameters = [];
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343

    /**
     * @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 = '';

    /**
     * Set in RecordsContentObject and ContentContentObject to the current number of records selected in a query.
     *
     * @var int
344
     * @deprecated since v11, will be removed in v12. Drop together with usages in RecordsContentObject and ContentContentObject
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
     */
    public $currentRecordTotal = 0;

    /**
     * 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
     */
367
    public $parentRecord = [];
368
369

    /**
370
     * @var string|int
371
     */
372
    public $checkPid_badDoktypeList = PageRepository::DOKTYPE_RECYCLER;
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390

    /**
     * This will be set by typoLink() to the url of the most recent link created.
     *
     * @var string
     */
    public $lastTypoLinkUrl = '';

    /**
     * DO. link target.
     *
     * @var string
     */
    public $lastTypoLinkTarget = '';

    /**
     * @var array
     */
391
    public $lastTypoLinkLD = [];
392

393
394
    public ?LinkResultInterface $lastTypoLinkResult = null;

395
396
397
398
    /**
     * array that registers rendered content elements (or any table) to make sure they are not rendered recursively!
     *
     * @var array
399
     * @deprecated since v11, will be removed in v12. Unused.
400
     */
401
    public $recordRegister = [];
402
403
404
405
406
407

    /**
     * Containing hook objects for stdWrap
     *
     * @var array
     */
408
    protected $stdWrapHookObjects = [];
409
410
411
412
413
414
415
416
417

    /**
     * Containing hook objects for getImgResource
     *
     * @var array
     */
    protected $getImgResourceHookObjects;

    /**
418
     * @var File|FileReference|Folder|string|null Current file objects (during iterations over files)
419
     */
420
    protected $currentFile;
421
422
423

    /**
     * Set to TRUE by doConvertToUserIntObject() if USER object wants to become USER_INT
424
     * @var bool
425
426
427
428
429
430
431
     */
    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.
432
     * @var bool
433
434
435
436
437
438
     */
    protected $userObjectType = false;

    /**
     * @var array
     */
439
    protected $stopRendering = [];
440
441
442
443
444
445
446

    /**
     * @var int
     */
    protected $stdWrapRecursionLevel = 0;

    /**
447
     * @var TypoScriptFrontendController|null
448
449
450
     */
    protected $typoScriptFrontendController;

451
452
453
454
455
456
457
    /**
     * Request pointer, if injected. Use getRequest() instead of reading this property directly.
     *
     * @var ServerRequestInterface|null
     */
    private ?ServerRequestInterface $request = null;

458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
    /**
     * Indicates that object type is USER.
     *
     * @see ContentObjectRender::$userObjectType
     */
    const OBJECTTYPE_USER_INT = 1;
    /**
     * Indicates that object type is USER.
     *
     * @see ContentObjectRender::$userObjectType
     */
    const OBJECTTYPE_USER = 2;

    /**
     * @param TypoScriptFrontendController $typoScriptFrontendController
473
     * @param ContainerInterface $container
474
     */
475
    public function __construct(TypoScriptFrontendController $typoScriptFrontendController = null, ContainerInterface $container = null)
476
477
    {
        $this->typoScriptFrontendController = $typoScriptFrontendController;
478
        $this->contentObjectClassMap = $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'] ?? [];
479
        $this->container = $container;
480
481
    }

482
483
484
485
486
    public function setRequest(ServerRequestInterface $request): void
    {
        $this->request = $request;
    }

487
488
489
490
491
492
493
494
495
496
    /**
     * 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);
497
        unset($vars['typoScriptFrontendController'], $vars['logger'], $vars['container'], $vars['request']);
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
        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 ($this->currentFile !== null && is_string($this->currentFile)) {
519
            [$objectType, $identifier] = explode(':', $this->currentFile, 2);
520
521
            try {
                if ($objectType === 'File') {
522
                    $this->currentFile = GeneralUtility::makeInstance(ResourceFactory::class)->retrieveFileOrFolderObject($identifier);
523
                } elseif ($objectType === 'FileReference') {
524
                    $this->currentFile = GeneralUtility::makeInstance(ResourceFactory::class)->getFileReferenceObject($identifier);
525
526
527
528
529
                }
            } catch (ResourceDoesNotExistException $e) {
                $this->currentFile = null;
            }
        }
530
        $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
531
        $this->container = GeneralUtility::getContainer();
532
533
534
535

        // We do not derive $this->request from globals here. The request is expected to be injected
        // using setRequest() after deserialization or with start().
        // (A fallback to $GLOBALS['TYPO3_REQUEST'] is available in getRequest() for BC)
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    }

    /**
     * Allow injecting content object class map.
     *
     * This method is private API, please use configuration
     * $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'] to add new content objects
     *
     * @internal
     * @param array $contentObjectClassMap
     */
    public function setContentObjectClassMap(array $contentObjectClassMap)
    {
        $this->contentObjectClassMap = $contentObjectClassMap;
    }

    /**
     * Register a single content object name to class name
     *
     * This method is private API, please use configuration
     * $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'] to add new content objects
     *
     * @param string $className
     * @param string $contentObjectName
560
     * @internal
561
562
563
564
565
566
567
568
569
570
571
572
573
     */
    public function registerContentObjectClass($className, $contentObjectName)
    {
        $this->contentObjectClassMap[$contentObjectName] = $className;
    }

    /**
     * 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.
574
     * @param ServerRequestInterface|null $request
575
     */
576
    public function start($data, $table = '', ?ServerRequestInterface $request = null)
577
    {
578
        $this->request = $request ?? $this->request;
579
580
        $this->data = $data;
        $this->table = $table;
581
582
583
        $this->currentRecord = $table !== ''
            ? $table . ':' . ($this->data['uid'] ?? '')
            : '';
584
585
        $this->parameters = [];
        $this->stdWrapHookObjects = [];
586
587
588
589
        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);
590
            }
591
            $this->stdWrapHookObjects[] = $hookObject;
592
        }
593
594
595
596
        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);
597
            }
598
            $postInitializationProcessor->postProcessContentObjectInitialization($this);
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
        }
    }

    /**
     * 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)) {
621
            $this->getImgResourceHookObjects = [];
622
623
624
625
            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);
626
                }
627
                $this->getImgResourceHookObjects[] = $hookObject;
628
629
630
631
632
633
634
635
636
637
638
            }
        }
        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.
639
     * @internal
640
641
642
     */
    public function setParent($data, $currentRecord)
    {
643
        $this->parentRecord = [
644
            'data' => $data,
645
            'currentRecord' => $currentRecord,
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
    }

    /***********************************************
     *
     * 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];
    }

    /**
     * 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 '';
        }
692
        $sKeyArray = ArrayUtility::filterAndSortByNumericKeys($setup);
693
694
695
        $content = '';
        foreach ($sKeyArray as $theKey) {
            $theValue = $setup[$theKey];
696
            if ((int)$theKey && !str_contains($theKey, '.')) {
697
                $conf = $setup[$theKey . '.'] ?? [];
698
699
700
701
702
703
704
705
706
                $content .= $this->cObjGetSingle($theValue, $conf, $addKey . $theKey);
            }
        }
        return $content;
    }

    /**
     * Renders a content object
     *
707
     * @param string $name The content object name, eg. "TEXT" or "USER" or "IMAGE"
708
709
710
711
712
713
714
715
     * @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($name, $conf, $TSkey = '__')
    {
        $content = '';
716
717
718
719
720
721
722
723
724
725
726
727
        $timeTracker = $this->getTimeTracker();
        $name = trim($name);
        if ($timeTracker->LR) {
            $timeTracker->push($TSkey, $name);
        }
        // Checking if the COBJ is a reference to another object. (eg. name of 'some.object =< styles.something')
        if (isset($name[0]) && $name[0] === '<') {
            $key = trim(substr($name, 1));
            $cF = GeneralUtility::makeInstance(TypoScriptParser::class);
            // $name and $conf is loaded with the referenced values.
            $confOverride = is_array($conf) ? $conf : [];
            [$name, $conf] = $cF->getVal($key, $this->getTypoScriptFrontendController()->tmpl->setup);
728
            $conf = array_replace_recursive($conf, $confOverride);
729
730
731
732
733
734
735
736
            // Getting the cObject
            $timeTracker->incStackPointer();
            $content .= $this->cObjGetSingle($name, $conf, $key);
            $timeTracker->decStackPointer();
        } else {
            $contentObject = $this->getContentObject($name);
            if ($contentObject) {
                $content .= $this->render($contentObject, $conf);
737
738
            }
        }
739
740
741
        if ($timeTracker->LR) {
            $timeTracker->pull($content);
        }
742
743
744
745
746
747
748
749
750
        return $content;
    }

    /**
     * Returns a new content object of type $name.
     * This content object needs to be registered as content object
     * in $this->contentObjectClassMap
     *
     * @param string $name
751
     * @return AbstractContentObject|null
752
753
754
755
756
757
758
759
760
761
     * @throws ContentRenderingException
     */
    public function getContentObject($name)
    {
        if (!isset($this->contentObjectClassMap[$name])) {
            return null;
        }
        $fullyQualifiedClassName = $this->contentObjectClassMap[$name];
        $contentObject = GeneralUtility::makeInstance($fullyQualifiedClassName, $this);
        if (!($contentObject instanceof AbstractContentObject)) {
762
            throw new ContentRenderingException(sprintf('Registered content object class name "%s" must be an instance of AbstractContentObject, but is not!', $fullyQualifiedClassName), 1422564295);
763
        }
764
        $contentObject->setRequest($this->getRequest());
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
        return $contentObject;
    }

    /********************************************
     *
     * 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
     * @return string
     */
784
    public function render(AbstractContentObject $contentObject, $configuration = [])
785
786
787
788
    {
        $content = '';

        // Evaluate possible cache and return
789
        $cacheConfiguration = $configuration['cache.'] ?? null;
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
        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 (\Exception $exception) {
            $exceptionHandler = $this->createExceptionHandler($configuration);
            if ($exceptionHandler === null) {
                throw $exception;
            }
810
            $content = $exceptionHandler->handle($exception, $contentObject, $configuration);
811
812
813
        }

        // Store cache
814
        if ($cacheConfiguration !== null && !$this->getTypoScriptFrontendController()->no_cache) {
815
816
            $key = $this->calculateCacheKey($cacheConfiguration);
            if (!empty($key)) {
817
                /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $cacheFrontend */
818
                $cacheFrontend = GeneralUtility::makeInstance(CacheManager::class)->getCache('hash');
819
820
821
822
823
824
825
826
827
828
829
830
831
832
                $tags = $this->calculateCacheTags($cacheConfiguration);
                $lifetime = $this->calculateCacheLifetime($cacheConfiguration);
                $cacheFrontend->set($key, $content, $tags, $lifetime);
            }
        }

        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
833
     * @return ExceptionHandlerInterface|null
834
835
     * @throws ContentRenderingException
     */
836
    protected function createExceptionHandler($configuration = [])
837
838
839
840
    {
        $exceptionHandler = null;
        $exceptionHandlerClassName = $this->determineExceptionHandlerClassName($configuration);
        if (!empty($exceptionHandlerClassName)) {
841
842
843
844
845
846
847
848
849
850
            if (method_exists($exceptionHandlerClassName, 'setConfiguration')) {
                $exceptionHandler = GeneralUtility::makeInstance($exceptionHandlerClassName);
                $exceptionHandler->setConfiguration($this->mergeExceptionHandlerConfiguration($configuration));
            } else {
                trigger_error(
                    'Passing the TypoScript configuration as constructor argument to ' . $exceptionHandlerClassName . ' is deprecated and will stop working in TYPO3 v12.0. Exception handler classes therefore have to implement the setConfiguration() method.',
                    E_USER_DEPRECATED
                );
                $exceptionHandler = GeneralUtility::makeInstance($exceptionHandlerClassName, $this->mergeExceptionHandlerConfiguration($configuration));
            }
851
852
853
854
855
856
857
858
859
860
861
862
            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);
            }
        }

        return $exceptionHandler;
    }

    /**
     * Determine exception handler class name from global and content object configuration
     *
     * @param array $configuration
863
     * @return string|null
864
865
866
867
868
869
     */
    protected function determineExceptionHandlerClassName($configuration)
    {
        $exceptionHandlerClassName = null;
        $tsfe = $this->getTypoScriptFrontendController();
        if (!isset($tsfe->config['config']['contentObjectExceptionHandler'])) {
870
            if (Environment::getContext()->isProduction()) {
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
                $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)
    {
897
        $exceptionHandlerConfiguration = [];
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
        $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) {
938
            $this->getTimeTracker()->setTSlogMessage(self::class . '::convertToUserIntObject() is called in the wrong context or for the wrong object type', LogLevel::WARNING);
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
        } 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
1000
     * @internal
For faster browsing, not all history is shown. View entire blame