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