[TASK] Streamline return tags in phpdocs
[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 $storeArrDat = $this->getTypoScriptFrontendController()->sys_page->getHash($storeKey);
1668 if (is_array($storeArrDat)) {
1669 $storeArr = $storeArrDat;
1670 // Setting cache:
1671 $this->substMarkerCache[$storeKey] = $storeArr;
1672 $timeTracker->setTSlogMessage('Cached from DB', 0);
1673 } else {
1674 // Finding subparts and substituting them with the subpart as a marker
1675 foreach ($sPkeys as $sPK) {
1676 $content = $this->substituteSubpart($content, $sPK, $sPK);
1677 }
1678 // Finding subparts and wrapping them with markers
1679 foreach ($wPkeys as $wPK) {
1680 $content = $this->substituteSubpart($content, $wPK, [
1681 $wPK,
1682 $wPK
1683 ]);
1684 }
1685
1686 $storeArr = [];
1687 // search all markers in the content
1688 $result = preg_match_all('/###([^#](?:[^#]*+|#{1,2}[^#])+)###/', $content, $markersInContent);
1689 if ($result !== false && !empty($markersInContent[1])) {
1690 $keysToReplaceFlipped = array_flip($keysToReplace);
1691 $regexKeys = [];
1692 $wrappedKeys = [];
1693 // Traverse keys and quote them for reg ex.
1694 foreach ($markersInContent[1] as $key) {
1695 if (isset($keysToReplaceFlipped['###' . $key . '###'])) {
1696 $regexKeys[] = preg_quote($key, '/');
1697 $wrappedKeys[] = '###' . $key . '###';
1698 }
1699 }
1700 $regex = '/###(?:' . implode('|', $regexKeys) . ')###/';
1701 $storeArr['c'] = preg_split($regex, $content); // contains all content parts around markers
1702 $storeArr['k'] = $wrappedKeys; // contains all markers incl. ###
1703 // Setting cache:
1704 $this->substMarkerCache[$storeKey] = $storeArr;
1705 // Storing the cached data:
1706 $this->getTypoScriptFrontendController()->sys_page->storeHash($storeKey, $storeArr, 'substMarkArrayCached');
1707 }
1708 $timeTracker->setTSlogMessage('Parsing', 0);
1709 }
1710 }
1711 if (!empty($storeArr['k']) && is_array($storeArr['k'])) {
1712 // Substitution/Merging:
1713 // Merging content types together, resetting
1714 $valueArr = array_merge($markContentArray, $subpartContentArray, $wrappedSubpartContentArray);
1715 $wSCA_reg = [];
1716 $content = '';
1717 // Traversing the keyList array and merging the static and dynamic content
1718 foreach ($storeArr['k'] as $n => $keyN) {
1719 // add content before marker
1720 $content .= $storeArr['c'][$n];
1721 if (!is_array($valueArr[$keyN])) {
1722 // fetch marker replacement from $markContentArray or $subpartContentArray
1723 $content .= $valueArr[$keyN];
1724 } else {
1725 if (!isset($wSCA_reg[$keyN])) {
1726 $wSCA_reg[$keyN] = 0;
1727 }
1728 // fetch marker replacement from $wrappedSubpartContentArray
1729 $content .= $valueArr[$keyN][$wSCA_reg[$keyN] % 2];
1730 $wSCA_reg[$keyN]++;
1731 }
1732 }
1733 // add remaining content
1734 $content .= $storeArr['c'][count($storeArr['k'])];
1735 }
1736 $timeTracker->pull();
1737 return $content;
1738 }
1739
1740 /**
1741 * Traverses the input $markContentArray array and for each key the marker
1742 * by the same name (possibly wrapped and in upper case) will be
1743 * substituted with the keys value in the array.
1744 *
1745 * This is very useful if you have a data-record to substitute in some
1746 * content. In particular when you use the $wrap and $uppercase values to
1747 * pre-process the markers. Eg. a key name like "myfield" could effectively
1748 * be represented by the marker "###MYFIELD###" if the wrap value
1749 * was "###|###" and the $uppercase boolean TRUE.
1750 *
1751 * @param string $content The content stream, typically HTML template content.
1752 * @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.
1753 * @param string $wrap A wrap value - [part 1] | [part 2] - for the markers before substitution
1754 * @param bool $uppercase If set, all marker string substitution is done with upper-case markers.
1755 * @param bool $deleteUnused If set, all unused marker are deleted.
1756 * @return string The processed output stream
1757 * @see substituteMarker(), substituteMarkerInObject(), TEMPLATE()
1758 */
1759 public function substituteMarkerArray($content, array $markContentArray, $wrap = '', $uppercase = false, $deleteUnused = false)
1760 {
1761 return $this->templateService->substituteMarkerArray($content, $markContentArray, $wrap, $uppercase, $deleteUnused);
1762 }
1763
1764 /**
1765 * Substitute marker array in an array of values
1766 *
1767 * @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)
1768 * @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.
1769 * @return mixed The processed input variable.
1770 * @see substituteMarker()
1771 */
1772 public function substituteMarkerInObject(&$tree, array $markContentArray)
1773 {
1774 if (is_array($tree)) {
1775 foreach ($tree as $key => $value) {
1776 $this->substituteMarkerInObject($tree[$key], $markContentArray);
1777 }
1778 } else {
1779 $tree = $this->substituteMarkerArray($tree, $markContentArray);
1780 }
1781 return $tree;
1782 }
1783
1784 /**
1785 * Replaces all markers and subparts in a template with the content provided in the structured array.
1786 *
1787 * @param string $content
1788 * @param array $markersAndSubparts
1789 * @param string $wrap
1790 * @param bool $uppercase
1791 * @param bool $deleteUnused
1792 * @return string
1793 */
1794 public function substituteMarkerAndSubpartArrayRecursive($content, array $markersAndSubparts, $wrap = '', $uppercase = false, $deleteUnused = false)
1795 {
1796 return $this->templateService->substituteMarkerAndSubpartArrayRecursive($content, $markersAndSubparts, $wrap, $uppercase, $deleteUnused);
1797 }
1798
1799 /**
1800 * Adds elements to the input $markContentArray based on the values from
1801 * the fields from $fieldList found in $row
1802 *
1803 * @param array $markContentArray Array with key/values being marker-strings/substitution values.
1804 * @param array $row An array with keys found in the $fieldList (typically a record) which values should be moved to the $markContentArray
1805 * @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)
1806 * @param bool $nl2br If set, all values added to $markContentArray will be nl2br()'ed
1807 * @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 "###
1808 * @param bool $HSC If set, all values are passed through htmlspecialchars() - RECOMMENDED to avoid most obvious XSS and maintain XHTML compliance.
1809 * @return array The modified $markContentArray
1810 */
1811 public function fillInMarkerArray(array $markContentArray, array $row, $fieldList = '', $nl2br = true, $prefix = 'FIELD_', $HSC = false)
1812 {
1813 $tsfe = $this->getTypoScriptFrontendController();
1814 if ($fieldList) {
1815 $fArr = GeneralUtility::trimExplode(',', $fieldList, true);
1816 foreach ($fArr as $field) {
1817 $markContentArray['###' . $prefix . $field . '###'] = $nl2br ? nl2br($row[$field], !empty($tsfe->xhtmlDoctype)) : $row[$field];
1818 }
1819 } else {
1820 if (is_array($row)) {
1821 foreach ($row as $field => $value) {
1822 if (!MathUtility::canBeInterpretedAsInteger($field)) {
1823 if ($HSC) {
1824 $value = htmlspecialchars($value);
1825 }
1826 $markContentArray['###' . $prefix . $field . '###'] = $nl2br ? nl2br($value, !empty($tsfe->xhtmlDoctype)) : $value;
1827 }
1828 }
1829 }
1830 }
1831 return $markContentArray;
1832 }
1833
1834 /**
1835 * Sets the current file object during iterations over files.
1836 *
1837 * @param File $fileObject The file object.
1838 */
1839 public function setCurrentFile($fileObject)
1840 {
1841 $this->currentFile = $fileObject;
1842 }
1843
1844 /**
1845 * Gets the current file object during iterations over files.
1846 *
1847 * @return File The current file object.
1848 */
1849 public function getCurrentFile()
1850 {
1851 return $this->currentFile;
1852 }
1853
1854 /***********************************************
1855 *
1856 * "stdWrap" + sub functions
1857 *
1858 ***********************************************/
1859 /**
1860 * The "stdWrap" function. This is the implementation of what is known as "stdWrap properties" in TypoScript.
1861 * Basically "stdWrap" performs some processing of a value based on properties in the input $conf array(holding the TypoScript "stdWrap properties")
1862 * 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.
1863 *
1864 * If $this->alternativeData is an array it's used instead of the $this->data array in ->getData
1865 *
1866 * @param string $content Input value undergoing processing in this function. Possibly substituted by other values fetched from another source.
1867 * @param array $conf TypoScript "stdWrap properties".
1868 * @return string The processed input value
1869 */
1870 public function stdWrap($content = '', $conf = [])
1871 {
1872 $content = (string)$content;
1873 // If there is any hook object, activate all of the process and override functions.
1874 // The hook interface ContentObjectStdWrapHookInterface takes care that all 4 methods exist.
1875 if ($this->stdWrapHookObjects) {
1876 $conf['stdWrapPreProcess'] = 1;
1877 $conf['stdWrapOverride'] = 1;
1878 $conf['stdWrapProcess'] = 1;
1879 $conf['stdWrapPostProcess'] = 1;
1880 }
1881
1882 if (!is_array($conf) || !$conf) {
1883 return $content;
1884 }
1885
1886 // Cache handling
1887 if (is_array($conf['cache.'])) {
1888 $conf['cache.']['key'] = $this->stdWrap($conf['cache.']['key'], $conf['cache.']['key.']);
1889 $conf['cache.']['tags'] = $this->stdWrap($conf['cache.']['tags'], $conf['cache.']['tags.']);
1890 $conf['cache.']['lifetime'] = $this->stdWrap($conf['cache.']['lifetime'], $conf['cache.']['lifetime.']);
1891 $conf['cacheRead'] = 1;
1892 $conf['cacheStore'] = 1;
1893 }
1894 // The configuration is sorted and filtered by intersection with the defined stdWrapOrder.
1895 $sortedConf = array_keys(array_intersect_key($this->stdWrapOrder, $conf));
1896 // Functions types that should not make use of nested stdWrap function calls to avoid conflicts with internal TypoScript used by these functions
1897 $stdWrapDisabledFunctionTypes = 'cObject,functionName,stdWrap';
1898 // Additional Array to check whether a function has already been executed
1899 $isExecuted = [];
1900 // Additional switch to make sure 'required', 'if' and 'fieldRequired'
1901 // will still stop rendering immediately in case they return FALSE
1902 $this->stdWrapRecursionLevel++;
1903 $this->stopRendering[$this->stdWrapRecursionLevel] = false;
1904 // execute each function in the predefined order
1905 foreach ($sortedConf as $stdWrapName) {
1906 // eliminate the second key of a pair 'key'|'key.' to make sure functions get called only once and check if rendering has been stopped
1907 if (!$isExecuted[$stdWrapName] && !$this->stopRendering[$this->stdWrapRecursionLevel]) {
1908 $functionName = rtrim($stdWrapName, '.');
1909 $functionProperties = $functionName . '.';
1910 $functionType = $this->stdWrapOrder[$functionName];
1911 // If there is any code on the next level, check if it contains "official" stdWrap functions
1912 // if yes, execute them first - will make each function stdWrap aware
1913 // so additional stdWrap calls within the functions can be removed, since the result will be the same
1914 if (!empty($conf[$functionProperties]) && !GeneralUtility::inList($stdWrapDisabledFunctionTypes, $functionType)) {
1915 if (array_intersect_key($this->stdWrapOrder, $conf[$functionProperties])) {
1916 $conf[$functionName] = $this->stdWrap($conf[$functionName], $conf[$functionProperties]);
1917 }
1918 }
1919 // Check if key is still containing something, since it might have been changed by next level stdWrap before
1920 if ((isset($conf[$functionName]) || $conf[$functionProperties]) && ($functionType !== 'boolean' || $conf[$functionName])) {
1921 // Get just that part of $conf that is needed for the particular function
1922 $singleConf = [
1923 $functionName => $conf[$functionName],
1924 $functionProperties => $conf[$functionProperties]
1925 ];
1926 // In this special case 'spaceBefore' and 'spaceAfter' need additional stuff from 'space.''
1927 if ($functionName === 'spaceBefore' || $functionName === 'spaceAfter') {
1928 $singleConf['space.'] = $conf['space.'];
1929 }
1930 // Hand over the whole $conf array to the stdWrapHookObjects
1931 if ($functionType === 'hook') {
1932 $singleConf = $conf;
1933 }
1934 // Add both keys - with and without the dot - to the set of executed functions
1935 $isExecuted[$functionName] = true;
1936 $isExecuted[$functionProperties] = true;
1937 // Call the function with the prefix stdWrap_ to make sure nobody can execute functions just by adding their name to the TS Array
1938 $functionName = 'stdWrap_' . $functionName;
1939 $content = $this->{$functionName}($content, $singleConf);
1940 } elseif ($functionType === 'boolean' && !$conf[$functionName]) {
1941 $isExecuted[$functionName] = true;
1942 $isExecuted[$functionProperties] = true;
1943 }
1944 }
1945 }
1946 unset($this->stopRendering[$this->stdWrapRecursionLevel]);
1947 $this->stdWrapRecursionLevel--;
1948
1949 return $content;
1950 }
1951
1952 /**
1953 * Gets a configuration value by passing them through stdWrap first and taking a default value if stdWrap doesn't yield a result.
1954 *
1955 * @param string $key The config variable key (from TS array).
1956 * @param array $config The TypoScript array.
1957 * @param string $defaultValue Optional default value.
1958 * @return string Value of the config variable
1959 */
1960 public function stdWrapValue($key, array $config, $defaultValue = '')
1961 {
1962 if (isset($config[$key])) {
1963 if (!isset($config[$key . '.'])) {
1964 return $config[$key];
1965 }
1966 } elseif (isset($config[$key . '.'])) {
1967 $config[$key] = '';
1968 } else {
1969 return $defaultValue;
1970 }
1971 $stdWrapped = $this->stdWrap($config[$key], $config[$key . '.']);
1972 return $stdWrapped ?: $defaultValue;
1973 }
1974
1975 /**
1976 * stdWrap pre process hook
1977 * can be used by extensions authors to modify the behaviour of stdWrap functions to their needs
1978 * this hook will execute functions before any other stdWrap function can modify anything
1979 *
1980 * @param string $content Input value undergoing processing in these functions.
1981 * @param array $conf All stdWrap properties, not just the ones for a particular function.
1982 * @return string The processed input value
1983 */
1984 public function stdWrap_stdWrapPreProcess($content = '', $conf = [])
1985 {
1986 foreach ($this->stdWrapHookObjects as $hookObject) {
1987 /** @var ContentObjectStdWrapHookInterface $hookObject */
1988 $content = $hookObject->stdWrapPreProcess($content, $conf, $this);
1989 }
1990 return $content;
1991 }
1992
1993 /**
1994 * Check if content was cached before (depending on the given cache key)
1995 *
1996 * @param string $content Input value undergoing processing in these functions.
1997 * @param array $conf All stdWrap properties, not just the ones for a particular function.
1998 * @return string The processed input value
1999 */
2000 public function stdWrap_cacheRead($content = '', $conf = [])
2001 {
2002 if (!isset($conf['cache.'])) {
2003 return $content;
2004 }
2005 $result = $this->getFromCache($conf['cache.']);
2006 return $result === false ? $content : $result;
2007 }
2008
2009 /**
2010 * Add tags to page cache (comma-separated list)
2011 *
2012 * @param string $content Input value undergoing processing in these functions.
2013 * @param array $conf All stdWrap properties, not just the ones for a particular function.
2014 * @return string The processed input value
2015 */
2016 public function stdWrap_addPageCacheTags($content = '', $conf = [])
2017 {
2018 $tags = isset($conf['addPageCacheTags.'])
2019 ? $this->stdWrap($conf['addPageCacheTags'], $conf['addPageCacheTags.'])
2020 : $conf['addPageCacheTags'];
2021 if (!empty($tags)) {
2022 $cacheTags = GeneralUtility::trimExplode(',', $tags, true);
2023 $this->getTypoScriptFrontendController()->addCacheTags($cacheTags);
2024 }
2025 return $content;
2026 }
2027
2028 /**
2029 * setContentToCurrent
2030 * actually it just does the contrary: Sets the value of 'current' based on current content
2031 *
2032 * @param string $content Input value undergoing processing in this function.
2033 * @return string The processed input value
2034 */
2035 public function stdWrap_setContentToCurrent($content = '')
2036 {
2037 $this->data[$this->currentValKey] = $content;
2038 return $content;
2039 }
2040
2041 /**
2042 * setCurrent
2043 * Sets the value of 'current' based on the outcome of stdWrap operations
2044 *
2045 * @param string $content Input value undergoing processing in this function.
2046 * @param array $conf stdWrap properties for setCurrent.
2047 * @return string The processed input value
2048 */
2049 public function stdWrap_setCurrent($content = '', $conf = [])
2050 {
2051 $this->data[$this->currentValKey] = $conf['setCurrent'];
2052 return $content;
2053 }
2054
2055 /**
2056 * lang
2057 * Translates content based on the language currently used by the FE
2058 *
2059 * @param string $content Input value undergoing processing in this function.
2060 * @param array $conf stdWrap properties for lang.
2061 * @return string The processed input value
2062 */
2063 public function stdWrap_lang($content = '', $conf = [])
2064 {
2065 $tsfe = $this->getTypoScriptFrontendController();
2066 if (isset($conf['lang.']) && $tsfe->config['config']['language'] && isset($conf['lang.'][$tsfe->config['config']['language']])) {
2067 $content = $conf['lang.'][$tsfe->config['config']['language']];
2068 }
2069 return $content;
2070 }
2071
2072 /**
2073 * data
2074 * Gets content from different sources based on getText functions, makes use of alternativeData, when set
2075 *
2076 * @param string $content Input value undergoing processing in this function.
2077 * @param array $conf stdWrap properties for data.
2078 * @return string The processed input value
2079 */
2080 public function stdWrap_data($content = '', $conf = [])
2081 {
2082 $content = $this->getData($conf['data'], is_array($this->alternativeData) ? $this->alternativeData : $this->data);
2083 // This must be unset directly after
2084 $this->alternativeData = '';
2085 return $content;
2086 }
2087
2088 /**
2089 * field
2090 * Gets content from a DB field
2091 *
2092 * @param string $content Input value undergoing processing in this function.
2093 * @param array $conf stdWrap properties for field.
2094 * @return string The processed input value
2095 */
2096 public function stdWrap_field($content = '', $conf = [])
2097 {
2098 return $this->getFieldVal($conf['field']);
2099 }
2100
2101 /**
2102 * current
2103 * Gets content that has been perviously set as 'current'
2104 * Can be set via setContentToCurrent or setCurrent or will be set automatically i.e. inside the split function
2105 *
2106 * @param string $content Input value undergoing processing in this function.
2107 * @param array $conf stdWrap properties for current.
2108 * @return string The processed input value
2109 */
2110 public function stdWrap_current($content = '', $conf = [])
2111 {
2112 return $this->data[$this->currentValKey];
2113 }
2114
2115 /**
2116 * cObject
2117 * Will replace the content with the value of an official TypoScript cObject
2118 * like TEXT, COA, HMENU
2119 *
2120 * @param string $content Input value undergoing processing in this function.
2121 * @param array $conf stdWrap properties for cObject.
2122 * @return string The processed input value
2123 */
2124 public function stdWrap_cObject($content = '', $conf = [])
2125 {
2126 return $this->cObjGetSingle($conf['cObject'], $conf['cObject.'], '/stdWrap/.cObject');
2127 }
2128
2129 /**
2130 * numRows
2131 * Counts the number of returned records of a DB operation
2132 * makes use of select internally
2133 *
2134 * @param string $content Input value undergoing processing in this function.
2135 * @param array $conf stdWrap properties for numRows.
2136 * @return string The processed input value
2137 */
2138 public function stdWrap_numRows($content = '', $conf = [])
2139 {
2140 return $this->numRows($conf['numRows.']);
2141 }
2142
2143 /**
2144 * filelist
2145 * Will create a list of files based on some additional parameters
2146 *
2147 * @param string $content Input value undergoing processing in this function.
2148 * @param array $conf stdWrap properties for filelist.
2149 * @return string The processed input value
2150 */
2151 public function stdWrap_filelist($content = '', $conf = [])
2152 {
2153 return $this->filelist($conf['filelist']);
2154 }
2155
2156 /**
2157 * preUserFunc
2158 * Will execute a user public function before the content will be modified by any other stdWrap function
2159 *
2160 * @param string $content Input value undergoing processing in this function.
2161 * @param array $conf stdWrap properties for preUserFunc.
2162 * @return string The processed input value
2163 */
2164 public function stdWrap_preUserFunc($content = '', $conf = [])
2165 {
2166 return $this->callUserFunction($conf['preUserFunc'], $conf['preUserFunc.'], $content);
2167 }
2168
2169 /**
2170 * stdWrap override hook
2171 * can be used by extensions authors to modify the behaviour of stdWrap functions to their needs
2172 * this hook will execute functions on existing content but still before the content gets modified or replaced
2173 *
2174 * @param string $content Input value undergoing processing in these functions.
2175 * @param array $conf All stdWrap properties, not just the ones for a particular function.
2176 * @return string The processed input value
2177 */
2178 public function stdWrap_stdWrapOverride($content = '', $conf = [])
2179 {
2180 foreach ($this->stdWrapHookObjects as $hookObject) {
2181 /** @var ContentObjectStdWrapHookInterface $hookObject */
2182 $content = $hookObject->stdWrapOverride($content, $conf, $this);
2183 }
2184 return $content;
2185 }
2186
2187 /**
2188 * override
2189 * Will override the current value of content with its own value'
2190 *
2191 * @param string $content Input value undergoing processing in this function.
2192 * @param array $conf stdWrap properties for override.
2193 * @return string The processed input value
2194 */
2195 public function stdWrap_override($content = '', $conf = [])
2196 {
2197 if (trim($conf['override'])) {
2198 $content = $conf['override'];
2199 }
2200 return $content;
2201 }
2202
2203 /**
2204 * preIfEmptyListNum
2205 * Gets a value off a CSV list before the following ifEmpty check
2206 * 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
2207 *
2208 * @param string $content Input value undergoing processing in this function.
2209 * @param array $conf stdWrap properties for preIfEmptyListNum.
2210 * @return string The processed input value
2211 */
2212 public function stdWrap_preIfEmptyListNum($content = '', $conf = [])
2213 {
2214 return $this->listNum($content, $conf['preIfEmptyListNum'], $conf['preIfEmptyListNum.']['splitChar']);
2215 }
2216
2217 /**
2218 * ifNull
2219 * Will set content to a replacement value in case the value of content is NULL
2220 *
2221 * @param string|NULL $content Input value undergoing processing in this function.
2222 * @param array $conf stdWrap properties for ifNull.
2223 * @return string The processed input value
2224 */
2225 public function stdWrap_ifNull($content = '', $conf = [])
2226 {
2227 return $content !== null ? $content : $conf['ifNull'];
2228 }
2229
2230 /**
2231 * ifEmpty
2232 * Will set content to a replacement value in case the trimmed value of content returns FALSE
2233 * 0 (zero) will be replaced as well
2234 *
2235 * @param string $content Input value undergoing processing in this function.
2236 * @param array $conf stdWrap properties for ifEmpty.
2237 * @return string The processed input value
2238 */
2239 public function stdWrap_ifEmpty($content = '', $conf = [])
2240 {
2241 if (!trim($content)) {
2242 $content = $conf['ifEmpty'];
2243 }
2244 return $content;
2245 }
2246
2247 /**
2248 * ifBlank
2249 * Will set content to a replacement value in case the trimmed value of content has no length
2250 * 0 (zero) will not be replaced
2251 *
2252 * @param string $content Input value undergoing processing in this function.
2253 * @param array $conf stdWrap properties for ifBlank.
2254 * @return string The processed input value
2255 */
2256 public function stdWrap_ifBlank($content = '', $conf = [])
2257 {
2258 if (trim($content) === '') {
2259 $content = $conf['ifBlank'];
2260 }
2261 return $content;
2262 }
2263
2264 /**
2265 * listNum
2266 * Gets a value off a CSV list after ifEmpty check
2267 * Might return an empty value in case the CSV does not contain a value at the position given by listNum
2268 * Use preIfEmptyListNum to avoid that behaviour
2269 *
2270 * @param string $content Input value undergoing processing in this function.
2271 * @param array $conf stdWrap properties for listNum.
2272 * @return string The processed input value
2273 */
2274 public function stdWrap_listNum($content = '', $conf = [])
2275 {
2276 return $this->listNum($content, $conf['listNum'], $conf['listNum.']['splitChar']);
2277 }
2278
2279 /**
2280 * trim
2281 * Cuts off any whitespace at the beginning and the end of the content
2282 *
2283 * @param string $content Input value undergoing processing in this function.
2284 * @return string The processed input value
2285 */
2286 public function stdWrap_trim($content = '')
2287 {
2288 return trim($content);
2289 }
2290
2291 /**
2292 * strPad
2293 * Will return a string padded left/right/on both sides, based on configuration given as stdWrap properties
2294 *
2295 * @param string $content Input value undergoing processing in this function.
2296 * @param array $conf stdWrap properties for strPad.
2297 * @return string The processed input value
2298 */
2299 public function stdWrap_strPad($content = '', $conf = [])
2300 {
2301 // Must specify a length in conf for this to make sense
2302 $length = 0;
2303 // Padding with space is PHP-default
2304 $padWith = ' ';
2305 // Padding on the right side is PHP-default
2306 $padType = STR_PAD_RIGHT;
2307 if (!empty($conf['strPad.']['length'])) {
2308 $length = isset($conf['strPad.']['length.']) ? $this->stdWrap($conf['strPad.']['length'], $conf['strPad.']['length.']) : $conf['strPad.']['length'];
2309 $length = (int)$length;
2310 }
2311 if (isset($conf['strPad.']['padWith']) && (string)$conf['strPad.']['padWith'] !== '') {
2312 $padWith = isset($conf['strPad.']['padWith.']) ? $this->stdWrap($conf['strPad.']['padWith'], $conf['strPad.']['padWith.']) : $conf['strPad.']['padWith'];
2313 }
2314 if (!empty($conf['strPad.']['type'])) {
2315 $type = isset($conf['strPad.']['type.']) ? $this->stdWrap($conf['strPad.']['type'], $conf['strPad.']['type.']) : $conf['strPad.']['type'];
2316 if (strtolower($type) === 'left') {
2317 $padType = STR_PAD_LEFT;
2318 } elseif (strtolower($type) === 'both') {
2319 $padType = STR_PAD_BOTH;
2320 }
2321 }
2322 return str_pad($content, $length, $padWith, $padType);
2323 }
2324
2325 /**
2326 * stdWrap
2327 * A recursive call of the stdWrap function set
2328 * This enables the user to execute stdWrap functions in another than the predefined order
2329 * It modifies the content, not the property
2330 * while the new feature of chained stdWrap functions modifies the property and not the content
2331 *
2332 * @param string $content Input value undergoing processing in this function.
2333 * @param array $conf stdWrap properties for stdWrap.
2334 * @return string The processed input value
2335 */
2336 public function stdWrap_stdWrap($content = '', $conf = [])
2337 {
2338 return $this->stdWrap($content, $conf['stdWrap.']);
2339 }
2340
2341 /**
2342 * stdWrap process hook
2343 * can be used by extensions authors to modify the behaviour of stdWrap functions to their needs
2344 * this hook executes functions directly after the recursive stdWrap function call but still before the content gets modified
2345 *
2346 * @param string $content Input value undergoing processing in these functions.
2347 * @param array $conf All stdWrap properties, not just the ones for a particular function.
2348 * @return string The processed input value
2349 */
2350 public function stdWrap_stdWrapProcess($content = '', $conf = [])
2351 {
2352 foreach ($this->stdWrapHookObjects as $hookObject) {
2353 /** @var ContentObjectStdWrapHookInterface $hookObject */
2354 $content = $hookObject->stdWrapProcess($content, $conf, $this);
2355 }
2356 return $content;
2357 }
2358
2359 /**
2360 * required
2361 * Will immediately stop rendering and return an empty value
2362 * when there is no content at this point
2363 *
2364 * @param string $content Input value undergoing processing in this function.
2365 * @return string The processed input value
2366 */
2367 public function stdWrap_required($content = '')
2368 {
2369 if ((string)$content === '') {
2370 $content = '';
2371 $this->stopRendering[$this->stdWrapRecursionLevel] = true;
2372 }
2373 return $content;
2374 }
2375
2376 /**
2377 * if
2378 * Will immediately stop rendering and return an empty value
2379 * when the result of the checks returns FALSE
2380 *
2381 * @param string $content Input value undergoing processing in this function.
2382 * @param array $conf stdWrap properties for if.
2383 * @return string The processed input value
2384 */
2385 public function stdWrap_if($content = '', $conf = [])
2386 {
2387 if (empty($conf['if.']) || $this->checkIf($conf['if.'])) {
2388 return $content;
2389 }
2390 $this->stopRendering[$this->stdWrapRecursionLevel] = true;
2391 return '';
2392 }
2393
2394 /**
2395 * fieldRequired
2396 * Will immediately stop rendering and return an empty value
2397 * when there is no content in the field given by fieldRequired
2398 *
2399 * @param string $content Input value undergoing processing in this function.
2400 * @param array $conf stdWrap properties for fieldRequired.
2401 * @return string The processed input value
2402 */
2403 public function stdWrap_fieldRequired($content = '', $conf = [])
2404 {
2405 if (!trim($this->data[$conf['fieldRequired']])) {
2406 $content = '';
2407 $this->stopRendering[$this->stdWrapRecursionLevel] = true;
2408 }
2409 return $content;
2410 }
2411
2412 /**
2413 * stdWrap csConv: Converts the input to UTF-8
2414 *
2415 * The character set of the input must be specified. Returns the input if
2416 * matters go wrong, for example if an invalid character set is given.
2417 *
2418 * @param string $content The string to convert.
2419 * @param array $conf stdWrap properties for csConv.
2420 * @return string The processed input.
2421 */
2422 public function stdWrap_csConv($content = '', $conf = [])
2423 {
2424 if (!empty($conf['csConv'])) {
2425 $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
2426 $output = $charsetConverter->conv($content, $charsetConverter->parse_charset($conf['csConv']), 'utf-8');
2427 return $output !== false && $output !== '' ? $output : $content;
2428 } else {
2429 return $content;
2430 }
2431 }
2432
2433 /**
2434 * parseFunc
2435 * Will parse the content based on functions given as stdWrap properties
2436 * Heavily used together with RTE based content
2437 *
2438 * @param string $content Input value undergoing processing in this function.
2439 * @param array $conf stdWrap properties for parseFunc.
2440 * @return string The processed input value
2441 */
2442 public function stdWrap_parseFunc($content = '', $conf = [])
2443 {
2444 return $this->parseFunc($content, $conf['parseFunc.'], $conf['parseFunc']);
2445 }
2446
2447 /**
2448 * HTMLparser
2449 * Will parse HTML content based on functions given as stdWrap properties
2450 * Heavily used together with RTE based content
2451 *
2452 * @param string $content Input value undergoing processing in this function.
2453 * @param array $conf stdWrap properties for HTMLparser.
2454 * @return string The processed input value
2455 */
2456 public function stdWrap_HTMLparser($content = '', $conf = [])
2457 {
2458 if (is_array($conf['HTMLparser.'])) {
2459 $content = $this->HTMLparser_TSbridge($content, $conf['HTMLparser.']);
2460 }
2461 return $content;
2462 }
2463
2464 /**
2465 * split
2466 * Will split the content by a given token and treat the results separately
2467 * Automatically fills 'current' with a single result
2468 *
2469 * @param string $content Input value undergoing processing in this function.
2470 * @param array $conf stdWrap properties for split.
2471 * @return string The processed input value
2472 */
2473 public function stdWrap_split($content = '', $conf = [])
2474 {
2475 return $this->splitObj($content, $conf['split.']);
2476 }
2477
2478 /**
2479 * replacement
2480 * Will execute replacements on the content (optionally with preg-regex)
2481 *
2482 * @param string $content Input value undergoing processing in this function.
2483 * @param array $conf stdWrap properties for replacement.
2484 * @return string The processed input value
2485 */
2486 public function stdWrap_replacement($content = '', $conf = [])
2487 {
2488 return $this->replacement($content, $conf['replacement.']);
2489 }
2490
2491 /**
2492 * prioriCalc
2493 * Will use the content as a mathematical term and calculate the result
2494 * Can be set to 1 to just get a calculated value or 'intval' to get the integer of the result
2495 *
2496 * @param string $content Input value undergoing processing in this function.
2497 * @param array $conf stdWrap properties for prioriCalc.
2498 * @return string The processed input value
2499 */
2500 public function stdWrap_prioriCalc($content = '', $conf = [])
2501 {
2502 $content = MathUtility::calculateWithParentheses($content);
2503 if ($conf['prioriCalc'] === 'intval') {
2504 $content = (int)$content;
2505 }
2506 return $content;
2507 }
2508
2509 /**
2510 * char
2511 * Returns a one-character string containing the character specified by ascii code.
2512 *
2513 * Reliable results only for character codes in the integer range 0 - 127.
2514 *
2515 * @see http://php.net/manual/en/function.chr.php
2516 * @param string $content Input value undergoing processing in this function.
2517 * @param array $conf stdWrap properties for char.
2518 * @return string The processed input value
2519 */
2520 public function stdWrap_char($content = '', $conf = [])
2521 {
2522 return chr((int)$conf['char']);
2523 }
2524
2525 /**
2526 * intval
2527 * Will return an integer value of the current content
2528 *
2529 * @param string $content Input value undergoing processing in this function.
2530 * @return string The processed input value
2531 */
2532 public function stdWrap_intval($content = '')
2533 {
2534 return (int)$content;
2535 }
2536
2537 /**
2538 * Will return a hashed value of the current content
2539 *
2540 * @param string $content Input value undergoing processing in this function.
2541 * @param array $conf stdWrap properties for hash.
2542 * @return string The processed input value
2543 * @link http://php.net/manual/de/function.hash-algos.php for a list of supported hash algorithms
2544 */
2545 public function stdWrap_hash($content = '', array $conf = [])
2546 {
2547 $algorithm = isset($conf['hash.']) ? $this->stdWrap($conf['hash'], $conf['hash.']) : $conf['hash'];
2548 if (function_exists('hash') && in_array($algorithm, hash_algos())) {
2549 return hash($algorithm, $content);
2550 }
2551 // Non-existing hashing algorithm
2552 return '';
2553 }
2554
2555 /**
2556 * stdWrap_round will return a rounded number with ceil(), floor() or round(), defaults to round()
2557 * Only the english number format is supported . (dot) as decimal point
2558 *
2559 * @param string $content Input value undergoing processing in this function.
2560 * @param array $conf stdWrap properties for round.
2561 * @return string The processed input value
2562 */
2563 public function stdWrap_round($content = '', $conf = [])
2564 {
2565 return $this->round($content, $conf['round.']);
2566 }
2567
2568 /**
2569 * numberFormat
2570 * Will return a formatted number based on configuration given as stdWrap properties
2571 *
2572 * @param string $content Input value undergoing processing in this function.
2573 * @param array $conf stdWrap properties for numberFormat.
2574 * @return string The processed input value
2575 */
2576 public function stdWrap_numberFormat($content = '', $conf = [])
2577 {
2578 return $this->numberFormat($content, $conf['numberFormat.']);
2579 }
2580
2581 /**
2582 * expandList
2583 * Will return a formatted number based on configuration given as stdWrap properties
2584 *
2585 * @param string $content Input value undergoing processing in this function.
2586 * @return string The processed input value
2587 */
2588 public function stdWrap_expandList($content = '')
2589 {
2590 return GeneralUtility::expandList($content);
2591 }
2592
2593 /**
2594 * date
2595 * Will return a formatted date based on configuration given according to PHP date/gmdate properties
2596 * Will return gmdate when the property GMT returns TRUE
2597 *
2598 * @param string $content Input value undergoing processing in this function.
2599 * @param array $conf stdWrap properties for date.
2600 * @return string The processed input value
2601 */
2602 public function stdWrap_date($content = '', $conf = [])
2603 {
2604 // Check for zero length string to mimic default case of date/gmdate.
2605 $content = (string)$content === '' ? $GLOBALS['EXEC_TIME'] : (int)$content;
2606 $content = $conf['date.']['GMT'] ? gmdate($conf['date'], $content) : date($conf['date'], $content);
2607 return $content;
2608 }
2609
2610 /**
2611 * strftime
2612 * Will return a formatted date based on configuration given according to PHP strftime/gmstrftime properties
2613 * Will return gmstrftime when the property GMT returns TRUE
2614 *
2615 * @param string $content Input value undergoing processing in this function.
2616 * @param array $conf stdWrap properties for strftime.
2617 * @return string The processed input value
2618 */
2619 public function stdWrap_strftime($content = '', $conf = [])
2620 {
2621 // Check for zero length string to mimic default case of strtime/gmstrftime
2622 $content = (string)$content === '' ? $GLOBALS['EXEC_TIME'] : (int)$content;
2623 $content = $conf['strftime.']['GMT'] ? gmstrftime($conf['strftime'], $content) : strftime($conf['strftime'], $content);
2624 if (!empty($conf['strftime.']['charset'])) {
2625 /** @var CharsetConverter $charsetConverter */
2626 $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
2627 $output = $charsetConverter->conv($content, $charsetConverter->parse_charset($conf['strftime.']['charset']), 'utf-8');
2628 return $output ?: $content;
2629 }
2630 return $content;
2631 }
2632
2633 /**
2634 * strtotime
2635 * Will return a timestamp based on configuration given according to PHP strtotime
2636 *
2637 * @param string $content Input value undergoing processing in this function.
2638 * @param array $conf stdWrap properties for strtotime.
2639 * @return string The processed input value
2640 */
2641 public function stdWrap_strtotime($content = '', $conf = [])
2642 {
2643 if ($conf['strtotime'] !== '1') {
2644 $content .= ' ' . $conf['strtotime'];
2645 }
2646 return strtotime($content, $GLOBALS['EXEC_TIME']);
2647 }
2648
2649 /**
2650 * age
2651 * Will return the age of a given timestamp based on configuration given by stdWrap properties
2652 *
2653 * @param string $content Input value undergoing processing in this function.
2654 * @param array $conf stdWrap properties for age.
2655 * @return string The processed input value
2656 */
2657 public function stdWrap_age($content = '', $conf = [])
2658 {
2659 return $this->calcAge((int)$GLOBALS['EXEC_TIME'] - (int)$content, $conf['age']);
2660 }
2661
2662 /**
2663 * case
2664 * Will transform the content to be upper or lower case only
2665 * Leaves HTML tags untouched
2666 *
2667 * @param string $content Input value undergoing processing in this function.
2668 * @param array $conf stdWrap properties for case.
2669 * @return string The processed input value
2670 */
2671 public function stdWrap_case($content = '', $conf = [])
2672 {
2673 return $this->HTMLcaseshift($content, $conf['case']);
2674 }
2675
2676 /**
2677 * bytes
2678 * Will return the size of a given number in Bytes *
2679 *
2680 * @param string $content Input value undergoing processing in this function.
2681 * @param array $conf stdWrap properties for bytes.
2682 * @return string The processed input value
2683 */
2684 public function stdWrap_bytes($content = '', $conf = [])
2685 {
2686 return GeneralUtility::formatSize($content, $conf['bytes.']['labels'], $conf['bytes.']['base']);
2687 }
2688
2689 /**
2690 * substring
2691 * Will return a substring based on position information given by stdWrap properties
2692 *
2693 * @param string $content Input value undergoing processing in this function.
2694 * @param array $conf stdWrap properties for substring.
2695 * @return string The processed input value
2696 */
2697 public function stdWrap_substring($content = '', $conf = [])
2698 {
2699 return $this->substring($content, $conf['substring']);
2700 }
2701
2702 /**
2703 * removeBadHTML
2704 * Removes HTML tags based on stdWrap properties
2705 *
2706 * @param string $content Input value undergoing processing in this function.
2707 * @return string The processed input value
2708 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
2709 */
2710 public function stdWrap_removeBadHTML($content = '')
2711 {
2712 return $this->removeBadHTML($content);
2713 }
2714
2715 /**
2716 * cropHTML
2717 * Crops content to a given size while leaving HTML tags untouched
2718 *
2719 * @param string $content Input value undergoing processing in this function.
2720 * @param array $conf stdWrap properties for cropHTML.
2721 * @return string The processed input value
2722 */
2723 public function stdWrap_cropHTML($content = '', $conf = [])
2724 {
2725 return $this->cropHTML($content, $conf['cropHTML']);
2726 }
2727
2728 /**
2729 * stripHtml
2730 * Copmletely removes HTML tags from content
2731 *
2732 * @param string $content Input value undergoing processing in this function.
2733 * @return string The processed input value
2734 */
2735 public function stdWrap_stripHtml($content = '')
2736 {
2737 return strip_tags($content);
2738 }
2739
2740 /**
2741 * crop
2742 * Crops content to a given size without caring about HTML tags
2743 *
2744 * @param string $content Input value undergoing processing in this function.
2745 * @param array $conf stdWrap properties for crop.
2746 * @return string The processed input value
2747 */
2748 public function stdWrap_crop($content = '', $conf = [])
2749 {
2750 return $this->crop($content, $conf['crop']);
2751 }
2752
2753 /**
2754 * rawUrlEncode
2755 * Encodes content to be used within URLs
2756 *
2757 * @param string $content Input value undergoing processing in this function.
2758 * @return string The processed input value
2759 */
2760 public function stdWrap_rawUrlEncode($content = '')
2761 {
2762 return rawurlencode($content);
2763 }
2764
2765 /**
2766 * htmlSpecialChars
2767 * Transforms HTML tags to readable text by replacing special characters with their HTML entity
2768 * When preserveEntities returns TRUE, existing entities will be left untouched
2769 *
2770 * @param string $content Input value undergoing processing in this function.
2771 * @param array $conf stdWrap properties for htmlSpecalChars.
2772 * @return string The processed input value
2773 */
2774 public function stdWrap_htmlSpecialChars($content = '', $conf = [])
2775 {
2776 if (!empty($conf['htmlSpecialChars.']['preserveEntities'])) {
2777 $content = htmlspecialchars($content, ENT_COMPAT, 'UTF-8', false);
2778 } else {
2779 $content = htmlspecialchars($content);
2780 }
2781 return $content;
2782 }
2783
2784 /**
2785 * encodeForJavaScriptValue
2786 * Escapes content to be used inside JavaScript strings. No quotes are added around the value
2787 * as this can easily be done in TypoScript
2788 *
2789 * @param string $content Input value undergoing processing in this function
2790 * @return string The processed input value
2791 */
2792 public function stdWrap_encodeForJavaScriptValue($content = '')
2793 {
2794 return GeneralUtility::quoteJSvalue($content);
2795 }
2796
2797 /**
2798 * doubleBrTag
2799 * Searches for double line breaks and replaces them with the given value
2800 *
2801 * @param string $content Input value undergoing processing in this function.
2802 * @param array $conf stdWrap properties for doubleBrTag.
2803 * @return string The processed input value
2804 */
2805 public function stdWrap_doubleBrTag($content = '', $conf = [])
2806 {
2807 return preg_replace('/\R{1,2}[\t\x20]*\R{1,2}/', $conf['doubleBrTag'], $content);
2808 }
2809
2810 /**
2811 * br
2812 * Searches for single line breaks and replaces them with a <br />/<br> tag
2813 * according to the doctype
2814 *
2815 * @param string $content Input value undergoing processing in this function.
2816 * @return string The processed input value
2817 */
2818 public function stdWrap_br($content = '')
2819 {
2820 return nl2br($content, !empty($this->getTypoScriptFrontendController()->xhtmlDoctype));
2821 }
2822
2823 /**
2824 * brTag
2825 * Searches for single line feeds and replaces them with the given value
2826 *
2827 * @param string $content Input value undergoing processing in this function.
2828 * @param array $conf stdWrap properties for brTag.
2829 * @return string The processed input value
2830 */
2831 public function stdWrap_brTag($content = '', $conf = [])
2832 {
2833 return str_replace(LF, $conf['brTag'], $content);
2834 }
2835
2836 /**
2837 * encapsLines
2838 * Modifies text blocks by searching for lines which are not surrounded by HTML tags yet
2839 * and wrapping them with values given by stdWrap properties
2840 *
2841 * @param string $content Input value undergoing processing in this function.
2842 * @param array $conf stdWrap properties for erncapsLines.
2843 * @return string The processed input value
2844 */
2845 public function stdWrap_encapsLines($content = '', $conf = [])
2846 {
2847 return $this->encaps_lineSplit($content, $conf['encapsLines.']);
2848 }
2849
2850 /**
2851 * keywords
2852 * Transforms content into a CSV list to be used i.e. as keywords within a meta tag
2853 *
2854 * @param string $content Input value undergoing processing in this function.
2855 * @return string The processed input value
2856 */
2857 public function stdWrap_keywords($content = '')
2858 {
2859 return $this->keywords($content);
2860 }
2861
2862 /**
2863 * innerWrap
2864 * First of a set of different wraps which will be applied in a certain order before or after other functions that modify the content
2865 * See wrap
2866 *
2867 * @param string $content Input value undergoing processing in this function.
2868 * @param array $conf stdWrap properties for innerWrap.
2869 * @return string The processed input value
2870 */
2871 public function stdWrap_innerWrap($content = '', $conf = [])
2872 {
2873 return $this->wrap($content, $conf['innerWrap']);
2874 }
2875
2876 /**
2877 * innerWrap2
2878 * Second of a set of different wraps which will be applied in a certain order before or after other functions that modify the content
2879 * See wrap
2880 *
2881 * @param string $content Input value undergoing processing in this function.
2882 * @param array $conf stdWrap properties for innerWrap2.
2883 * @return string The processed input value
2884 */
2885 public function stdWrap_innerWrap2($content = '', $conf = [])
2886 {
2887 return $this->wrap($content, $conf['innerWrap2']);
2888 }
2889
2890 /**
2891 * fontTag
2892 * A wrap formerly used to apply font tags to format the content
2893 * See wrap
2894 *
2895 * @param string $content Input value undergoing processing in this function.
2896 * @param array $conf stdWrap properties for fontTag.
2897 * @return string The processed input value
2898 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
2899 */
2900 public function stdWrap_fontTag($content = '', $conf = [])
2901 {
2902 GeneralUtility::logDeprecatedFunction();
2903 return $this->wrap($content, $conf['fontTag']);
2904 }
2905
2906 /**
2907 * addParams
2908 * Adds tag attributes to any content that is a tag
2909 *
2910 * @param string $content Input value undergoing processing in this function.
2911 * @param array $conf stdWrap properties for addParams.
2912 * @return string The processed input value
2913 */
2914 public function stdWrap_addParams($content = '', $conf = [])
2915 {
2916 return $this->addParams($content, $conf['addParams.']);
2917 }
2918
2919 /**
2920 * filelink
2921 * Used to make lists of links to files
2922 * See wrap
2923 *
2924 * @param string $content Input value undergoing processing in this function.
2925 * @param array $conf stdWrap properties for filelink.
2926 * @return string The processed input value
2927 */
2928 public function stdWrap_filelink($content = '', $conf = [])
2929 {
2930 return $this->filelink($content, $conf['filelink.']);
2931 }
2932
2933 /**
2934 * preCObject
2935 * A content object that is prepended to the current content but between the innerWraps and the rest of the wraps
2936 *
2937 * @param string $content Input value undergoing processing in this function.
2938 * @param array $conf stdWrap properties for preCObject.
2939 * @return string The processed input value
2940 */
2941 public function stdWrap_preCObject($content = '', $conf = [])
2942 {
2943 return $this->cObjGetSingle($conf['preCObject'], $conf['preCObject.'], '/stdWrap/.preCObject') . $content;
2944 }
2945
2946 /**
2947 * postCObject
2948 * A content object that is appended to the current content but between the innerWraps and the rest of the wraps
2949 *
2950 * @param string $content Input value undergoing processing in this function.
2951 * @param array $conf stdWrap properties for postCObject.
2952 * @return string The processed input value
2953 */
2954 public function stdWrap_postCObject($content = '', $conf = [])
2955 {
2956 return $content . $this->cObjGetSingle($conf['postCObject'], $conf['postCObject.'], '/stdWrap/.postCObject');
2957 }
2958
2959 /**
2960 * wrapAlign
2961 * Wraps content with a div container having the style attribute text-align set to the given value
2962 * See wrap
2963 *
2964 * @param string $content Input value undergoing processing in this function.
2965 * @param array $conf stdWrap properties for wrapAlign.
2966 * @return string The processed input value
2967 */
2968 public function stdWrap_wrapAlign($content = '', $conf = [])
2969 {
2970 $wrapAlign =