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