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