[TASK] Add more fixers for php-cs-fixer
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / ContentObject / ContentObjectRenderer.php
1 <?php
2 namespace TYPO3\CMS\Frontend\ContentObject;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Doctrine\DBAL\DBALException;
18 use TYPO3\CMS\Core\Cache\CacheManager;
19 use TYPO3\CMS\Core\Charset\CharsetConverter;
20 use TYPO3\CMS\Core\Database\ConnectionPool;
21 use TYPO3\CMS\Core\Database\Query\QueryHelper;
22 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
23 use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
24 use TYPO3\CMS\Core\FrontendEditing\FrontendEditingController;
25 use TYPO3\CMS\Core\Html\HtmlParser;
26 use TYPO3\CMS\Core\LinkHandling\LinkService;
27 use TYPO3\CMS\Core\Log\LogManager;
28 use TYPO3\CMS\Core\Mail\MailMessage;
29 use TYPO3\CMS\Core\Resource\Exception;
30 use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
31 use TYPO3\CMS\Core\Resource\File;
32 use TYPO3\CMS\Core\Resource\FileInterface;
33 use TYPO3\CMS\Core\Resource\FileReference;
34 use TYPO3\CMS\Core\Resource\Folder;
35 use TYPO3\CMS\Core\Resource\ProcessedFile;
36 use TYPO3\CMS\Core\Resource\ResourceFactory;
37 use TYPO3\CMS\Core\Service\DependencyOrderingService;
38 use TYPO3\CMS\Core\Service\MarkerBasedTemplateService;
39 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
40 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
41 use TYPO3\CMS\Core\Utility\ArrayUtility;
42 use TYPO3\CMS\Core\Utility\DebugUtility;
43 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
44 use TYPO3\CMS\Core\Utility\GeneralUtility;
45 use TYPO3\CMS\Core\Utility\HttpUtility;
46 use TYPO3\CMS\Core\Utility\MailUtility;
47 use TYPO3\CMS\Core\Utility\MathUtility;
48 use TYPO3\CMS\Core\Utility\StringUtility;
49 use TYPO3\CMS\Core\Versioning\VersionState;
50 use TYPO3\CMS\Frontend\ContentObject\Exception\ContentRenderingException;
51 use TYPO3\CMS\Frontend\ContentObject\Exception\ExceptionHandlerInterface;
52 use TYPO3\CMS\Frontend\ContentObject\Exception\ProductionExceptionHandler;
53 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
54 use TYPO3\CMS\Frontend\Http\UrlProcessorInterface;
55 use TYPO3\CMS\Frontend\Imaging\GifBuilder;
56 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
57 use TYPO3\CMS\Frontend\Page\PageRepository;
58 use TYPO3\CMS\Frontend\Service\TypoLinkCodecService;
59
60 /**
61 * This class contains all main TypoScript features.
62 * This includes the rendering of TypoScript content objects (cObjects).
63 * Is the backbone of TypoScript Template rendering.
64 *
65 * There are lots of functions you can use from your include-scripts.
66 * The class is normally instantiated and referred to as "cObj".
67 * 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.
68 */
69 class ContentObjectRenderer
70 {
71 /**
72 * @var array
73 */
74 public $align = [
75 'center',
76 'right',
77 'left'
78 ];
79
80 /**
81 * stdWrap functions in their correct order
82 *
83 * @see stdWrap()
84 */
85 public $stdWrapOrder = [
86 'stdWrapPreProcess' => 'hook',
87 // this is a placeholder for the first Hook
88 'cacheRead' => 'hook',
89 // this is a placeholder for checking if the content is available in cache
90 'setContentToCurrent' => 'boolean',
91 'setContentToCurrent.' => 'array',
92 'addPageCacheTags' => 'string',
93 'addPageCacheTags.' => 'array',
94 'setCurrent' => 'string',
95 'setCurrent.' => 'array',
96 'lang.' => 'array',
97 'data' => 'getText',
98 'data.' => 'array',
99 'field' => 'fieldName',
100 'field.' => 'array',
101 'current' => 'boolean',
102 'current.' => 'array',
103 'cObject' => 'cObject',
104 'cObject.' => 'array',
105 'numRows.' => 'array',
106 'filelist' => 'dir',
107 'filelist.' => 'array',
108 'preUserFunc' => 'functionName',
109 'stdWrapOverride' => 'hook',
110 // this is a placeholder for the second Hook
111 'override' => 'string',
112 'override.' => 'array',
113 'preIfEmptyListNum' => 'listNum',
114 'preIfEmptyListNum.' => 'array',
115 'ifNull' => 'string',
116 'ifNull.' => 'array',
117 'ifEmpty' => 'string',
118 'ifEmpty.' => 'array',
119 'ifBlank' => 'string',
120 'ifBlank.' => 'array',
121 'listNum' => 'listNum',
122 'listNum.' => 'array',
123 'trim' => 'boolean',
124 'trim.' => 'array',
125 'strPad.' => 'array',
126 'stdWrap' => 'stdWrap',
127 'stdWrap.' => 'array',
128 'stdWrapProcess' => 'hook',
129 // this is a placeholder for the third Hook
130 'required' => 'boolean',
131 'required.' => 'array',
132 'if.' => 'array',
133 'fieldRequired' => 'fieldName',
134 'fieldRequired.' => 'array',
135 'csConv' => 'string',
136 'csConv.' => 'array',
137 'parseFunc' => 'objectpath',
138 'parseFunc.' => 'array',
139 'HTMLparser' => 'boolean',
140 'HTMLparser.' => 'array',
141 'split.' => 'array',
142 'replacement.' => 'array',
143 'prioriCalc' => 'boolean',
144 'prioriCalc.' => 'array',
145 'char' => 'integer',
146 'char.' => 'array',
147 'intval' => 'boolean',
148 'intval.' => 'array',
149 'hash' => 'string',
150 'hash.' => 'array',
151 'round' => 'boolean',
152 'round.' => 'array',
153 'numberFormat.' => 'array',
154 'expandList' => 'boolean',
155 'expandList.' => 'array',
156 'date' => 'dateconf',
157 'date.' => 'array',
158 'strtotime' => 'strtotimeconf',
159 'strtotime.' => 'array',
160 'strftime' => 'strftimeconf',
161 'strftime.' => 'array',
162 'age' => 'boolean',
163 'age.' => 'array',
164 'case' => 'case',
165 'case.' => 'array',
166 'bytes' => 'boolean',
167 'bytes.' => 'array',
168 'substring' => 'parameters',
169 'substring.' => 'array',
170 'removeBadHTML' => 'boolean',
171 'removeBadHTML.' => 'array',
172 'cropHTML' => 'crop',
173 'cropHTML.' => 'array',
174 'stripHtml' => 'boolean',
175 'stripHtml.' => 'array',
176 'crop' => 'crop',
177 'crop.' => 'array',
178 'rawUrlEncode' => 'boolean',
179 'rawUrlEncode.' => 'array',
180 'htmlSpecialChars' => 'boolean',
181 'htmlSpecialChars.' => 'array',
182 'encodeForJavaScriptValue' => 'boolean',
183 'encodeForJavaScriptValue.' => 'array',
184 'doubleBrTag' => 'string',
185 'doubleBrTag.' => 'array',
186 'br' => 'boolean',
187 'br.' => 'array',
188 'brTag' => 'string',
189 'brTag.' => 'array',
190 'encapsLines.' => 'array',
191 'keywords' => 'boolean',
192 'keywords.' => 'array',
193 'innerWrap' => 'wrap',
194 'innerWrap.' => 'array',
195 'innerWrap2' => 'wrap',
196 'innerWrap2.' => 'array',
197 'fontTag' => 'wrap',
198 'fontTag.' => 'array',
199 'addParams.' => 'array',
200 'filelink.' => 'array',
201 'preCObject' => 'cObject',
202 'preCObject.' => 'array',
203 'postCObject' => 'cObject',
204 'postCObject.' => 'array',
205 'wrapAlign' => 'align',
206 'wrapAlign.' => 'array',
207 'typolink.' => 'array',
208 'TCAselectItem.' => 'array',
209 'space' => 'space',
210 'space.' => 'array',
211 'spaceBefore' => 'int',
212 'spaceBefore.' => 'array',
213 'spaceAfter' => 'int',
214 'spaceAfter.' => 'array',
215 'wrap' => 'wrap',
216 'wrap.' => 'array',
217 'noTrimWrap' => 'wrap',
218 'noTrimWrap.' => 'array',
219 'wrap2' => 'wrap',
220 'wrap2.' => 'array',
221 'dataWrap' => 'dataWrap',
222 'dataWrap.' => 'array',
223 'prepend' => 'cObject',
224 'prepend.' => 'array',
225 'append' => 'cObject',
226 'append.' => 'array',
227 'wrap3' => 'wrap',
228 'wrap3.' => 'array',
229 'orderedStdWrap' => 'stdWrap',
230 'orderedStdWrap.' => 'array',
231 'outerWrap' => 'wrap',
232 'outerWrap.' => 'array',
233 'insertData' => 'boolean',
234 'insertData.' => 'array',
235 'postUserFunc' => 'functionName',
236 'postUserFuncInt' => 'functionName',
237 'prefixComment' => 'string',
238 'prefixComment.' => 'array',
239 'editIcons' => 'string',
240 'editIcons.' => 'array',
241 'editPanel' => 'boolean',
242 'editPanel.' => 'array',
243 'cacheStore' => 'hook',
244 // this is a placeholder for storing the content in cache
245 'stdWrapPostProcess' => 'hook',
246 // this is a placeholder for the last Hook
247 'debug' => 'boolean',
248 'debug.' => 'array',
249 'debugFunc' => 'boolean',
250 'debugFunc.' => 'array',
251 'debugData' => 'boolean',
252 'debugData.' => 'array'
253 ];
254
255 /**
256 * Class names for accordant content object names
257 *
258 * @var array
259 */
260 protected $contentObjectClassMap = [];
261
262 /**
263 * Holds ImageMagick parameters and extensions used for compression
264 *
265 * @var array
266 * @see IMGTEXT()
267 */
268 public $image_compression = [
269 10 => [
270 'params' => '',
271 'ext' => 'gif'
272 ],
273 11 => [
274 'params' => '-colors 128',
275 'ext' => 'gif'
276 ],
277 12 => [
278 'params' => '-colors 64',
279 'ext' => 'gif'
280 ],
281 13 => [
282 'params' => '-colors 32',
283 'ext' => 'gif'
284 ],
285 14 => [
286 'params' => '-colors 16',
287 'ext' => 'gif'
288 ],
289 15 => [
290 'params' => '-colors 8',
291 'ext' => 'gif'
292 ],
293 20 => [
294 'params' => '-quality 100',
295 'ext' => 'jpg'
296 ],
297 21 => [
298 'params' => '-quality 90',
299 'ext' => 'jpg'
300 ],
301 22 => [
302 'params' => '-quality 80',
303 'ext' => 'jpg'
304 ],
305 23 => [
306 'params' => '-quality 70',
307 'ext' => 'jpg'
308 ],
309 24 => [
310 'params' => '-quality 60',
311 'ext' => 'jpg'
312 ],
313 25 => [
314 'params' => '-quality 50',
315 'ext' => 'jpg'
316 ],
317 26 => [
318 'params' => '-quality 40',
319 'ext' => 'jpg'
320 ],
321 27 => [
322 'params' => '-quality 30',
323 'ext' => 'jpg'
324 ],
325 28 => [
326 'params' => '-quality 20',
327 'ext' => 'jpg'
328 ],
329 30 => [
330 'params' => '-colors 256',
331 'ext' => 'png'
332 ],
333 31 => [
334 'params' => '-colors 128',
335 'ext' => 'png'
336 ],
337 32 => [
338 'params' => '-colors 64',
339 'ext' => 'png'
340 ],
341 33 => [
342 'params' => '-colors 32',
343 'ext' => 'png'
344 ],
345 34 => [
346 'params' => '-colors 16',
347 'ext' => 'png'
348 ],
349 35 => [
350 'params' => '-colors 8',
351 'ext' => 'png'
352 ],
353 39 => [
354 'params' => '',
355 'ext' => 'png'
356 ]
357 ];
358
359 /**
360 * ImageMagick parameters for image effects
361 *
362 * @var array
363 * @see IMGTEXT()
364 */
365 public $image_effects = [
366 1 => '-rotate 90',
367 2 => '-rotate 270',
368 3 => '-rotate 180',
369 10 => '-colorspace GRAY',
370 11 => '-sharpen 70',
371 20 => '-normalize',
372 23 => '-contrast',
373 25 => '-gamma 1.3',
374 26 => '-gamma 0.8'
375 ];
376
377 /**
378 * Loaded with the current data-record.
379 *
380 * If the instance of this class is used to render records from the database those records are found in this array.
381 * The function stdWrap has TypoScript properties that fetch field-data from this array.
382 *
383 * @var array
384 * @see start()
385 */
386 public $data = [];
387
388 /**
389 * @var string
390 */
391 protected $table = '';
392
393 /**
394 * Used for backup
395 *
396 * @var array
397 */
398 public $oldData = [];
399
400 /**
401 * If this is set with an array before stdWrap, it's used instead of $this->data in the data-property in stdWrap
402 *
403 * @var string
404 */
405 public $alternativeData = '';
406
407 /**
408 * Used by the parseFunc function and is loaded with tag-parameters when parsing tags.
409 *
410 * @var array
411 */
412 public $parameters = [];
413
414 /**
415 * @var string
416 */
417 public $currentValKey = 'currentValue_kidjls9dksoje';
418
419 /**
420 * This is set to the [table]:[uid] of the record delivered in the $data-array, if the cObjects CONTENT or RECORD is in operation.
421 * Note that $GLOBALS['TSFE']->currentRecord is set to an equal value but always indicating the latest record rendered.
422 *
423 * @var string
424 */
425 public $currentRecord = '';
426
427 /**
428 * Set in RecordsContentObject and ContentContentObject to the current number of records selected in a query.
429 *
430 * @var int
431 */
432 public $currentRecordTotal = 0;
433
434 /**
435 * Incremented in RecordsContentObject and ContentContentObject before each record rendering.
436 *
437 * @var int
438 */
439 public $currentRecordNumber = 0;
440
441 /**
442 * Incremented in RecordsContentObject and ContentContentObject before each record rendering.
443 *
444 * @var int
445 */
446 public $parentRecordNumber = 0;
447
448 /**
449 * 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.
450 *
451 * @var array
452 */
453 public $parentRecord = [];
454
455 /**
456 * This is used by checkPid, that checks if pages are accessible. The $checkPid_cache['page_uid'] is set TRUE or FALSE upon this check featuring a caching function for the next request.
457 *
458 * @var array
459 */
460 public $checkPid_cache = [];
461
462 /**
463 * @var string
464 */
465 public $checkPid_badDoktypeList = '255';
466
467 /**
468 * This will be set by typoLink() to the url of the most recent link created.
469 *
470 * @var string
471 */
472 public $lastTypoLinkUrl = '';
473
474 /**
475 * DO. link target.
476 *
477 * @var string
478 */
479 public $lastTypoLinkTarget = '';
480
481 /**
482 * @var array
483 */
484 public $lastTypoLinkLD = [];
485
486 /**
487 * Caching substituteMarkerArrayCached function
488 *
489 * @var array
490 */
491 public $substMarkerCache = [];
492
493 /**
494 * array that registers rendered content elements (or any table) to make sure they are not rendered recursively!
495 *
496 * @var array
497 */
498 public $recordRegister = [];
499
500 /**
501 * Additionally registered content object types and class names
502 *
503 * @var array
504 */
505 protected $cObjHookObjectsRegistry = [];
506
507 /**
508 * @var array
509 */
510 public $cObjHookObjectsArr = [];
511
512 /**
513 * Containing hook objects for stdWrap
514 *
515 * @var array
516 */
517 protected $stdWrapHookObjects = [];
518
519 /**
520 * Containing hook objects for getImgResource
521 *
522 * @var array
523 */
524 protected $getImgResourceHookObjects;
525
526 /**
527 * @var File Current file objects (during iterations over files)
528 */
529 protected $currentFile = null;
530
531 /**
532 * Set to TRUE by doConvertToUserIntObject() if USER object wants to become USER_INT
533 */
534 public $doConvertToUserIntObject = false;
535
536 /**
537 * Indicates current object type. Can hold one of OBJECTTYPE_ constants or FALSE.
538 * The value is set and reset inside USER() function. Any time outside of
539 * USER() it is FALSE.
540 */
541 protected $userObjectType = false;
542
543 /**
544 * @var array
545 */
546 protected $stopRendering = [];
547
548 /**
549 * @var int
550 */
551 protected $stdWrapRecursionLevel = 0;
552
553 /**
554 * @var TypoScriptFrontendController
555 */
556 protected $typoScriptFrontendController;
557
558 /**
559 * @var MarkerBasedTemplateService
560 */
561 protected $templateService;
562
563 /**
564 * Indicates that object type is USER.
565 *
566 * @see ContentObjectRender::$userObjectType
567 */
568 const OBJECTTYPE_USER_INT = 1;
569 /**
570 * Indicates that object type is USER.
571 *
572 * @see ContentObjectRender::$userObjectType
573 */
574 const OBJECTTYPE_USER = 2;
575
576 /**
577 * @param TypoScriptFrontendController $typoScriptFrontendController
578 */
579 public function __construct(TypoScriptFrontendController $typoScriptFrontendController = null)
580 {
581 $this->typoScriptFrontendController = $typoScriptFrontendController;
582 $this->contentObjectClassMap = $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'];
583 $this->templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
584 }
585
586 /**
587 * Prevent several objects from being serialized.
588 * If currentFile is set, it is either a File or a FileReference object. As the object itself can't be serialized,
589 * we have store a hash and restore the object in __wakeup()
590 *
591 * @return array
592 */
593 public function __sleep()
594 {
595 $vars = get_object_vars($this);
596 unset($vars['typoScriptFrontendController']);
597 if ($this->currentFile instanceof FileReference) {
598 $this->currentFile = 'FileReference:' . $this->currentFile->getUid();
599 } elseif ($this->currentFile instanceof File) {
600 $this->currentFile = 'File:' . $this->currentFile->getIdentifier();
601 } else {
602 unset($vars['currentFile']);
603 }
604 return array_keys($vars);
605 }
606
607 /**
608 * Restore currentFile from hash.
609 * If currentFile references a File, the identifier equals file identifier.
610 * If it references a FileReference the identifier equals the uid of the reference.
611 */
612 public function __wakeup()
613 {
614 if (isset($GLOBALS['TSFE'])) {
615 $this->typoScriptFrontendController = $GLOBALS['TSFE'];
616 }
617 if ($this->currentFile !== null && is_string($this->currentFile)) {
618 list($objectType, $identifier) = explode(':', $this->currentFile, 2);
619 try {
620 if ($objectType === 'File') {
621 $this->currentFile = ResourceFactory::getInstance()->retrieveFileOrFolderObject($identifier);
622 } elseif ($objectType === 'FileReference') {
623 $this->currentFile = ResourceFactory::getInstance()->getFileReferenceObject($identifier);
624 }
625 } catch (ResourceDoesNotExistException $e) {
626 $this->currentFile = null;
627 }
628 }
629 }
630
631 /**
632 * Allow injecting content object class map.
633 *
634 * This method is private API, please use configuration
635 * $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'] to add new content objects
636 *
637 * @internal
638 * @param array $contentObjectClassMap
639 */
640 public function setContentObjectClassMap(array $contentObjectClassMap)
641 {
642 $this->contentObjectClassMap = $contentObjectClassMap;
643 }
644
645 /**
646 * Register a single content object name to class name
647 *
648 * This method is private API, please use configuration
649 * $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'] to add new content objects
650 *
651 * @internal
652 * @param string $className
653 * @param string $contentObjectName
654 */
655 public function registerContentObjectClass($className, $contentObjectName)
656 {
657 $this->contentObjectClassMap[$contentObjectName] = $className;
658 }
659
660 /**
661 * Class constructor.
662 * Well, it has to be called manually since it is not a real constructor function.
663 * 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.
664 *
665 * @param array $data The record data that is rendered.
666 * @param string $table The table that the data record is from.
667 * @return void
668 */
669 public function start($data, $table = '')
670 {
671 $this->data = $data;
672 $this->table = $table;
673 $this->currentRecord = $table !== '' ? $table . ':' . $this->data['uid'] : '';
674 $this->parameters = [];
675 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['cObjTypeAndClass'])) {
676 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['cObjTypeAndClass'] as $classArr) {
677 $this->cObjHookObjectsRegistry[$classArr[0]] = $classArr[1];
678 }
679 }
680 $this->stdWrapHookObjects = [];
681 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['stdWrap'])) {
682 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['stdWrap'] as $classData) {
683 $hookObject = GeneralUtility::getUserObj($classData);
684 if (!$hookObject instanceof ContentObjectStdWrapHookInterface) {
685 throw new \UnexpectedValueException($classData . ' must implement interface ' . ContentObjectStdWrapHookInterface::class, 1195043965);
686 }
687 $this->stdWrapHookObjects[] = $hookObject;
688 }
689 }
690 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['postInit'])) {
691 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['postInit'] as $classData) {
692 $postInitializationProcessor = GeneralUtility::getUserObj($classData);
693 if (!$postInitializationProcessor instanceof ContentObjectPostInitHookInterface) {
694 throw new \UnexpectedValueException($classData . ' must implement interface ' . ContentObjectPostInitHookInterface::class, 1274563549);
695 }
696 $postInitializationProcessor->postProcessContentObjectInitialization($this);
697 }
698 }
699 }
700
701 /**
702 * Returns the current table
703 *
704 * @return string
705 */
706 public function getCurrentTable()
707 {
708 return $this->table;
709 }
710
711 /**
712 * Gets the 'getImgResource' hook objects.
713 * The first call initializes the accordant objects.
714 *
715 * @return array The 'getImgResource' hook objects (if any)
716 */
717 protected function getGetImgResourceHookObjects()
718 {
719 if (!isset($this->getImgResourceHookObjects)) {
720 $this->getImgResourceHookObjects = [];
721 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['getImgResource'])) {
722 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['getImgResource'] as $classData) {
723 $hookObject = GeneralUtility::getUserObj($classData);
724 if (!$hookObject instanceof ContentObjectGetImageResourceHookInterface) {
725 throw new \UnexpectedValueException('$hookObject must implement interface ' . ContentObjectGetImageResourceHookInterface::class, 1218636383);
726 }
727 $this->getImgResourceHookObjects[] = $hookObject;
728 }
729 }
730 }
731 return $this->getImgResourceHookObjects;
732 }
733
734 /**
735 * Sets the internal variable parentRecord with information about current record.
736 * 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.
737 *
738 * @param array $data The record array
739 * @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.
740 * @return void
741 * @access private
742 */
743 public function setParent($data, $currentRecord)
744 {
745 $this->parentRecord = [
746 'data' => $data,
747 'currentRecord' => $currentRecord
748 ];
749 }
750
751 /***********************************************
752 *
753 * CONTENT_OBJ:
754 *
755 ***********************************************/
756 /**
757 * Returns the "current" value.
758 * 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.
759 * It's like "load accumulator" in the good old C64 days... basically a "register" you can use as you like.
760 * 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.
761 *
762 * @return mixed The "current" value
763 */
764 public function getCurrentVal()
765 {
766 return $this->data[$this->currentValKey];
767 }
768
769 /**
770 * Sets the "current" value.
771 *
772 * @param mixed $value The variable that you want to set as "current
773 * @return void
774 * @see getCurrentVal()
775 */
776 public function setCurrentVal($value)
777 {
778 $this->data[$this->currentValKey] = $value;
779 }
780
781 /**
782 * Rendering of a "numerical array" of cObjects from TypoScript
783 * Will call ->cObjGetSingle() for each cObject found and accumulate the output.
784 *
785 * @param array $setup array with cObjects as values.
786 * @param string $addKey A prefix for the debugging information
787 * @return string Rendered output from the cObjects in the array.
788 * @see cObjGetSingle()
789 */
790 public function cObjGet($setup, $addKey = '')
791 {
792 if (!is_array($setup)) {
793 return '';
794 }
795 $sKeyArray = ArrayUtility::filterAndSortByNumericKeys($setup);
796 $content = '';
797 foreach ($sKeyArray as $theKey) {
798 $theValue = $setup[$theKey];
799 if ((int)$theKey && strpos($theKey, '.') === false) {
800 $conf = $setup[$theKey . '.'];
801 $content .= $this->cObjGetSingle($theValue, $conf, $addKey . $theKey);
802 }
803 }
804 return $content;
805 }
806
807 /**
808 * Renders a content object
809 *
810 * @param string $name The content object name, eg. "TEXT" or "USER" or "IMAGE
811 * @param array $conf The array with TypoScript properties for the content object
812 * @param string $TSkey A string label used for the internal debugging tracking.
813 * @return string cObject output
814 * @throws \UnexpectedValueException
815 */
816 public function cObjGetSingle($name, $conf, $TSkey = '__')
817 {
818 $content = '';
819 // Checking that the function is not called eternally. This is done by interrupting at a depth of 100
820 $this->getTypoScriptFrontendController()->cObjectDepthCounter--;
821 if ($this->getTypoScriptFrontendController()->cObjectDepthCounter > 0) {
822 $timeTracker = $this->getTimeTracker();
823 $name = trim($name);
824 if ($timeTracker->LR) {
825 $timeTracker->push($TSkey, $name);
826 }
827 // Checking if the COBJ is a reference to another object. (eg. name of 'blabla.blabla = < styles.something')
828 if ($name[0] === '<') {
829 $key = trim(substr($name, 1));
830 $cF = GeneralUtility::makeInstance(TypoScriptParser::class);
831 // $name and $conf is loaded with the referenced values.
832 $confOverride = is_array($conf) ? $conf : [];
833 list($name, $conf) = $cF->getVal($key, $this->getTypoScriptFrontendController()->tmpl->setup);
834 $conf = array_replace_recursive(is_array($conf) ? $conf : [], $confOverride);
835 // Getting the cObject
836 $timeTracker->incStackPointer();
837 $content .= $this->cObjGetSingle($name, $conf, $key);
838 $timeTracker->decStackPointer();
839 } else {
840 $hooked = false;
841 // Application defined cObjects
842 if (!empty($this->cObjHookObjectsRegistry[$name])) {
843 if (empty($this->cObjHookObjectsArr[$name])) {
844 $this->cObjHookObjectsArr[$name] = GeneralUtility::getUserObj($this->cObjHookObjectsRegistry[$name]);
845 }
846 $hookObj = $this->cObjHookObjectsArr[$name];
847 if (method_exists($hookObj, 'cObjGetSingleExt')) {
848 $content .= $hookObj->cObjGetSingleExt($name, $conf, $TSkey, $this);
849 $hooked = true;
850 }
851 }
852 if (!$hooked) {
853 $contentObject = $this->getContentObject($name);
854 if ($contentObject) {
855 $content .= $this->render($contentObject, $conf);
856 } else {
857 // Call hook functions for extra processing
858 if ($name && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['cObjTypeAndClassDefault'])) {
859 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['cObjTypeAndClassDefault'] as $classData) {
860 $hookObject = GeneralUtility::getUserObj($classData);
861 if (!$hookObject instanceof ContentObjectGetSingleHookInterface) {
862 throw new \UnexpectedValueException('$hookObject must implement interface ' . ContentObjectGetSingleHookInterface::class, 1195043731);
863 }
864 /** @var $hookObject ContentObjectGetSingleHookInterface */
865 $content .= $hookObject->getSingleContentObject($name, (array)$conf, $TSkey, $this);
866 }
867 } else {
868 // Log error in AdminPanel
869 $warning = sprintf('Content Object "%s" does not exist', $name);
870 $timeTracker->setTSlogMessage($warning, 2);
871 }
872 }
873 }
874 }
875 if ($timeTracker->LR) {
876 $timeTracker->pull($content);
877 }
878 }
879 // Increasing on exit...
880 $this->getTypoScriptFrontendController()->cObjectDepthCounter++;
881 return $content;
882 }
883
884 /**
885 * Returns a new content object of type $name.
886 * This content object needs to be registered as content object
887 * in $this->contentObjectClassMap
888 *
889 * @param string $name
890 * @return NULL|AbstractContentObject
891 * @throws ContentRenderingException
892 */
893 public function getContentObject($name)
894 {
895 if (!isset($this->contentObjectClassMap[$name])) {
896 return null;
897 }
898 $fullyQualifiedClassName = $this->contentObjectClassMap[$name];
899 $contentObject = GeneralUtility::makeInstance($fullyQualifiedClassName, $this);
900 if (!($contentObject instanceof AbstractContentObject)) {
901 throw new ContentRenderingException(sprintf('Registered content object class name "%s" must be an instance of AbstractContentObject, but is not!', $fullyQualifiedClassName), 1422564295);
902 }
903 return $contentObject;
904 }
905
906 /********************************************
907 *
908 * Functions rendering content objects (cObjects)
909 *
910 ********************************************/
911
912 /**
913 * Renders a content object by taking exception and cache handling
914 * into consideration
915 *
916 * @param AbstractContentObject $contentObject Content object instance
917 * @param array $configuration Array of TypoScript properties
918 *
919 * @throws ContentRenderingException
920 * @throws \Exception
921 * @return string
922 */
923 public function render(AbstractContentObject $contentObject, $configuration = [])
924 {
925 $content = '';
926
927 // Evaluate possible cache and return
928 $cacheConfiguration = isset($configuration['cache.']) ? $configuration['cache.'] : null;
929 if ($cacheConfiguration !== null) {
930 unset($configuration['cache.']);
931 $cache = $this->getFromCache($cacheConfiguration);
932 if ($cache !== false) {
933 return $cache;
934 }
935 }
936
937 // Render content
938 try {
939 $content .= $contentObject->render($configuration);
940 } catch (ContentRenderingException $exception) {
941 // Content rendering Exceptions indicate a critical problem which should not be
942 // caught e.g. when something went wrong with Exception handling itself
943 throw $exception;
944 } catch (\Exception $exception) {
945 $exceptionHandler = $this->createExceptionHandler($configuration);
946 if ($exceptionHandler === null) {
947 throw $exception;
948 } else {
949 $content = $exceptionHandler->handle($exception, $contentObject, $configuration);
950 }
951 }
952
953 // Store cache
954 if ($cacheConfiguration !== null) {
955 $key = $this->calculateCacheKey($cacheConfiguration);
956 if (!empty($key)) {
957 /** @var $cacheFrontend \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend */
958 $cacheFrontend = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash');
959 $tags = $this->calculateCacheTags($cacheConfiguration);
960 $lifetime = $this->calculateCacheLifetime($cacheConfiguration);
961 $cacheFrontend->set($key, $content, $tags, $lifetime);
962 }
963 }
964
965 return $content;
966 }
967
968 /**
969 * Creates the content object exception handler from local content object configuration
970 * or, from global configuration if not explicitly disabled in local configuration
971 *
972 * @param array $configuration
973 * @return NULL|ExceptionHandlerInterface
974 * @throws ContentRenderingException
975 */
976 protected function createExceptionHandler($configuration = [])
977 {
978 $exceptionHandler = null;
979 $exceptionHandlerClassName = $this->determineExceptionHandlerClassName($configuration);
980 if (!empty($exceptionHandlerClassName)) {
981 $exceptionHandler = GeneralUtility::makeInstance($exceptionHandlerClassName, $this->mergeExceptionHandlerConfiguration($configuration));
982 if (!$exceptionHandler instanceof ExceptionHandlerInterface) {
983 throw new ContentRenderingException('An exception handler was configured but the class does not exist or does not implement the ExceptionHandlerInterface', 1403653369);
984 }
985 }
986
987 return $exceptionHandler;
988 }
989
990 /**
991 * Determine exception handler class name from global and content object configuration
992 *
993 * @param array $configuration
994 * @return string|NULL
995 */
996 protected function determineExceptionHandlerClassName($configuration)
997 {
998 $exceptionHandlerClassName = null;
999 $tsfe = $this->getTypoScriptFrontendController();
1000 if (!isset($tsfe->config['config']['contentObjectExceptionHandler'])) {
1001 if (GeneralUtility::getApplicationContext()->isProduction()) {
1002 $exceptionHandlerClassName = '1';
1003 }
1004 } else {
1005 $exceptionHandlerClassName = $tsfe->config['config']['contentObjectExceptionHandler'];
1006 }
1007
1008 if (isset($configuration['exceptionHandler'])) {
1009 $exceptionHandlerClassName = $configuration['exceptionHandler'];
1010 }
1011
1012 if ($exceptionHandlerClassName === '1') {
1013 $exceptionHandlerClassName = ProductionExceptionHandler::class;
1014 }
1015
1016 return $exceptionHandlerClassName;
1017 }
1018
1019 /**
1020 * Merges global exception handler configuration with the one from the content object
1021 * and returns the merged exception handler configuration
1022 *
1023 * @param array $configuration
1024 * @return array
1025 */
1026 protected function mergeExceptionHandlerConfiguration($configuration)
1027 {
1028 $exceptionHandlerConfiguration = [];
1029 $tsfe = $this->getTypoScriptFrontendController();
1030 if (!empty($tsfe->config['config']['contentObjectExceptionHandler.'])) {
1031 $exceptionHandlerConfiguration = $tsfe->config['config']['contentObjectExceptionHandler.'];
1032 }
1033 if (!empty($configuration['exceptionHandler.'])) {
1034 $exceptionHandlerConfiguration = array_replace_recursive($exceptionHandlerConfiguration, $configuration['exceptionHandler.']);
1035 }
1036
1037 return $exceptionHandlerConfiguration;
1038 }
1039
1040 /**
1041 * Retrieves a type of object called as USER or USER_INT. Object can detect their
1042 * type by using this call. It returns OBJECTTYPE_USER_INT or OBJECTTYPE_USER depending on the
1043 * current object execution. In all other cases it will return FALSE to indicate
1044 * a call out of context.
1045 *
1046 * @return mixed One of OBJECTTYPE_ class constants or FALSE
1047 */
1048 public function getUserObjectType()
1049 {
1050 return $this->userObjectType;
1051 }
1052
1053 /**
1054 * Sets the user object type
1055 *
1056 * @param mixed $userObjectType
1057 * @return void
1058 */
1059 public function setUserObjectType($userObjectType)
1060 {
1061 $this->userObjectType = $userObjectType;
1062 }
1063
1064 /**
1065 * Requests the current USER object to be converted to USER_INT.
1066 *
1067 * @return void
1068 */
1069 public function convertToUserIntObject()
1070 {
1071 if ($this->userObjectType !== self::OBJECTTYPE_USER) {
1072 $this->getTimeTracker()->setTSlogMessage(self::class . '::convertToUserIntObject() is called in the wrong context or for the wrong object type', 2);
1073 } else {
1074 $this->doConvertToUserIntObject = true;
1075 }
1076 }
1077
1078 /************************************
1079 *
1080 * Various helper functions for content objects:
1081 *
1082 ************************************/
1083 /**
1084 * Converts a given config in Flexform to a conf-array
1085 *
1086 * @param string|array $flexData Flexform data
1087 * @param array $conf Array to write the data into, by reference
1088 * @param bool $recursive Is set if called recursive. Don't call function with this parameter, it's used inside the function only
1089 * @return void
1090 */
1091 public function readFlexformIntoConf($flexData, &$conf, $recursive = false)
1092 {
1093 if ($recursive === false && is_string($flexData)) {
1094 $flexData = GeneralUtility::xml2array($flexData, 'T3');
1095 }
1096 if (is_array($flexData) && isset($flexData['data']['sDEF']['lDEF'])) {
1097 $flexData = $flexData['data']['sDEF']['lDEF'];
1098 }
1099 if (!is_array($flexData)) {
1100 return;
1101 }
1102 foreach ($flexData as $key => $value) {
1103 if (!is_array($value)) {
1104 continue;
1105 }
1106 if (isset($value['el'])) {
1107 if (is_array($value['el']) && !empty($value['el'])) {
1108 foreach ($value['el'] as $ekey => $element) {
1109 if (isset($element['vDEF'])) {
1110 $conf[$ekey] = $element['vDEF'];
1111 } else {
1112 if (is_array($element)) {
1113 $this->readFlexformIntoConf($element, $conf[$key][key($element)][$ekey], true);
1114 } else {
1115 $this->readFlexformIntoConf($element, $conf[$key][$ekey], true);
1116 }
1117 }
1118 }
1119 } else {
1120 $this->readFlexformIntoConf($value['el'], $conf[$key], true);
1121 }
1122 }
1123 if (isset($value['vDEF'])) {
1124 $conf[$key] = $value['vDEF'];
1125 }
1126 }
1127 }
1128
1129 /**
1130 * Returns all parents of the given PID (Page UID) list
1131 *
1132 * @param string $pidList A list of page Content-Element PIDs (Page UIDs) / stdWrap
1133 * @param array $pidConf stdWrap array for the list
1134 * @return string A list of PIDs
1135 * @access private
1136 */
1137 public function getSlidePids($pidList, $pidConf)
1138 {
1139 $pidList = isset($pidConf) ? trim($this->stdWrap($pidList, $pidConf)) : trim($pidList);
1140 if ($pidList === '') {
1141 $pidList = 'this';
1142 }
1143 $tsfe = $this->getTypoScriptFrontendController();
1144 $listArr = null;
1145 if (trim($pidList)) {
1146 $listArr = GeneralUtility::intExplode(',', str_replace('this', $tsfe->contentPid, $pidList));
1147 $listArr = $this->checkPidArray($listArr);
1148 }
1149 $pidList = [];
1150 if (is_array($listArr) && !empty($listArr)) {
1151 foreach ($listArr as $uid) {
1152 $page = $tsfe->sys_page->getPage($uid);
1153 if (!$page['is_siteroot']) {
1154 $pidList[] = $page['pid'];
1155 }
1156 }
1157 }
1158 return implode(',', $pidList);
1159 }
1160
1161 /**
1162 * Returns a <img> tag with the image file defined by $file and processed according to the properties in the TypoScript array.
1163 * Mostly this function is a sub-function to the IMAGE function which renders the IMAGE cObject in TypoScript.
1164 * This function is called by "$this->cImage($conf['file'], $conf);" from IMAGE().
1165 *
1166 * @param string $file File TypoScript resource
1167 * @param array $conf TypoScript configuration properties
1168 * @return string <img> tag, (possibly wrapped in links and other HTML) if any image found.
1169 * @access private
1170 * @see IMAGE()
1171 */
1172 public function cImage($file, $conf)
1173 {
1174 $tsfe = $this->getTypoScriptFrontendController();
1175 $info = $this->getImgResource($file, $conf['file.']);
1176 $tsfe->lastImageInfo = $info;
1177 if (!is_array($info)) {
1178 return '';
1179 }
1180 if (is_file(PATH_site . $info['3'])) {
1181 $source = $tsfe->absRefPrefix . str_replace('%2F', '/', rawurlencode($info['3']));
1182 } else {
1183 $source = $info[3];
1184 }
1185
1186 $layoutKey = $this->stdWrap($conf['layoutKey'], $conf['layoutKey.']);
1187 $imageTagTemplate = $this->getImageTagTemplate($layoutKey, $conf);
1188 $sourceCollection = $this->getImageSourceCollection($layoutKey, $conf, $file);
1189
1190 // This array is used to collect the image-refs on the page...
1191 $tsfe->imagesOnPage[] = $source;
1192 $altParam = $this->getAltParam($conf);
1193 $params = $this->stdWrapValue('params', $conf);
1194 if ($params !== '' && $params[0] !== ' ') {
1195 $params = ' ' . $params;
1196 }
1197
1198 $imageTagValues = [
1199 'width' => (int)$info[0],
1200 'height' => (int)$info[1],
1201 'src' => htmlspecialchars($source),
1202 'params' => $params,
1203 'altParams' => $altParam,
1204 'border' => $this->getBorderAttr(' border="' . (int)$conf['border'] . '"'),
1205 'sourceCollection' => $sourceCollection,
1206 'selfClosingTagSlash' => (!empty($tsfe->xhtmlDoctype) ? ' /' : ''),
1207 ];
1208
1209 $theValue = $this->substituteMarkerArray($imageTagTemplate, $imageTagValues, '###|###', true, true);
1210
1211 $linkWrap = isset($conf['linkWrap.']) ? $this->stdWrap($conf['linkWrap'], $conf['linkWrap.']) : $conf['linkWrap'];
1212 if ($linkWrap) {
1213 $theValue = $this->linkWrap($theValue, $linkWrap);
1214 } elseif ($conf['imageLinkWrap']) {
1215 $originalFile = !empty($info['originalFile']) ? $info['originalFile'] : $info['origFile'];
1216 $theValue = $this->imageLinkWrap($theValue, $originalFile, $conf['imageLinkWrap.']);
1217 }
1218 $wrap = isset($conf['wrap.']) ? $this->stdWrap($conf['wrap'], $conf['wrap.']) : $conf['wrap'];
1219 if ((string)$wrap !== '') {
1220 $theValue = $this->wrap($theValue, $conf['wrap']);
1221 }
1222 return $theValue;
1223 }
1224
1225 /**
1226 * Returns the 'border' attribute for an <img> tag only if the doctype is not xhtml_strict, xhtml_11 or html5
1227 * or if the config parameter 'disableImgBorderAttr' is not set.
1228 *
1229 * @param string $borderAttr The border attribute
1230 * @return string The border attribute
1231 */
1232 public function getBorderAttr($borderAttr)
1233 {
1234 $tsfe = $this->getTypoScriptFrontendController();
1235 $docType = $tsfe->xhtmlDoctype;
1236 if (
1237 $docType !== 'xhtml_strict' && $docType !== 'xhtml_11'
1238 && $tsfe->config['config']['doctype'] !== 'html5'
1239 && !$tsfe->config['config']['disableImgBorderAttr']
1240 ) {
1241 return $borderAttr;
1242 }
1243 return '';
1244 }
1245
1246 /**
1247 * Returns the html-template for rendering the image-Tag if no template is defined via typoscript the
1248 * default <img> tag template is returned
1249 *
1250 * @param string $layoutKey rendering key
1251 * @param array $conf TypoScript configuration properties
1252 * @return string
1253 */
1254 public function getImageTagTemplate($layoutKey, $conf)
1255 {
1256 if ($layoutKey && isset($conf['layout.']) && isset($conf['layout.'][$layoutKey . '.'])) {
1257 $imageTagLayout = $this->stdWrap($conf['layout.'][$layoutKey . '.']['element'], $conf['layout.'][$layoutKey . '.']['element.']);
1258 } else {
1259 $imageTagLayout = '<img src="###SRC###" width="###WIDTH###" height="###HEIGHT###" ###PARAMS### ###ALTPARAMS### ###BORDER######SELFCLOSINGTAGSLASH###>';
1260 }
1261 return $imageTagLayout;
1262 }
1263
1264 /**
1265 * Render alternate sources for the image tag. If no source collection is given an empty string is returned.
1266 *
1267 * @param string $layoutKey rendering key
1268 * @param array $conf TypoScript configuration properties
1269 * @param string $file
1270 * @throws \UnexpectedValueException
1271 * @return string
1272 */
1273 public function getImageSourceCollection($layoutKey, $conf, $file)
1274 {
1275 $sourceCollection = '';
1276 if ($layoutKey && $conf['sourceCollection.'] && ($conf['layout.'][$layoutKey . '.']['source'] || $conf['layout.'][$layoutKey . '.']['source.'])) {
1277
1278 // find active sourceCollection
1279 $activeSourceCollections = [];
1280 foreach ($conf['sourceCollection.'] as $sourceCollectionKey => $sourceCollectionConfiguration) {
1281 if (substr($sourceCollectionKey, -1) === '.') {
1282 if (empty($sourceCollectionConfiguration['if.']) || $this->checkIf($sourceCollectionConfiguration['if.'])) {
1283 $activeSourceCollections[] = $sourceCollectionConfiguration;
1284 }
1285 }
1286 }
1287
1288 // apply option split to configurations
1289 $tsfe = $this->getTypoScriptFrontendController();
1290 $srcLayoutOptionSplitted = $tsfe->tmpl->splitConfArray($conf['layout.'][$layoutKey . '.'], count($activeSourceCollections));
1291
1292 // render sources
1293 foreach ($activeSourceCollections as $key => $sourceConfiguration) {
1294 $sourceLayout = $this->stdWrap($srcLayoutOptionSplitted[$key]['source'], $srcLayoutOptionSplitted[$key]['source.']);
1295
1296 $sourceRenderConfiguration = [
1297 'file' => $file,
1298 'file.' => $conf['file.']
1299 ];
1300
1301 if (isset($sourceConfiguration['quality']) || isset($sourceConfiguration['quality.'])) {
1302 $imageQuality = isset($sourceConfiguration['quality']) ? $sourceConfiguration['quality'] : '';
1303 if (isset($sourceConfiguration['quality.'])) {
1304 $imageQuality = $this->stdWrap($sourceConfiguration['quality'], $sourceConfiguration['quality.']);
1305 }
1306 if ($imageQuality) {
1307 $sourceRenderConfiguration['file.']['params'] = '-quality ' . (int)$imageQuality;
1308 }
1309 }
1310
1311 if (isset($sourceConfiguration['pixelDensity'])) {
1312 $pixelDensity = (int)$this->stdWrap($sourceConfiguration['pixelDensity'], $sourceConfiguration['pixelDensity.']);
1313 } else {
1314 $pixelDensity = 1;
1315 }
1316 $dimensionKeys = ['width', 'height', 'maxW', 'minW', 'maxH', 'minH'];
1317 foreach ($dimensionKeys as $dimensionKey) {
1318 $dimension = $this->stdWrap($sourceConfiguration[$dimensionKey], $sourceConfiguration[$dimensionKey . '.']);
1319 if (!$dimension) {
1320 $dimension = $this->stdWrap($conf['file.'][$dimensionKey], $conf['file.'][$dimensionKey . '.']);
1321 }
1322 if ($dimension) {
1323 if (strstr($dimension, 'c') !== false && ($dimensionKey === 'width' || $dimensionKey === 'height')) {
1324 $dimensionParts = explode('c', $dimension, 2);
1325 $dimension = ((int)$dimensionParts[0] * $pixelDensity) . 'c';
1326 if ($dimensionParts[1]) {
1327 $dimension .= $dimensionParts[1];
1328 }
1329 } else {
1330 $dimension = (int)$dimension * $pixelDensity;
1331 }
1332 $sourceRenderConfiguration['file.'][$dimensionKey] = $dimension;
1333 // Remove the stdWrap properties for dimension as they have been processed already above.
1334 unset($sourceRenderConfiguration['file.'][$dimensionKey . '.']);
1335 }
1336 }
1337 $sourceInfo = $this->getImgResource($sourceRenderConfiguration['file'], $sourceRenderConfiguration['file.']);
1338 if ($sourceInfo) {
1339 $sourceConfiguration['width'] = $sourceInfo[0];
1340 $sourceConfiguration['height'] = $sourceInfo[1];
1341 $urlPrefix = '';
1342 if (parse_url($sourceInfo[3], PHP_URL_HOST) === null) {
1343 $urlPrefix = $tsfe->absRefPrefix;
1344 }
1345 $sourceConfiguration['src'] = htmlspecialchars($urlPrefix . $sourceInfo[3]);
1346 $sourceConfiguration['selfClosingTagSlash'] = !empty($tsfe->xhtmlDoctype) ? ' /' : '';
1347
1348 $oneSourceCollection = $this->substituteMarkerArray($sourceLayout, $sourceConfiguration, '###|###', true, true);
1349
1350 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['getImageSourceCollection'])) {
1351 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['getImageSourceCollection'] as $classData) {
1352 $hookObject = GeneralUtility::getUserObj($classData);
1353 if (!$hookObject instanceof ContentObjectOneSourceCollectionHookInterface) {
1354 throw new \UnexpectedValueException(
1355 '$hookObject must implement interface ' . ContentObjectOneSourceCollectionHookInterface::class,
1356 1380007853
1357 );
1358 }
1359 $oneSourceCollection = $hookObject->getOneSourceCollection((array)$sourceRenderConfiguration, (array)$sourceConfiguration, $oneSourceCollection, $this);
1360 }
1361 }
1362
1363 $sourceCollection .= $oneSourceCollection;
1364 }
1365 }
1366 }
1367 return $sourceCollection;
1368 }
1369
1370 /**
1371 * Wraps the input string in link-tags that opens the image in a new window.
1372 *
1373 * @param string $string String to wrap, probably an <img> tag
1374 * @param string|File|FileReference $imageFile The original image file
1375 * @param array $conf TypoScript properties for the "imageLinkWrap" function
1376 * @return string The input string, $string, wrapped as configured.
1377 * @see cImage()
1378 */
1379 public function imageLinkWrap($string, $imageFile, $conf)
1380 {
1381 $string = (string)$string;
1382 $enable = isset($conf['enable.']) ? $this->stdWrap($conf['enable'], $conf['enable.']) : $conf['enable'];
1383 if (!$enable) {
1384 return $string;
1385 }
1386 $content = (string)$this->typoLink($string, $conf['typolink.']);
1387 if (isset($conf['file.'])) {
1388 $imageFile = $this->stdWrap($imageFile, $conf['file.']);
1389 }
1390
1391 if ($imageFile instanceof File) {
1392 $file = $imageFile;
1393 } elseif ($imageFile instanceof FileReference) {
1394 $file = $imageFile->getOriginalFile();
1395 } else {
1396 if (MathUtility::canBeInterpretedAsInteger($imageFile)) {
1397 $file = ResourceFactory::getInstance()->getFileObject((int)$imageFile);
1398 } else {
1399 $file = ResourceFactory::getInstance()->getFileObjectFromCombinedIdentifier($imageFile);
1400 }
1401 }
1402
1403 // Create imageFileLink if not created with typolink
1404 if ($content === $string) {
1405 $parameterNames = ['width', 'height', 'effects', 'bodyTag', 'title', 'wrap', 'crop'];
1406 $parameters = [];
1407 $sample = isset($conf['sample.']) ? $this->stdWrap($conf['sample'], $conf['sample.']) : $conf['sample'];
1408 if ($sample) {
1409 $parameters['sample'] = 1;
1410 }
1411 foreach ($parameterNames as $parameterName) {
1412 if (isset($conf[$parameterName . '.'])) {
1413 $conf[$parameterName] = $this->stdWrap($conf[$parameterName], $conf[$parameterName . '.']);
1414 }
1415 if (isset($conf[$parameterName]) && $conf[$parameterName]) {
1416 $parameters[$parameterName] = $conf[$parameterName];
1417 }
1418 }
1419 $parametersEncoded = base64_encode(serialize($parameters));
1420 $hmac = GeneralUtility::hmac(implode('|', [$file->getUid(), $parametersEncoded]));
1421 $params = '&md5=' . $hmac;
1422 foreach (str_split($parametersEncoded, 64) as $index => $chunk) {
1423 $params .= '&parameters' . rawurlencode('[') . $index . rawurlencode(']') . '=' . rawurlencode($chunk);
1424 }
1425 $url = $this->getTypoScriptFrontendController()->absRefPrefix . 'index.php?eID=tx_cms_showpic&file=' . $file->getUid() . $params;
1426 $directImageLink = isset($conf['directImageLink.']) ? $this->stdWrap($conf['directImageLink'], $conf['directImageLink.']) : $conf['directImageLink'];
1427 if ($directImageLink) {
1428 $imgResourceConf = [
1429 'file' => $imageFile,
1430 'file.' => $conf
1431 ];
1432 $url = $this->cObjGetSingle('IMG_RESOURCE', $imgResourceConf);
1433 if (!$url) {
1434 // If no imagemagick / gm is available
1435 $url = $imageFile;
1436 }
1437 }
1438 // Create TARGET-attribute only if the right doctype is used
1439 $target = '';
1440 $xhtmlDocType = $this->getTypoScriptFrontendController()->xhtmlDoctype;
1441 if ($xhtmlDocType !== 'xhtml_strict' && $xhtmlDocType !== 'xhtml_11') {
1442 $target = isset($conf['target.'])
1443 ? (string)$this->stdWrap($conf['target'], $conf['target.'])
1444 : (string)$conf['target'];
1445 if ($target === '') {
1446 $target = 'thePicture';
1447 }
1448 }
1449 $a1 = '';
1450 $a2 = '';
1451 $conf['JSwindow'] = isset($conf['JSwindow.']) ? $this->stdWrap($conf['JSwindow'], $conf['JSwindow.']) : $conf['JSwindow'];
1452 if ($conf['JSwindow']) {
1453 if ($conf['JSwindow.']['altUrl'] || $conf['JSwindow.']['altUrl.']) {
1454 $altUrl = isset($conf['JSwindow.']['altUrl.']) ? $this->stdWrap($conf['JSwindow.']['altUrl'], $conf['JSwindow.']['altUrl.']) : $conf['JSwindow.']['altUrl'];
1455 if ($altUrl) {
1456 $url = $altUrl . ($conf['JSwindow.']['altUrl_noDefaultParams'] ? '' : '?file=' . rawurlencode($imageFile) . $params);
1457 }
1458 }
1459
1460 $processedFile = $file->process('Image.CropScaleMask', $conf);
1461 $JSwindowExpand = isset($conf['JSwindow.']['expand.']) ? $this->stdWrap($conf['JSwindow.']['expand'], $conf['JSwindow.']['expand.']) : $conf['JSwindow.']['expand'];
1462 $offset = GeneralUtility::intExplode(',', $JSwindowExpand . ',');
1463 $newWindow = isset($conf['JSwindow.']['newWindow.']) ? $this->stdWrap($conf['JSwindow.']['newWindow'], $conf['JSwindow.']['newWindow.']) : $conf['JSwindow.']['newWindow'];
1464 $onClick = 'openPic('
1465 . GeneralUtility::quoteJSvalue($this->getTypoScriptFrontendController()->baseUrlWrap($url)) . ','
1466 . '\'' . ($newWindow ? md5($url) : 'thePicture') . '\','
1467 . GeneralUtility::quoteJSvalue('width=' . ($processedFile->getProperty('width') + $offset[0])
1468 . ',height=' . ($processedFile->getProperty('height') + $offset[1]) . ',status=0,menubar=0')
1469 . '); return false;';
1470 $a1 = '<a href="' . htmlspecialchars($url) . '"'
1471 . ' onclick="' . htmlspecialchars($onClick) . '"'
1472 . ($target !== '' ? ' target="' . htmlspecialchars($target) . '"' : '')
1473 . $this->getTypoScriptFrontendController()->ATagParams . '>';
1474 $a2 = '</a>';
1475 $this->getTypoScriptFrontendController()->setJS('openPic');
1476 } else {
1477 $conf['linkParams.']['parameter'] = $url;
1478 $string = $this->typoLink($string, $conf['linkParams.']);
1479 }
1480 if (isset($conf['stdWrap.'])) {
1481 $string = $this->stdWrap($string, $conf['stdWrap.']);
1482 }
1483 $content = $a1 . $string . $a2;
1484 }
1485 return $content;
1486 }
1487
1488 /**
1489 * Returns content of a file. If it's an image the content of the file is not returned but rather an image tag is.
1490 *
1491 * @param string $fName The filename, being a TypoScript resource data type
1492 * @param string $addParams Additional parameters (attributes). Default is empty alt and title tags.
1493 * @return string If jpg,gif,jpeg,png: returns image_tag with picture in. If html,txt: returns content string
1494 * @see FILE()
1495 */
1496 public function fileResource($fName, $addParams = 'alt="" title=""')
1497 {
1498 $tsfe = $this->getTypoScriptFrontendController();
1499 $incFile = $tsfe->tmpl->getFileName($fName);
1500 if ($incFile && file_exists($incFile)) {
1501 $fileInfo = GeneralUtility::split_fileref($incFile);
1502 $extension = $fileInfo['fileext'];
1503 if ($extension === 'jpg' || $extension === 'jpeg' || $extension === 'gif' || $extension === 'png') {
1504 $imgFile = $incFile;
1505 $imgInfo = @getimagesize($imgFile);
1506 return '<img src="' . htmlspecialchars($tsfe->absRefPrefix . $imgFile) . '" width="' . (int)$imgInfo[0] . '" height="' . (int)$imgInfo[1] . '"' . $this->getBorderAttr(' border="0"') . ' ' . $addParams . ' />';
1507 } elseif (filesize($incFile) < 1024 * 1024) {
1508 return file_get_contents($incFile);
1509 }
1510 }
1511 return '';
1512 }
1513
1514 /**
1515 * Sets the SYS_LASTCHANGED timestamp if input timestamp is larger than current value.
1516 * The SYS_LASTCHANGED timestamp can be used by various caching/indexing applications to determine if the page has new content.
1517 * Therefore you should call this function with the last-changed timestamp of any element you display.
1518 *
1519 * @param int $tstamp Unix timestamp (number of seconds since 1970)
1520 * @return void
1521 * @see TypoScriptFrontendController::setSysLastChanged()
1522 */
1523 public function lastChanged($tstamp)
1524 {
1525 $tstamp = (int)$tstamp;
1526 $tsfe = $this->getTypoScriptFrontendController();
1527 if ($tstamp > (int)$tsfe->register['SYS_LASTCHANGED']) {
1528 $tsfe->register['SYS_LASTCHANGED'] = $tstamp;
1529 }
1530 }
1531
1532 /**
1533 * Wraps the input string by the $wrap value and implements the "linkWrap" data type as well.
1534 * The "linkWrap" data type means that this function will find any integer encapsulated in {} (curly braces) in the first wrap part and substitute it with the corresponding page uid from the rootline where the found integer is pointing to the key in the rootline. See link below.
1535 *
1536 * @param string $content Input string
1537 * @param string $wrap A string where the first two parts separated by "|" (vertical line) will be wrapped around the input string
1538 * @return string Wrapped output string
1539 * @see wrap(), cImage(), FILE()
1540 */
1541 public function linkWrap($content, $wrap)
1542 {
1543 $wrapArr = explode('|', $wrap);
1544 if (preg_match('/\\{([0-9]*)\\}/', $wrapArr[0], $reg)) {
1545 if ($uid = $this->getTypoScriptFrontendController()->tmpl->rootLine[$reg[1]]['uid']) {
1546 $wrapArr[0] = str_replace($reg[0], $uid, $wrapArr[0]);
1547 }
1548 }
1549 return trim($wrapArr[0]) . $content . trim($wrapArr[1]);
1550 }
1551
1552 /**
1553 * An abstraction method which creates an alt or title parameter for an HTML img, applet, area or input element and the FILE content element.
1554 * From the $conf array it implements the properties "altText", "titleText" and "longdescURL"
1555 *
1556 * @param array $conf TypoScript configuration properties
1557 * @param bool $longDesc If set, the longdesc attribute will be generated - must only be used for img elements!
1558 * @return string Parameter string containing alt and title parameters (if any)
1559 * @see IMGTEXT(), FILE(), FORM(), cImage(), filelink()
1560 */
1561 public function getAltParam($conf, $longDesc = true)
1562 {
1563 $altText = isset($conf['altText.']) ? trim($this->stdWrap($conf['altText'], $conf['altText.'])) : trim($conf['altText']);
1564 $titleText = isset($conf['titleText.']) ? trim($this->stdWrap($conf['titleText'], $conf['titleText.'])) : trim($conf['titleText']);
1565 if (isset($conf['longdescURL.']) && $this->getTypoScriptFrontendController()->config['config']['doctype'] != 'html5') {
1566 $longDescUrl = $this->typoLink_URL($conf['longdescURL.']);
1567 } else {
1568 $longDescUrl = trim($conf['longdescURL']);
1569 }
1570 $longDescUrl = strip_tags($longDescUrl);
1571
1572 // "alt":
1573 $altParam = ' alt="' . htmlspecialchars($altText) . '"';
1574 // "title":
1575 $emptyTitleHandling = isset($conf['emptyTitleHandling.']) ? $this->stdWrap($conf['emptyTitleHandling'], $conf['emptyTitleHandling.']) : $conf['emptyTitleHandling'];
1576 // Choices: 'keepEmpty' | 'useAlt' | 'removeAttr'
1577 if ($titleText || $emptyTitleHandling === 'keepEmpty') {
1578 $altParam .= ' title="' . htmlspecialchars($titleText) . '"';
1579 } elseif (!$titleText && $emptyTitleHandling === 'useAlt') {
1580 $altParam .= ' title="' . htmlspecialchars($altText) . '"';
1581 }
1582 // "longDesc" URL
1583 if ($longDesc && !empty($longDescUrl)) {
1584 $altParam .= ' longdesc="' . htmlspecialchars($longDescUrl) . '"';
1585 }
1586 return $altParam;
1587 }
1588
1589 /**
1590 * An abstraction method to add parameters to an A tag.
1591 * Uses the ATagParams property.
1592 *
1593 * @param array $conf TypoScript configuration properties
1594 * @param bool|int $addGlobal If set, will add the global config.ATagParams to the link
1595 * @return string String containing the parameters to the A tag (if non empty, with a leading space)
1596 * @see IMGTEXT(), filelink(), makelinks(), typolink()
1597 */
1598 public function getATagParams($conf, $addGlobal = 1)
1599 {
1600 $aTagParams = '';
1601 if ($conf['ATagParams.']) {
1602 $aTagParams = ' ' . $this->stdWrap($conf['ATagParams'], $conf['ATagParams.']);
1603 } elseif ($conf['ATagParams']) {
1604 $aTagParams = ' ' . $conf['ATagParams'];
1605 }
1606 if ($addGlobal) {
1607 $aTagParams = ' ' . trim($this->getTypoScriptFrontendController()->ATagParams . $aTagParams);
1608 }
1609 // Extend params
1610 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['getATagParamsPostProc']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['getATagParamsPostProc'])) {
1611 $_params = [
1612 'conf' => &$conf,
1613 'aTagParams' => &$aTagParams
1614 ];
1615 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['getATagParamsPostProc'] as $objRef) {
1616 $processor =& GeneralUtility::getUserObj($objRef);
1617 $aTagParams = $processor->process($_params, $this);
1618 }
1619 }
1620
1621 $aTagParams = trim($aTagParams);
1622 if (!empty($aTagParams)) {
1623 $aTagParams = ' ' . $aTagParams;
1624 }
1625
1626 return $aTagParams;
1627 }
1628
1629 /**
1630 * All extension links should ask this function for additional properties to their tags.
1631 * Designed to add for instance an "onclick" property for site tracking systems.
1632 *
1633 * @param string $URL URL of the website
1634 * @param string $TYPE
1635 * @return string The additional tag properties
1636 */
1637 public function extLinkATagParams($URL, $TYPE)
1638 {
1639 $out = '';
1640 if ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['extLinkATagParamsHandler']) {
1641 $extLinkATagParamsHandler = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['extLinkATagParamsHandler']);
1642 if (method_exists($extLinkATagParamsHandler, 'main')) {
1643 $out .= trim($extLinkATagParamsHandler->main($URL, $TYPE, $this));
1644 }
1645 }
1646 return trim($out) ? ' ' . trim($out) : '';
1647 }
1648
1649 /***********************************************
1650 *
1651 * HTML template processing functions
1652 *
1653 ***********************************************/
1654 /**
1655 * Returns a subpart from the input content stream.
1656 * A subpart is a part of the input stream which is encapsulated in a
1657 * string matching the input string, $marker. If this string is found
1658 * inside of HTML comment tags the start/end points of the content block
1659 * returned will be that right outside that comment block.
1660 * Example: The contennt string is
1661 * "Hello <!--###sub1### begin--> World. How are <!--###sub1### end--> you?"
1662 * If $marker is "###sub1###" then the content returned is
1663 * " World. How are ". The input content string could just as well have
1664 * been "Hello ###sub1### World. How are ###sub1### you?" and the result
1665 * would be the same
1666 * Wrapper for \TYPO3\CMS\Core\Utility\MarkerBasedTemplateService::getSubpart which behaves identical
1667 *
1668 * @param string $content The content stream, typically HTML template content.
1669 * @param string $marker The marker string, typically on the form "###[the marker string]###
1670 * @return string The subpart found, if found.
1671 */
1672 public function getSubpart($content, $marker)
1673 {
1674 return $this->templateService->getSubpart($content, $marker);
1675 }
1676
1677 /**
1678 * Substitute subpart in input template stream.
1679 * This function substitutes a subpart in $content with the content of
1680 * $subpartContent.
1681 * Wrapper for \TYPO3\CMS\Core\Utility\MarkerBasedTemplateService::substituteSubpart which behaves identical
1682 *
1683 * @param string $content The content stream, typically HTML template content.
1684 * @param string $marker The marker string, typically on the form "###[the marker string]###
1685 * @param mixed $subpartContent The content to insert instead of the subpart found. If a string, then just plain substitution happens (includes removing the HTML comments of the subpart if found). If $subpartContent happens to be an array, it's [0] and [1] elements are wrapped around the EXISTING content of the subpart (fetched by getSubpart()) thereby not removing the original content.
1686 * @param bool|int $recursive If $recursive is set, the function calls itself with the content set to the remaining part of the content after the second marker. This means that proceding subparts are ALSO substituted!
1687 * @return string The processed HTML content string.
1688 */
1689 public function substituteSubpart($content, $marker, $subpartContent, $recursive = 1)
1690 {
1691 return $this->templateService->substituteSubpart($content, $marker, $subpartContent, $recursive);
1692 }
1693
1694 /**
1695 * Substitues multiple subparts at once
1696 *
1697 * @param string $content The content stream, typically HTML template content.
1698 * @param array $subpartsContent The array of key/value pairs being subpart/content values used in the substitution. For each element in this array the function will substitute a subpart in the content stream with the content.
1699 * @return string The processed HTML content string.
1700 */
1701 public function substituteSubpartArray($content, array $subpartsContent)
1702 {
1703 return $this->templateService->substituteSubpartArray($content, $subpartsContent);
1704 }
1705
1706 /**
1707 * Substitutes a marker string in the input content
1708 * (by a simple str_replace())
1709 *
1710 * @param string $content The content stream, typically HTML template content.
1711 * @param string $marker The marker string, typically on the form "###[the marker string]###
1712 * @param mixed $markContent The content to insert instead of the marker string found.
1713 * @return string The processed HTML content string.
1714 * @see substituteSubpart()
1715 */
1716 public function substituteMarker($content, $marker, $markContent)
1717 {
1718 return $this->templateService->substituteMarker($content, $marker, $markContent);
1719 }
1720
1721 /**
1722 * Multi substitution function with caching.
1723 *
1724 * This function should be a one-stop substitution function for working
1725 * with HTML-template. It does not substitute by str_replace but by
1726 * splitting. This secures that the value inserted does not themselves
1727 * contain markers or subparts.
1728 *
1729 * Note that the "caching" won't cache the content of the substition,
1730 * but only the splitting of the template in various parts. So if you
1731 * want only one cache-entry per template, make sure you always pass the
1732 * exact same set of marker/subpart keys. Else you will be flooding the
1733 * user's cache table.
1734 *
1735 * This function takes three kinds of substitutions in one:
1736 * $markContentArray is a regular marker-array where the 'keys' are
1737 * substituted in $content with their values
1738 *
1739 * $subpartContentArray works exactly like markContentArray only is whole
1740 * subparts substituted and not only a single marker.
1741 *
1742 * $wrappedSubpartContentArray is an array of arrays with 0/1 keys where
1743 * the subparts pointed to by the main key is wrapped with the 0/1 value
1744 * alternating.
1745 *
1746 * @param string $content The content stream, typically HTML template content.
1747 * @param array $markContentArray Regular marker-array where the 'keys' are substituted in $content with their values
1748 * @param array $subpartContentArray Exactly like markContentArray only is whole subparts substituted and not only a single marker.
1749 * @param array $wrappedSubpartContentArray An array of arrays with 0/1 keys where the subparts pointed to by the main key is wrapped with the 0/1 value alternating.
1750 * @return string The output content stream
1751 * @see substituteSubpart(), substituteMarker(), substituteMarkerInObject(), TEMPLATE()
1752 */
1753 public function substituteMarkerArrayCached($content, array $markContentArray = null, array $subpartContentArray = null, array $wrappedSubpartContentArray = null)
1754 {
1755 $timeTracker = $this->getTimeTracker();
1756 $timeTracker->push('substituteMarkerArrayCached');
1757 // If not arrays then set them
1758 if (is_null($markContentArray)) {
1759 // Plain markers
1760 $markContentArray = [];
1761 }
1762 if (is_null($subpartContentArray)) {
1763 // Subparts being directly substituted
1764 $subpartContentArray = [];
1765 }
1766 if (is_null($wrappedSubpartContentArray)) {
1767 // Subparts being wrapped
1768 $wrappedSubpartContentArray = [];
1769 }
1770 // Finding keys and check hash:
1771 $sPkeys = array_keys($subpartContentArray);
1772 $wPkeys = array_keys($wrappedSubpartContentArray);
1773 $keysToReplace = array_merge(array_keys($markContentArray), $sPkeys, $wPkeys);
1774 if (empty($keysToReplace)) {
1775 $timeTracker->pull();
1776 return $content;
1777 }
1778 asort($keysToReplace);
1779 $storeKey = md5('substituteMarkerArrayCached_storeKey:' . serialize([$content, $keysToReplace]));
1780 if ($this->substMarkerCache[$storeKey]) {
1781 $storeArr = $this->substMarkerCache[$storeKey];
1782 $timeTracker->setTSlogMessage('Cached', 0);
1783 } else {
1784 $storeArrDat = $this->getTypoScriptFrontendController()->sys_page->getHash($storeKey);
1785 if (is_array($storeArrDat)) {
1786 $storeArr = $storeArrDat;
1787 // Setting cache:
1788 $this->substMarkerCache[$storeKey] = $storeArr;
1789 $timeTracker->setTSlogMessage('Cached from DB', 0);
1790 } else {
1791 // Finding subparts and substituting them with the subpart as a marker
1792 foreach ($sPkeys as $sPK) {
1793 $content = $this->substituteSubpart($content, $sPK, $sPK);
1794 }
1795 // Finding subparts and wrapping them with markers
1796 foreach ($wPkeys as $wPK) {
1797 $content = $this->substituteSubpart($content, $wPK, [
1798 $wPK,
1799 $wPK
1800 ]);
1801 }
1802
1803 $storeArr = [];
1804 // search all markers in the content
1805 $result = preg_match_all('/###([^#](?:[^#]*+|#{1,2}[^#])+)###/', $content, $markersInContent);
1806 if ($result !== false && !empty($markersInContent[1])) {
1807 $keysToReplaceFlipped = array_flip($keysToReplace);
1808 $regexKeys = [];
1809 $wrappedKeys = [];
1810 // Traverse keys and quote them for reg ex.
1811 foreach ($markersInContent[1] as $key) {
1812 if (isset($keysToReplaceFlipped['###' . $key . '###'])) {
1813 $regexKeys[] = preg_quote($key, '/');
1814 $wrappedKeys[] = '###' . $key . '###';
1815 }
1816 }
1817 $regex = '/###(?:' . implode('|', $regexKeys) . ')###/';
1818 $storeArr['c'] = preg_split($regex, $content); // contains all content parts around markers
1819 $storeArr['k'] = $wrappedKeys; // contains all markers incl. ###
1820 // Setting cache:
1821 $this->substMarkerCache[$storeKey] = $storeArr;
1822 // Storing the cached data:
1823 $this->getTypoScriptFrontendController()->sys_page->storeHash($storeKey, $storeArr, 'substMarkArrayCached');
1824 }
1825 $timeTracker->setTSlogMessage('Parsing', 0);
1826 }
1827 }
1828 if (!empty($storeArr['k']) && is_array($storeArr['k'])) {
1829 // Substitution/Merging:
1830 // Merging content types together, resetting
1831 $valueArr = array_merge($markContentArray, $subpartContentArray, $wrappedSubpartContentArray);
1832 $wSCA_reg = [];
1833 $content = '';
1834 // Traversing the keyList array and merging the static and dynamic content
1835 foreach ($storeArr['k'] as $n => $keyN) {
1836 // add content before marker
1837 $content .= $storeArr['c'][$n];
1838 if (!is_array($valueArr[$keyN])) {
1839 // fetch marker replacement from $markContentArray or $subpartContentArray
1840 $content .= $valueArr[$keyN];
1841 } else {
1842 if (!isset($wSCA_reg[$keyN])) {
1843 $wSCA_reg[$keyN] = 0;
1844 }
1845 // fetch marker replacement from $wrappedSubpartContentArray
1846 $content .= $valueArr[$keyN][$wSCA_reg[$keyN] % 2];
1847 $wSCA_reg[$keyN]++;
1848 }
1849 }
1850 // add remaining content
1851 $content .= $storeArr['c'][count($storeArr['k'])];
1852 }
1853 $timeTracker->pull();
1854 return $content;
1855 }
1856
1857 /**
1858 * Traverses the input $markContentArray array and for each key the marker
1859 * by the same name (possibly wrapped and in upper case) will be
1860 * substituted with the keys value in the array.
1861 *
1862 * This is very useful if you have a data-record to substitute in some
1863 * content. In particular when you use the $wrap and $uppercase values to
1864 * pre-process the markers. Eg. a key name like "myfield" could effectively
1865 * be represented by the marker "###MYFIELD###" if the wrap value
1866 * was "###|###" and the $uppercase boolean TRUE.
1867 *
1868 * @param string $content The content stream, typically HTML template content.
1869 * @param array $markContentArray The array of key/value pairs being marker/content values used in the substitution. For each element in this array the function will substitute a marker in the content stream with the content.
1870 * @param string $wrap A wrap value - [part 1] | [part 2] - for the markers before substitution
1871 * @param bool $uppercase If set, all marker string substitution is done with upper-case markers.
1872 * @param bool $deleteUnused If set, all unused marker are deleted.
1873 * @return string The processed output stream
1874 * @see substituteMarker(), substituteMarkerInObject(), TEMPLATE()
1875 */
1876 public function substituteMarkerArray($content, array $markContentArray, $wrap = '', $uppercase = false, $deleteUnused = false)
1877 {
1878 return $this->templateService->substituteMarkerArray($content, $markContentArray, $wrap, $uppercase, $deleteUnused);
1879 }
1880
1881 /**
1882 * Substitute marker array in an array of values
1883 *
1884 * @param mixed $tree If string, then it just calls substituteMarkerArray. If array(and even multi-dim) then for each key/value pair the marker array will be substituted (by calling this function recursively)
1885 * @param array $markContentArray The array of key/value pairs being marker/content values used in the substitution. For each element in this array the function will substitute a marker in the content string/array values.
1886 * @return mixed The processed input variable.
1887 * @see substituteMarker()
1888 */
1889 public function substituteMarkerInObject(&$tree, array $markContentArray)
1890 {
1891 if (is_array($tree)) {
1892 foreach ($tree as $key => $value) {
1893 $this->substituteMarkerInObject($tree[$key], $markContentArray);
1894 }
1895 } else {
1896 $tree = $this->substituteMarkerArray($tree, $markContentArray);
1897 }
1898 return $tree;
1899 }
1900
1901 /**
1902 * Replaces all markers and subparts in a template with the content provided in the structured array.
1903 *
1904 * @param string $content
1905 * @param array $markersAndSubparts
1906 * @param string $wrap
1907 * @param bool $uppercase
1908 * @param bool $deleteUnused
1909 * @return string
1910 */
1911 public function substituteMarkerAndSubpartArrayRecursive($content, array $markersAndSubparts, $wrap = '', $uppercase = false, $deleteUnused = false)
1912 {
1913 return $this->templateService->substituteMarkerAndSubpartArrayRecursive($content, $markersAndSubparts, $wrap, $uppercase, $deleteUnused);
1914 }
1915
1916 /**
1917 * Adds elements to the input $markContentArray based on the values from
1918 * the fields from $fieldList found in $row
1919 *
1920 * @param array $markContentArray Array with key/values being marker-strings/substitution values.
1921 * @param array $row An array with keys found in the $fieldList (typically a record) which values should be moved to the $markContentArray
1922 * @param string $fieldList A list of fields from the $row array to add to the $markContentArray array. If empty all fields from $row will be added (unless they are integers)
1923 * @param bool $nl2br If set, all values added to $markContentArray will be nl2br()'ed
1924 * @param string $prefix Prefix string to the fieldname before it is added as a key in the $markContentArray. Notice that the keys added to the $markContentArray always start and end with "###
1925 * @param bool $HSC If set, all values are passed through htmlspecialchars() - RECOMMENDED to avoid most obvious XSS and maintain XHTML compliance.
1926 * @return array The modified $markContentArray
1927 */
1928 public function fillInMarkerArray(array $markContentArray, array $row, $fieldList = '', $nl2br = true, $prefix = 'FIELD_', $HSC = false)
1929 {
1930 $tsfe = $this->getTypoScriptFrontendController();
1931 if ($fieldList) {
1932 $fArr = GeneralUtility::trimExplode(',', $fieldList, true);
1933 foreach ($fArr as $field) {
1934 $markContentArray['###' . $prefix . $field . '###'] = $nl2br ? nl2br($row[$field], !empty($tsfe->xhtmlDoctype)) : $row[$field];
1935 }
1936 } else {
1937 if (is_array($row)) {
1938 foreach ($row as $field => $value) {
1939 if (!MathUtility::canBeInterpretedAsInteger($field)) {
1940 if ($HSC) {
1941 $value = htmlspecialchars($value);
1942 }
1943 $markContentArray['###' . $prefix . $field . '###'] = $nl2br ? nl2br($value, !empty($tsfe->xhtmlDoctype)) : $value;
1944 }
1945 }
1946 }
1947 }
1948 return $markContentArray;
1949 }
1950
1951 /**
1952 * Sets the current file object during iterations over files.
1953 *
1954 * @param File $fileObject The file object.
1955 */
1956 public function setCurrentFile($fileObject)
1957 {
1958 $this->currentFile = $fileObject;
1959 }
1960
1961 /**
1962 * Gets the current file object during iterations over files.
1963 *
1964 * @return File The current file object.
1965 */
1966 public function getCurrentFile()
1967 {
1968 return $this->currentFile;
1969 }
1970
1971 /***********************************************
1972 *
1973 * "stdWrap" + sub functions
1974 *
1975 ***********************************************/
1976 /**
1977 * The "stdWrap" function. This is the implementation of what is known as "stdWrap properties" in TypoScript.
1978 * Basically "stdWrap" performs some processing of a value based on properties in the input $conf array(holding the TypoScript "stdWrap properties")
1979 * See the link below for a complete list of properties and what they do. The order of the table with properties found in TSref (the link) follows the actual order of implementation in this function.
1980 *
1981 * If $this->alternativeData is an array it's used instead of the $this->data array in ->getData
1982 *
1983 * @param string $content Input value undergoing processing in this function. Possibly substituted by other values fetched from another source.
1984 * @param array $conf TypoScript "stdWrap properties".
1985 * @return string The processed input value
1986 */
1987 public function stdWrap($content = '', $conf = [])
1988 {
1989 $content = (string)$content;
1990 // If there is any hook object, activate all of the process and override functions.
1991 // The hook interface ContentObjectStdWrapHookInterface takes care that all 4 methods exist.
1992 if ($this->stdWrapHookObjects) {
1993 $conf['stdWrapPreProcess'] = 1;
1994 $conf['stdWrapOverride'] = 1;
1995 $conf['stdWrapProcess'] = 1;
1996 $conf['stdWrapPostProcess'] = 1;
1997 }
1998
1999 if (!is_array($conf) || !$conf) {
2000 return $content;
2001 }
2002
2003 // Cache handling
2004 if (is_array($conf['cache.'])) {
2005 $conf['cache.']['key'] = $this->stdWrap($conf['cache.']['key'], $conf['cache.']['key.']);
2006 $conf['cache.']['tags'] = $this->stdWrap($conf['cache.']['tags'], $conf['cache.']['tags.']);
2007 $conf['cache.']['lifetime'] = $this->stdWrap($conf['cache.']['lifetime'], $conf['cache.']['lifetime.']);
2008 $conf['cacheRead'] = 1;
2009 $conf['cacheStore'] = 1;
2010 }
2011 // The configuration is sorted and filtered by intersection with the defined stdWrapOrder.
2012 $sortedConf = array_keys(array_intersect_key($this->stdWrapOrder, $conf));
2013 // Functions types that should not make use of nested stdWrap function calls to avoid conflicts with internal TypoScript used by these functions
2014 $stdWrapDisabledFunctionTypes = 'cObject,functionName,stdWrap';
2015 // Additional Array to check whether a function has already been executed
2016 $isExecuted = [];
2017 // Additional switch to make sure 'required', 'if' and 'fieldRequired'
2018 // will still stop rendering immediately in case they return FALSE
2019 $this->stdWrapRecursionLevel++;
2020 $this->stopRendering[$this->stdWrapRecursionLevel] = false;
2021 // execute each function in the predefined order
2022 foreach ($sortedConf as $stdWrapName) {
2023 // eliminate the second key of a pair 'key'|'key.' to make sure functions get called only once and check if rendering has been stopped
2024 if (!$isExecuted[$stdWrapName] && !$this->stopRendering[$this->stdWrapRecursionLevel]) {
2025 $functionName = rtrim($stdWrapName, '.');
2026 $functionProperties = $functionName . '.';
2027 $functionType = $this->stdWrapOrder[$functionName];
2028 // If there is any code on the next level, check if it contains "official" stdWrap functions
2029 // if yes, execute them first - will make each function stdWrap aware
2030 // so additional stdWrap calls within the functions can be removed, since the result will be the same
2031 if (!empty($conf[$functionProperties]) && !GeneralUtility::inList($stdWrapDisabledFunctionTypes, $functionType)) {
2032 if (array_intersect_key($this->stdWrapOrder, $conf[$functionProperties])) {
2033 $conf[$functionName] = $this->stdWrap($conf[$functionName], $conf[$functionProperties]);
2034 }
2035 }
2036 // Check if key is still containing something, since it might have been changed by next level stdWrap before
2037 if ((isset($conf[$functionName]) || $conf[$functionProperties]) && ($functionType !== 'boolean' || $conf[$functionName])) {
2038 // Get just that part of $conf that is needed for the particular function
2039 $singleConf = [
2040 $functionName => $conf[$functionName],
2041 $functionProperties => $conf[$functionProperties]
2042 ];
2043 // In this special case 'spaceBefore' and 'spaceAfter' need additional stuff from 'space.''
2044 if ($functionName === 'spaceBefore' || $functionName === 'spaceAfter') {
2045 $singleConf['space.'] = $conf['space.'];
2046 }
2047 // Hand over the whole $conf array to the stdWrapHookObjects
2048 if ($functionType === 'hook') {
2049 $singleConf = $conf;
2050 }
2051 // Add both keys - with and without the dot - to the set of executed functions
2052 $isExecuted[$functionName] = true;
2053 $isExecuted[$functionProperties] = true;
2054 // Call the function with the prefix stdWrap_ to make sure nobody can execute functions just by adding their name to the TS Array
2055 $functionName = 'stdWrap_' . $functionName;
2056 $content = $this->{$functionName}($content, $singleConf);
2057 } elseif ($functionType === 'boolean' && !$conf[$functionName]) {
2058 $isExecuted[$functionName] = true;
2059 $isExecuted[$functionProperties] = true;
2060 }
2061 }
2062 }
2063 unset($this->stopRendering[$this->stdWrapRecursionLevel]);
2064 $this->stdWrapRecursionLevel--;
2065
2066 return $content;
2067 }
2068
2069 /**
2070 * Gets a configuration value by passing them through stdWrap first and taking a default value if stdWrap doesn't yield a result.
2071 *
2072 * @param string $key The config variable key (from TS array).
2073 * @param array $config The TypoScript array.
2074 * @param string $defaultValue Optional default value.
2075 * @return string Value of the config variable
2076 */
2077 public function stdWrapValue($key, array $config, $defaultValue = '')
2078 {
2079 if (isset($config[$key])) {
2080 if (!isset($config[$key . '.'])) {
2081 return $config[$key];
2082 }
2083 } elseif (isset($config[$key . '.'])) {
2084 $config[$key] = '';
2085 } else {
2086 return $defaultValue;
2087 }
2088 $stdWrapped = $this->stdWrap($config[$key], $config[$key . '.']);
2089 return $stdWrapped ?: $defaultValue;
2090 }
2091
2092 /**
2093 * stdWrap pre process hook
2094 * can be used by extensions authors to modify the behaviour of stdWrap functions to their needs
2095 * this hook will execute functions before any other stdWrap function can modify anything
2096 *
2097 * @param string $content Input value undergoing processing in these functions.
2098 * @param array $conf All stdWrap properties, not just the ones for a particular function.
2099 * @return string The processed input value
2100 */
2101 public function stdWrap_stdWrapPreProcess($content = '', $conf = [])
2102 {
2103 foreach ($this->stdWrapHookObjects as $hookObject) {
2104 /** @var ContentObjectStdWrapHookInterface $hookObject */
2105 $content = $hookObject->stdWrapPreProcess($content, $conf, $this);
2106 }
2107 return $content;
2108 }
2109
2110 /**
2111 * Check if content was cached before (depending on the given cache key)
2112 *
2113 * @param string $content Input value undergoing processing in these functions.
2114 * @param array $conf All stdWrap properties, not just the ones for a particular function.
2115 * @return string The processed input value
2116 */
2117 public function stdWrap_cacheRead($content = '', $conf = [])
2118 {
2119 if (!isset($conf['cache.'])) {
2120 return $content;
2121 }
2122 $result = $this->getFromCache($conf['cache.']);
2123 return $result === false ? $content : $result;
2124 }
2125
2126 /**
2127 * Add tags to page cache (comma-separated list)
2128 *
2129 * @param string $content Input value undergoing processing in these functions.
2130 * @param array $conf All stdWrap properties, not just the ones for a particular function.
2131 * @return string The processed input value
2132 */
2133 public function stdWrap_addPageCacheTags($content = '', $conf = [])
2134 {
2135 $tags = isset($conf['addPageCacheTags.'])
2136 ? $this->stdWrap($conf['addPageCacheTags'], $conf['addPageCacheTags.'])
2137 : $conf['addPageCacheTags'];
2138 if (!empty($tags)) {
2139 $cacheTags = GeneralUtility::trimExplode(',', $tags, true);
2140 $this->getTypoScriptFrontendController()->addCacheTags($cacheTags);
2141 }
2142 return $content;
2143 }
2144
2145 /**
2146 * setContentToCurrent
2147 * actually it just does the contrary: Sets the value of 'current' based on current content
2148 *
2149 * @param string $content Input value undergoing processing in this function.
2150 * @return string The processed input value
2151 */
2152 public function stdWrap_setContentToCurrent($content = '')
2153 {
2154 $this->data[$this->currentValKey] = $content;
2155 return $content;
2156 }
2157
2158 /**
2159 * setCurrent
2160 * Sets the value of 'current' based on the outcome of stdWrap operations
2161 *
2162 * @param string $content Input value undergoing processing in this function.
2163 * @param array $conf stdWrap properties for setCurrent.
2164 * @return string The processed input value
2165 */
2166 public function stdWrap_setCurrent($content = '', $conf = [])
2167 {
2168 $this->data[$this->currentValKey] = $conf['setCurrent'];
2169 return $content;
2170 }
2171
2172 /**
2173 * lang
2174 * Translates content based on the language currently used by the FE
2175 *
2176 * @param string $content Input value undergoing processing in this function.
2177 * @param array $conf stdWrap properties for lang.
2178 * @return string The processed input value
2179 */
2180 public function stdWrap_lang($content = '', $conf = [])
2181 {
2182 $tsfe = $this->getTypoScriptFrontendController();
2183 if (isset($conf['lang.']) && $tsfe->config['config']['language'] && isset($conf['lang.'][$tsfe->config['config']['language']])) {
2184 $content = $conf['lang.'][$tsfe->config['config']['language']];
2185 }
2186 return $content;
2187 }
2188
2189 /**
2190 * data
2191 * Gets content from different sources based on getText functions, makes use of alternativeData, when set
2192 *
2193 * @param string $content Input value undergoing processing in this function.
2194 * @param array $conf stdWrap properties for data.
2195 * @return string The processed input value
2196 */
2197 public function stdWrap_data($content = '', $conf = [])
2198 {
2199 $content = $this->getData($conf['data'], is_array($this->alternativeData) ? $this->alternativeData : $this->data);
2200 // This must be unset directly after
2201 $this->alternativeData = '';
2202 return $content;
2203 }
2204
2205 /**
2206 * field
2207 * Gets content from a DB field
2208 *
2209 * @param string $content Input value undergoing processing in this function.
2210 * @param array $conf stdWrap properties for field.
2211 * @return string The processed input value
2212 */
2213 public function stdWrap_field($content = '', $conf = [])
2214 {
2215 return $this->getFieldVal($conf['field']);
2216 }
2217
2218 /**
2219 * current
2220 * Gets content that has been perviously set as 'current'
2221 * Can be set via setContentToCurrent or setCurrent or will be set automatically i.e. inside the split function
2222 *
2223 * @param string $content Input value undergoing processing in this function.
2224 * @param array $conf stdWrap properties for current.
2225 * @return string The processed input value
2226 */
2227 public function stdWrap_current($content = '', $conf = [])
2228 {
2229 return $this->data[$this->currentValKey];
2230 }
2231
2232 /**
2233 * cObject
2234 * Will replace the content with the value of an official TypoScript cObject
2235 * like TEXT, COA, HMENU
2236 *
2237 * @param string $content Input value undergoing processing in this function.
2238 * @param array $conf stdWrap properties for cObject.
2239 * @return string The processed input value
2240 */
2241 public function stdWrap_cObject($content = '', $conf = [])
2242 {
2243 return $this->cObjGetSingle($conf['cObject'], $conf['cObject.'], '/stdWrap/.cObject');
2244 }
2245
2246 /**
2247 * numRows
2248 * Counts the number of returned records of a DB operation
2249 * makes use of select internally
2250 *
2251 * @param string $content Input value undergoing processing in this function.
2252 * @param array $conf stdWrap properties for numRows.
2253 * @return string The processed input value
2254 */
2255 public function stdWrap_numRows($content = '', $conf = [])
2256 {
2257 return $this->numRows($conf['numRows.']);
2258 }
2259
2260 /**
2261 * filelist
2262 * Will create a list of files based on some additional parameters
2263 *
2264 * @param string $content Input value undergoing processing in this function.
2265 * @param array $conf stdWrap properties for filelist.
2266 * @return string The processed input value
2267 */
2268 public function stdWrap_filelist($content = '', $conf = [])
2269 {
2270 return $this->filelist($conf['filelist']);
2271 }
2272
2273 /**
2274 * preUserFunc
2275 * Will execute a user public function before the content will be modified by any other stdWrap function
2276 *
2277 * @param string $content Input value undergoing processing in this function.
2278 * @param array $conf stdWrap properties for preUserFunc.
2279 * @return string The processed input value
2280 */
2281 public function stdWrap_preUserFunc($content = '', $conf = [])
2282 {
2283 return $this->callUserFunction($conf['preUserFunc'], $conf['preUserFunc.'], $content);
2284 }
2285
2286 /**
2287 * stdWrap override hook
2288 * can be used by extensions authors to modify the behaviour of stdWrap functions to their needs
2289 * this hook will execute functions on existing content but still before the content gets modified or replaced
2290 *
2291 * @param string $content Input value undergoing processing in these functions.
2292 * @param array $conf All stdWrap properties, not just the ones for a particular function.
2293 * @return string The processed input value
2294 */
2295 public function stdWrap_stdWrapOverride($content = '', $conf = [])
2296 {
2297 foreach ($this->stdWrapHookObjects as $hookObject) {
2298 /** @var ContentObjectStdWrapHookInterface $hookObject */
2299 $content = $hookObject->stdWrapOverride($content, $conf, $this);
2300 }
2301 return $content;
2302 }
2303
2304 /**
2305 * override
2306 * Will override the current value of content with its own value'
2307 *
2308 * @param string $content Input value undergoing processing in this function.
2309 * @param array $conf stdWrap properties for override.
2310 * @return string The processed input value
2311 */
2312 public function stdWrap_override($content = '', $conf = [])
2313 {
2314 if (trim($conf['override'])) {
2315 $content = $conf['override'];
2316 }
2317 return $content;
2318 }
2319
2320 /**
2321 * preIfEmptyListNum
2322 * Gets a value off a CSV list before the following ifEmpty check
2323 * Makes sure that the result of ifEmpty will be TRUE in case the CSV does not contain a value at the position given by preIfEmptyListNum
2324 *
2325 * @param string $content Input value undergoing processing in this function.
2326 * @param array $conf stdWrap properties for preIfEmptyListNum.
2327 * @return string The processed input value
2328 */
2329 public function stdWrap_preIfEmptyListNum($content = '', $conf = [])
2330 {
2331 return $this->listNum($content, $conf['preIfEmptyListNum'], $conf['preIfEmptyListNum.']['splitChar']);
2332 }
2333
2334 /**
2335 * ifNull
2336 * Will set content to a replacement value in case the value of content is NULL
2337 *
2338 * @param string|NULL $content Input value undergoing processing in this function.
2339 * @param array $conf stdWrap properties for ifNull.
2340 * @return string The processed input value
2341 */
2342 public function stdWrap_ifNull($content = '', $conf = [])
2343 {
2344 return $content !== null ? $content : $conf['ifNull'];
2345 }
2346
2347 /**
2348 * ifEmpty
2349 * Will set content to a replacement value in case the trimmed value of content returns FALSE
2350 * 0 (zero) will be replaced as well
2351 *
2352 * @param string $content Input value undergoing processing in this function.
2353 * @param array $conf stdWrap properties for ifEmpty.
2354 * @return string The processed input value
2355 */
2356 public function stdWrap_ifEmpty($content = '', $conf = [])
2357 {
2358 if (!trim($content)) {
2359 $content = $conf['ifEmpty'];
2360 }
2361 return $content;
2362 }
2363
2364 /**
2365 * ifBlank
2366 * Will set content to a replacement value in case the trimmed value of content has no length
2367 * 0 (zero) will not be replaced
2368 *
2369 * @param string $content Input value undergoing processing in this function.
2370 * @param array $conf stdWrap properties for ifBlank.
2371 * @return string The processed input value
2372 */
2373 public function stdWrap_ifBlank($content = '', $conf = [])
2374 {
2375 if (trim($content) === '') {
2376 $content = $conf['ifBlank'];
2377 }
2378 return $content;
2379 }
2380
2381 /**
2382 * listNum
2383 * Gets a value off a CSV list after ifEmpty check
2384 * Might return an empty value in case the CSV does not contain a value at the position given by listNum
2385 * Use preIfEmptyListNum to avoid that behaviour
2386 *
2387 * @param string $content Input value undergoing processing in this function.
2388 * @param array $conf stdWrap properties for listNum.
2389 * @return string The processed input value
2390 */
2391 public function stdWrap_listNum($content = '', $conf = [])
2392 {
2393 return $this->listNum($content, $conf['listNum'], $conf['listNum.']['splitChar']);
2394 }
2395
2396 /**
2397 * trim
2398 * Cuts off any whitespace at the beginning and the end of the content
2399 *
2400 * @param string $content Input value undergoing processing in this function.
2401 * @return string The processed input value
2402 */
2403 public function stdWrap_trim($content = '')
2404 {
2405 return trim($content);
2406 }
2407
2408 /**
2409 * strPad
2410 * Will return a string padded left/right/on both sides, based on configuration given as stdWrap properties
2411 *
2412 * @param string $content Input value undergoing processing in this function.
2413 * @param array $conf stdWrap properties for strPad.
2414 * @return string The processed input value
2415 */
2416 public function stdWrap_strPad($content = '', $conf = [])
2417 {
2418 // Must specify a length in conf for this to make sense
2419 $length = 0;
2420 // Padding with space is PHP-default
2421 $padWith = ' ';
2422 // Padding on the right side is PHP-default
2423 $padType = STR_PAD_RIGHT;
2424 if (!empty($conf['strPad.']['length'])) {
2425 $length = isset($conf['strPad.']['length.']) ? $this->stdWrap($conf['strPad.']['length'], $conf['strPad.']['length.']) : $conf['strPad.']['length'];
2426 $length = (int)$length;
2427 }
2428 if (isset($conf['strPad.']['padWith']) && (string)$conf['strPad.']['padWith'] !== '') {
2429 $padWith = isset($conf['strPad.']['padWith.']) ? $this->stdWrap($conf['strPad.']['padWith'], $conf['strPad.']['padWith.']) : $conf['strPad.']['padWith'];
2430 }
2431 if (!empty($conf['strPad.']['type'])) {
2432 $type = isset($conf['strPad.']['type.']) ? $this->stdWrap($conf['strPad.']['type'], $conf['strPad.']['type.']) : $conf['strPad.']['type'];
2433 if (strtolower($type) === 'left') {
2434 $padType = STR_PAD_LEFT;
2435 } elseif (strtolower($type) === 'both') {
2436 $padType = STR_PAD_BOTH;
2437 }
2438 }
2439 return str_pad($content, $length, $padWith, $padType);
2440 }
2441
2442 /**
2443 * stdWrap
2444 * A recursive call of the stdWrap function set
2445 * This enables the user to execute stdWrap functions in another than the predefined order
2446 * It modifies the content, not the property
2447 * while the new feature of chained stdWrap functions modifies the property and not the content
2448 *
2449 * @param string $content Input value undergoing processing in this function.
2450 * @param array $conf stdWrap properties for stdWrap.
2451 * @return string The processed input value
2452 */
2453 public function stdWrap_stdWrap($content = '', $conf = [])
2454 {
2455 return $this->stdWrap($content, $conf['stdWrap.']);
2456 }
2457
2458 /**
2459 * stdWrap process hook
2460 * can be used by extensions authors to modify the behaviour of stdWrap functions to their needs
2461 * this hook executes functions directly after the recursive stdWrap function call but still before the content gets modified
2462 *
2463 * @param string $content Input value undergoing processing in these functions.
2464 * @param array $conf All stdWrap properties, not just the ones for a particular function.
2465 * @return string The processed input value
2466 */
2467 public function stdWrap_stdWrapProcess($content = '', $conf = [])
2468 {
2469 foreach ($this->stdWrapHookObjects as $hookObject) {
2470 /** @var ContentObjectStdWrapHookInterface $hookObject */
2471 $content = $hookObject->stdWrapProcess($content, $conf, $this);
2472 }
2473 return $content;
2474 }
2475
2476 /**
2477 * required
2478 * Will immediately stop rendering and return an empty value
2479 * when there is no content at this point
2480 *
2481 * @param string $content Input value undergoing processing in this function.
2482 * @return string The processed input value
2483 */
2484 public function stdWrap_required($content = '')
2485 {
2486 if ((string)$content === '') {
2487 $content = '';
2488 $this->stopRendering[$this->stdWrapRecursionLevel] = true;
2489 }
2490 return $content;
2491 }
2492
2493 /**
2494 * if
2495 * Will immediately stop rendering and return an empty value
2496 * when the result of the checks returns FALSE
2497 *
2498 * @param string $content Input value undergoing processing in this function.
2499 * @param array $conf stdWrap properties for if.
2500 * @return string The processed input value
2501 */
2502 public function stdWrap_if($content = '', $conf = [])
2503 {
2504 if (empty($conf['if.']) || $this->checkIf($conf['if.'])) {
2505 return $content;
2506 }
2507 $this->stopRendering[$this->stdWrapRecursionLevel] = true;
2508 return '';
2509 }
2510
2511 /**
2512 * fieldRequired
2513 * Will immediately stop rendering and return an empty value
2514 * when there is no content in the field given by fieldRequired
2515 *
2516 * @param string $content Input value undergoing processing in this function.
2517 * @param array $conf stdWrap properties for fieldRequired.
2518 * @return string The processed input value
2519 */
2520 public function stdWrap_fieldRequired($content = '', $conf = [])
2521 {
2522 if (!trim($this->data[$conf['fieldRequired']])) {
2523 $content = '';
2524 $this->stopRendering[$this->stdWrapRecursionLevel] = true;
2525 }
2526 return $content;
2527 }
2528
2529 /**
2530 * csConv
2531 * Will convert the current chracter set of the content to the one given in csConv
2532 *
2533 * @param string $content Input value undergoing processing in this function.
2534 * @param array $conf stdWrap properties for csConv.
2535 * @return string The processed input value
2536 */
2537 public function stdWrap_csConv($content = '', $conf = [])
2538 {
2539 if (!empty($conf['csConv'])) {
2540 /** @var CharsetConverter $charsetConverter */
2541 $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
2542 $output = $charsetConverter->conv($content, $charsetConverter->parse_charset($conf['csConv']), 'utf-8');
2543 return $output ?: $content;
2544 } else {
2545 return $content;
2546 }
2547 }
2548
2549 /**
2550 * parseFunc
2551 * Will parse the content based on functions given as stdWrap properties
2552 * Heavily used together with RTE based content
2553 *
2554 * @param string $content Input value undergoing processing in this function.
2555 * @param array $conf stdWrap properties for parseFunc.
2556 * @return string The processed input value
2557 */
2558 public function stdWrap_parseFunc($content = '', $conf = [])
2559 {
2560 return $this->parseFunc($content, $conf['parseFunc.'], $conf['parseFunc']);
2561 }
2562
2563 /**
2564 * HTMLparser
2565 * Will parse HTML content based on functions given as stdWrap properties
2566 * Heavily used together with RTE based content
2567 *
2568 * @param string $content Input value undergoing processing in this function.
2569 * @param array $conf stdWrap properties for HTMLparser.
2570 * @return string The processed input value
2571 */
2572 public function stdWrap_HTMLparser($content = '', $conf = [])
2573 {
2574 if (is_array($conf['HTMLparser.'])) {
2575 $content = $this->HTMLparser_TSbridge($content, $conf['HTMLparser.']);
2576 }
2577 return $content;
2578 }
2579
2580 /**
2581 * split
2582 * Will split the content by a given token and treat the results separately
2583 * Automatically fills 'current' with a single result
2584 *
2585 * @param string $content Input value undergoing processing in this function.
2586 * @param array $conf stdWrap properties for split.
2587 * @return string The processed input value
2588 */
2589 public function stdWrap_split($content = '', $conf = [])
2590 {
2591 return $this->splitObj($content, $conf['split.']);
2592 }
2593
2594 /**
2595 * replacement
2596 * Will execute replacements on the content (optionally with preg-regex)
2597 *
2598 * @param string $content Input value undergoing processing in this function.
2599 * @param array $conf stdWrap properties for replacement.
2600 * @return string The processed input value
2601 */
2602 public function stdWrap_replacement($content = '', $conf = [])
2603 {
2604 return $this->replacement($content, $conf['replacement.']);
2605 }
2606
2607 /**
2608 * prioriCalc
2609 * Will use the content as a mathematical term and calculate the result
2610 * Can be set to 1 to just get a calculated value or 'intval' to get the integer of the result
2611 *
2612 * @param string $content Input value undergoing processing in this function.
2613 * @param array $conf stdWrap properties for prioriCalc.
2614 * @return string The processed input value
2615 */
2616 public function stdWrap_prioriCalc($content = '', $conf = [])
2617 {
2618 $content = MathUtility::calculateWithParentheses($content);
2619 if ($conf['prioriCalc'] === 'intval') {
2620 $content = (int)$content;
2621 }
2622 return $content;
2623 }
2624
2625 /**
2626 * char
2627 * Returns a one-character string containing the character specified by ascii code.
2628 *
2629 * Reliable results only for character codes in the integer range 0 - 127.
2630 *
2631 * @see http://php.net/manual/en/function.chr.php
2632 * @param string $content Input value undergoing processing in this function.
2633 * @param array $conf stdWrap properties for char.
2634 * @return string The processed input value
2635 */
2636 public function stdWrap_char($content = '', $conf = [])
2637 {
2638 return chr((int)$conf['char']);
2639 }
2640
2641 /**
2642 * intval
2643 * Will return an integer value of the current content
2644 *
2645 * @param string $content Input value undergoing processing in this function.
2646 * @return string The processed input value
2647 */
2648 public function stdWrap_intval($content = '')
2649 {
2650 return (int)$content;
2651 }
2652
2653 /**
2654 * Will return a hashed value of the current content
2655 *
2656 * @param string $content Input value undergoing processing in this function.
2657 * @param array $conf stdWrap properties for hash.
2658 * @return string The processed input value
2659 * @link http://php.net/manual/de/function.hash-algos.php for a list of supported hash algorithms
2660 */
2661 public function stdWrap_hash($content = '', array $conf = [])
2662 {
2663 $algorithm = isset($conf['hash.']) ? $this->stdWrap($conf['hash'], $conf['hash.']) : $conf['hash'];
2664 if (function_exists('hash') && in_array($algorithm, hash_algos())) {
2665 return hash($algorithm, $content);
2666 }
2667 // Non-existing hashing algorithm
2668 return '';
2669 }
2670
2671 /**
2672 * stdWrap_round will return a rounded number with ceil(), floor() or round(), defaults to round()
2673 * Only the english number format is supported . (dot) as decimal point
2674 *
2675 * @param string $content Input value undergoing processing in this function.
2676 * @param array $conf stdWrap properties for round.
2677 * @return string The processed input value
2678 */
2679 public function stdWrap_round($content = '', $conf = [])
2680 {
2681 return $this->round($content, $conf['round.']);
2682 }
2683
2684 /**
2685 * numberFormat
2686 * Will return a formatted number based on configuration given as stdWrap properties
2687 *
2688 * @param string $content Input value undergoing processing in this function.
2689 * @param array $conf stdWrap properties for numberFormat.
2690 * @return string The processed input value
2691 */
2692 public function stdWrap_numberFormat($content = '', $conf = [])
2693 {
2694 return $this->numberFormat($content, $conf['numberFormat.']);
2695 }
2696
2697 /**
2698 * expandList
2699 * Will return a formatted number based on configuration given as stdWrap properties
2700 *
2701 * @param string $content Input value undergoing processing in this function.
2702 * @return string The processed input value
2703 */
2704 public function stdWrap_expandList($content = '')
2705 {
2706 return GeneralUtility::expandList($content);
2707 }
2708
2709 /**
2710 * date
2711 * Will return a formatted date based on configuration given according to PHP date/gmdate properties
2712 * Will return gmdate when the property GMT returns TRUE
2713 *
2714 * @param string $content Input value undergoing processing in this function.
2715 * @param array $conf stdWrap properties for date.
2716 * @return string The processed input value
2717 */
2718 public function stdWrap_date($content = '', $conf = [])
2719 {
2720 // Check for zero length string to mimic default case of date/gmdate.
2721 $content = (string)$content === '' ? $GLOBALS['EXEC_TIME'] : (int)$content;
2722 $content = $conf['date.']['GMT'] ? gmdate($conf['date'], $content) : date($conf['date'], $content);
2723 return $content;
2724 }
2725
2726 /**
2727 * strftime
2728 * Will return a formatted date based on configuration given according to PHP strftime/gmstrftime properties
2729 * Will return gmstrftime when the property GMT returns TRUE
2730 *
2731 * @param string $content Input value undergoing processing in this function.
2732 * @param array $conf stdWrap properties for strftime.
2733 * @return string The processed input value
2734 */
2735 public function stdWrap_strftime($content = '', $conf = [])
2736 {
2737 // Check for zero length string to mimic default case of strtime/gmstrftime
2738 $content = (string)$content === '' ? $GLOBALS['EXEC_TIME'] : (int)$content;
2739 $content = $conf['strftime.']['GMT'] ? gmstrftime($conf['strftime'], $content) : strftime($conf['strftime'], $content);
2740 if (!empty($conf['strftime.']['charset'])) {
2741 /** @var CharsetConverter $charsetConverter */
2742 $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
2743 $output = $charsetConverter->conv($content, $charsetConverter->parse_charset($conf['strftime.']['charset']), 'utf-8');
2744 return $output ?: $content;
2745 }
2746 return $content;
2747 }
2748
2749 /**
2750 * strtotime
2751 * Will return a timestamp based on configuration given according to PHP strtotime
2752 *
2753 * @param string $content Input value undergoing processing in this function.
2754 * @param array $conf stdWrap properties for strtotime.
2755 * @return string The processed input value
2756 */
2757 public function stdWrap_strtotime($content = '', $conf = [])
2758 {
2759 if ($conf['strtotime'] !== '1') {
2760 $content .= ' ' . $conf['strtotime'];
2761 }
2762 return strtotime($content, $GLOBALS['EXEC_TIME']);
2763 }
2764
2765 /**
2766 * age
2767 * Will return the age of a given timestamp based on configuration given by stdWrap properties
2768 *
2769 * @param string $content Input value undergoing processing in this function.
2770 * @param array $conf stdWrap properties for age.
2771 * @return string The processed input value
2772 */
2773 public function stdWrap_age($content = '', $conf = [])
2774 {
2775 return $this->calcAge((int)$GLOBALS['EXEC_TIME'] - (int)$content, $conf['age']);
2776 }
2777
2778 /**
2779 * case
2780 * Will transform the content to be upper or lower case only
2781 * Leaves HTML tags untouched
2782 *
2783 * @param string $content Input value undergoing processing in this function.
2784 * @param array $conf stdWrap properties for case.
2785 * @return string The processed input value
2786 */
2787 public function stdWrap_case($content = '', $conf = [])
2788 {
2789 return $this->HTMLcaseshift($content, $conf['case']);
2790 }
2791
2792 /**
2793 * bytes
2794 * Will return the size of a given number in Bytes *
2795 *
2796 * @param string $content Input value undergoing processing in this function.
2797 * @param array $conf stdWrap properties for bytes.
2798 * @return string The processed input value
2799 */
2800 public function stdWrap_bytes($content = '', $conf = [])
2801 {
2802 return GeneralUtility::formatSize($content, $conf['bytes.']['labels'], $conf['bytes.']['base']);
2803 }
2804
2805 /**
2806 * substring
2807 * Will return a substring based on position information given by stdWrap properties
2808 *
2809 * @param string $content Input value undergoing processing in this function.
2810 * @param array $conf stdWrap properties for substring.
2811 * @return string The processed input value
2812 */
2813 public function stdWrap_substring($content = '', $conf = [])
2814 {
2815 return $this->substring($content, $conf['substring']);
2816 }
2817
2818 /**
2819 * removeBadHTML
2820 * Removes HTML tags based on stdWrap properties
2821 *
2822 * @param string $content Input value undergoing processing in this function.
2823 * @return string The processed input value
2824 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
2825 */
2826 public function stdWrap_removeBadHTML($content = '')
2827 {
2828 return $this->removeBadHTML($content);
2829 }
2830
2831 /**
2832 * cropHTML
2833 * Crops content to a given size while leaving HTML tags untouched
2834 *
2835 * @param string $content Input value undergoing processing in this function.
2836 * @param array $conf stdWrap properties for cropHTML.
2837 * @return string The processed input value
2838 */
2839 public function stdWrap_cropHTML($content = '', $conf = [])
2840 {
2841 return $this->cropHTML($content, $conf['cropHTML']);
2842 }
2843
2844 /**
2845 * stripHtml
2846 * Copmletely removes HTML tags from content
2847 *
2848 * @param string $content Input value undergoing processing in this function.
2849 * @return string The processed input value
2850 */
2851 public function stdWrap_stripHtml($content = '')
2852 {
2853 return strip_tags($content);
2854 }
2855
2856 /**
2857 * crop
2858 * Crops content to a given size without caring about HTML tags
2859 *
2860 * @param string $content Input value undergoing processing in this function.
2861 * @param array $conf stdWrap properties for crop.
2862 * @return string The processed input value
2863 */
2864 public function stdWrap_crop($content = '', $conf = [])
2865 {
2866 return $this->crop($content, $conf['crop']);
2867 }
2868
2869 /**
2870 * rawUrlEncode
2871 * Encodes content to be used within URLs
2872 *
2873 * @param string $content Input value undergoing processing in this function.
2874 * @return string The processed input value
2875 */
2876 public function stdWrap_rawUrlEncode($content = '')
2877 {
2878 return rawurlencode($content);
2879 }
2880
2881 /**
2882 * htmlSpecialChars
2883 * Transforms HTML tags to readable text by replacing special characters with their HTML entity
2884 * When preserveEntities returns TRUE, existing entities will be left untouched
2885 *
2886 * @param string $content Input value undergoing processing in this function.
2887 * @param array $conf stdWrap properties for htmlSpecalChars.
2888 * @return string The processed input value
2889 */
2890 public function stdWrap_htmlSpecialChars($content = '', $conf = [])
2891 {
2892 if (!empty($conf['htmlSpecialChars.']['preserveEntities'])) {
2893 $content = htmlspecialchars($content, ENT_COMPAT, 'UTF-8', false);
2894 } else {
2895 $content = htmlspecialchars($content);
2896 }
2897 return $content;
2898 }
2899
2900 /**
2901 * encodeForJavaScriptValue
2902 * Escapes content to be used inside JavaScript strings. No quotes are added around the value
2903 * as this can easily be done in TypoScript
2904 *
2905 * @param string $content Input value undergoing processing in this function
2906 * @return string The processed input value
2907 */
2908 public function stdWrap_encodeForJavaScriptValue($content = '')
2909 {
2910 return GeneralUtility::quoteJSvalue($content);
2911 }
2912
2913 /**
2914 * doubleBrTag
2915 * Searches for double line breaks and replaces them with the given value
2916 *
2917 * @param string $content Input value undergoing processing in this function.
2918 * @param array $conf stdWrap properties for doubleBrTag.
2919 * @return string The processed input value
2920 */
2921 public function stdWrap_doubleBrTag($content = '', $conf = [])
2922 {
2923 return preg_replace('/
2924 ?
2925 [ ]*
2926 ?
2927 /', $conf['doubleBrTag'], $content);
2928 }
2929
2930 /**
2931 * br
2932 * Searches for single line breaks and replaces them with a <br />/<br> tag
2933 * according to the doctype
2934 *
2935 * @param string $content Input value undergoing processing in this function.
2936 * @param array $conf stdWrap properties for br.
2937 * @return string The processed input value
2938 */
2939 public function stdWrap_br($content = '')
2940 {
2941 return nl2br($content, !empty($this->getTypoScriptFrontendController()->xhtmlDoctype));
2942 }
2943
2944 /**
2945 * brTag
2946 * Searches for single line feeds and replaces them with the given value
2947 *
2948 * @param string $content Input value undergoing processing in this function.
2949 * @param array $conf stdWrap properties for brTag.
2950 * @return string The processed input value
2951 */
2952 public function stdWrap_brTag($content = '', $conf = [])
2953 {
2954 return str_replace(LF, $conf['brTag'], $content);
2955 }
2956
2957 /**
2958 * encapsLines
2959 * Modifies text blocks by searching for lines which are not surrounded by HTML tags yet
2960 * and wrapping them with values given by stdWrap properties
2961 *
2962 * @param string $content Input value undergoing processing in this function.
2963 * @param array $conf stdWrap properties for erncapsLines.
2964 * @return string The processed input value
2965 */
2966 public function stdWrap_encapsLines($content = '', $conf = [])
2967 {
2968 return $this->encaps_lineSplit($content, $conf['encapsLines.']);
2969 }
2970
2971 /**
2972 * keywords
2973 * Transforms content into a CSV list to be used i.e. as keywords within a meta tag
2974 *
2975 * @param string $content Input value undergoing processing in this function.
2976 * @return string The processed input value
2977 */