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