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