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