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