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