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