[TASK] Remove leftover unused code in various PHP classes
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Page / PageRenderer.php
1 <?php
2 namespace TYPO3\CMS\Core\Page;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Routing\Router;
18 use TYPO3\CMS\Backend\Routing\UriBuilder;
19 use TYPO3\CMS\Backend\Template\DocumentTemplate;
20 use TYPO3\CMS\Core\Cache\CacheManager;
21 use TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException;
22 use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
23 use TYPO3\CMS\Core\Core\Environment;
24 use TYPO3\CMS\Core\Localization\LocalizationFactory;
25 use TYPO3\CMS\Core\MetaTag\MetaTagManagerRegistry;
26 use TYPO3\CMS\Core\Service\MarkerBasedTemplateService;
27 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
28 use TYPO3\CMS\Core\Utility\GeneralUtility;
29 use TYPO3\CMS\Core\Utility\PathUtility;
30 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
31
32 /**
33 * TYPO3 pageRender class
34 * This class render the HTML of a webpage, usable for BE and FE
35 */
36 class PageRenderer implements \TYPO3\CMS\Core\SingletonInterface
37 {
38 // Constants for the part to be rendered
39 const PART_COMPLETE = 0;
40 const PART_HEADER = 1;
41 const PART_FOOTER = 2;
42
43 const REQUIREJS_SCOPE_CONFIG = 'config';
44 const REQUIREJS_SCOPE_RESOLVE = 'resolve';
45
46 /**
47 * @var bool
48 */
49 protected $compressJavascript = false;
50
51 /**
52 * @var bool
53 */
54 protected $compressCss = false;
55
56 /**
57 * @var bool
58 */
59 protected $removeLineBreaksFromTemplate = false;
60
61 /**
62 * @var bool
63 */
64 protected $concatenateJavascript = false;
65
66 /**
67 * @var bool
68 */
69 protected $concatenateCss = false;
70
71 /**
72 * @var bool
73 */
74 protected $moveJsFromHeaderToFooter = false;
75
76 /**
77 * @var \TYPO3\CMS\Core\Localization\Locales
78 */
79 protected $locales;
80
81 /**
82 * The language key
83 * Two character string or 'default'
84 *
85 * @var string
86 */
87 protected $lang;
88
89 /**
90 * List of language dependencies for actual language. This is used for local variants of a language
91 * that depend on their "main" language, like Brazilian Portuguese or Canadian French.
92 *
93 * @var array
94 */
95 protected $languageDependencies = [];
96
97 /**
98 * @var \TYPO3\CMS\Core\Resource\ResourceCompressor
99 */
100 protected $compressor;
101
102 // Arrays containing associative array for the included files
103 /**
104 * @var array
105 */
106 protected $jsFiles = [];
107
108 /**
109 * @var array
110 */
111 protected $jsFooterFiles = [];
112
113 /**
114 * @var array
115 */
116 protected $jsLibs = [];
117
118 /**
119 * @var array
120 */
121 protected $jsFooterLibs = [];
122
123 /**
124 * @var array
125 */
126 protected $cssFiles = [];
127
128 /**
129 * @var array
130 */
131 protected $cssLibs = [];
132
133 /**
134 * The title of the page
135 *
136 * @var string
137 */
138 protected $title;
139
140 /**
141 * Charset for the rendering
142 *
143 * @var string
144 */
145 protected $charSet;
146
147 /**
148 * @var string
149 */
150 protected $favIcon;
151
152 /**
153 * @var string
154 */
155 protected $baseUrl;
156
157 /**
158 * @var bool
159 */
160 protected $renderXhtml = true;
161
162 // Static header blocks
163 /**
164 * @var string
165 */
166 protected $xmlPrologAndDocType = '';
167
168 /**
169 * @var array
170 */
171 protected $metaTags = [];
172
173 /**
174 * META Tags added via the API
175 *
176 * @var array
177 */
178 protected $metaTagsByAPI = [];
179
180 /**
181 * @var array
182 */
183 protected $inlineComments = [];
184
185 /**
186 * @var array
187 */
188 protected $headerData = [];
189
190 /**
191 * @var array
192 */
193 protected $footerData = [];
194
195 /**
196 * @var string
197 */
198 protected $titleTag = '<title>|</title>';
199
200 /**
201 * @var string
202 */
203 protected $metaCharsetTag = '<meta http-equiv="Content-Type" content="text/html; charset=|" />';
204
205 /**
206 * @var string
207 */
208 protected $htmlTag = '<html>';
209
210 /**
211 * @var string
212 */
213 protected $headTag = '<head>';
214
215 /**
216 * @var string
217 */
218 protected $baseUrlTag = '<base href="|" />';
219
220 /**
221 * @var string
222 */
223 protected $iconMimeType = '';
224
225 /**
226 * @var string
227 */
228 protected $shortcutTag = '<link rel="shortcut icon" href="%1$s"%2$s />';
229
230 // Static inline code blocks
231 /**
232 * @var array
233 */
234 protected $jsInline = [];
235
236 /**
237 * @var array
238 */
239 protected $jsFooterInline = [];
240
241 /**
242 * @var array
243 */
244 protected $cssInline = [];
245
246 /**
247 * @var string
248 */
249 protected $bodyContent;
250
251 /**
252 * @var string
253 */
254 protected $templateFile;
255
256 // Paths to contributed libraries
257
258 /**
259 * default path to the requireJS library, relative to the typo3/ directory
260 * @var string
261 */
262 protected $requireJsPath = 'EXT:core/Resources/Public/JavaScript/Contrib/';
263
264 // Internal flags for JS-libraries
265 /**
266 * if set, the requireJS library is included
267 * @var bool
268 */
269 protected $addRequireJs = false;
270
271 /**
272 * Inline configuration for requireJS (internal)
273 * @var array
274 */
275 protected $requireJsConfig = [];
276
277 /**
278 * Module names of internal requireJS 'paths'
279 * @var array
280 */
281 protected $internalRequireJsPathModuleNames = [];
282
283 /**
284 * Inline configuration for requireJS (public)
285 * @var array
286 */
287 protected $publicRequireJsConfig = [];
288
289 /**
290 * @var array
291 */
292 protected $inlineLanguageLabels = [];
293
294 /**
295 * @var array
296 */
297 protected $inlineLanguageLabelFiles = [];
298
299 /**
300 * @var array
301 */
302 protected $inlineSettings = [];
303
304 /**
305 * @var array
306 */
307 protected $inlineJavascriptWrap = [];
308
309 /**
310 * @var array
311 */
312 protected $inlineCssWrap = [];
313
314 /**
315 * Saves error messages generated during compression
316 *
317 * @var string
318 */
319 protected $compressError = '';
320
321 /**
322 * Is empty string for HTML and ' /' for XHTML rendering
323 *
324 * @var string
325 */
326 protected $endingSlash = '';
327
328 /**
329 * @var MetaTagManagerRegistry
330 */
331 protected $metaTagRegistry;
332
333 /**
334 * @var FrontendInterface
335 */
336 protected static $cache = null;
337
338 /**
339 * @param string $templateFile Declare the used template file. Omit this parameter will use default template
340 */
341 public function __construct($templateFile = '')
342 {
343 $this->reset();
344 $this->locales = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Localization\Locales::class);
345 if ($templateFile !== '') {
346 $this->templateFile = $templateFile;
347 }
348 $this->inlineJavascriptWrap = [
349 '<script type="text/javascript">' . LF . '/*<![CDATA[*/' . LF,
350 '/*]]>*/' . LF . '</script>' . LF
351 ];
352 $this->inlineCssWrap = [
353 '<style type="text/css">' . LF . '/*<![CDATA[*/' . LF . '<!-- ' . LF,
354 '-->' . LF . '/*]]>*/' . LF . '</style>' . LF
355 ];
356
357 $this->metaTagRegistry = GeneralUtility::makeInstance(MetaTagManagerRegistry::class);
358 $this->setMetaTag('name', 'generator', 'TYPO3 CMS');
359 }
360
361 /**
362 * @param FrontendInterface $cache
363 */
364 public static function setCache(FrontendInterface $cache)
365 {
366 static::$cache = $cache;
367 }
368
369 /**
370 * Reset all vars to initial values
371 */
372 protected function reset()
373 {
374 $this->templateFile = 'EXT:core/Resources/Private/Templates/PageRenderer.html';
375 $this->jsFiles = [];
376 $this->jsFooterFiles = [];
377 $this->jsInline = [];
378 $this->jsFooterInline = [];
379 $this->jsLibs = [];
380 $this->cssFiles = [];
381 $this->cssInline = [];
382 $this->metaTags = [];
383 $this->metaTagsByAPI = [];
384 $this->inlineComments = [];
385 $this->headerData = [];
386 $this->footerData = [];
387 }
388
389 /*****************************************************/
390 /* */
391 /* Public Setters */
392 /* */
393 /* */
394 /*****************************************************/
395 /**
396 * Sets the title
397 *
398 * @param string $title title of webpage
399 */
400 public function setTitle($title)
401 {
402 $this->title = $title;
403 }
404
405 /**
406 * Enables/disables rendering of XHTML code
407 *
408 * @param bool $enable Enable XHTML
409 */
410 public function setRenderXhtml($enable)
411 {
412 $this->renderXhtml = $enable;
413 }
414
415 /**
416 * Sets xml prolog and docType
417 *
418 * @param string $xmlPrologAndDocType Complete tags for xml prolog and docType
419 */
420 public function setXmlPrologAndDocType($xmlPrologAndDocType)
421 {
422 $this->xmlPrologAndDocType = $xmlPrologAndDocType;
423 }
424
425 /**
426 * Sets meta charset
427 *
428 * @param string $charSet Used charset
429 */
430 public function setCharSet($charSet)
431 {
432 $this->charSet = $charSet;
433 }
434
435 /**
436 * Sets language
437 *
438 * @param string $lang Used language
439 */
440 public function setLanguage($lang)
441 {
442 $this->lang = $lang;
443 $this->languageDependencies = [];
444
445 // Language is found. Configure it:
446 if (in_array($this->lang, $this->locales->getLocales())) {
447 $this->languageDependencies[] = $this->lang;
448 foreach ($this->locales->getLocaleDependencies($this->lang) as $language) {
449 $this->languageDependencies[] = $language;
450 }
451 }
452 }
453
454 /**
455 * Set the meta charset tag
456 *
457 * @param string $metaCharsetTag
458 */
459 public function setMetaCharsetTag($metaCharsetTag)
460 {
461 $this->metaCharsetTag = $metaCharsetTag;
462 }
463
464 /**
465 * Sets html tag
466 *
467 * @param string $htmlTag Html tag
468 */
469 public function setHtmlTag($htmlTag)
470 {
471 $this->htmlTag = $htmlTag;
472 }
473
474 /**
475 * Sets HTML head tag
476 *
477 * @param string $headTag HTML head tag
478 */
479 public function setHeadTag($headTag)
480 {
481 $this->headTag = $headTag;
482 }
483
484 /**
485 * Sets favicon
486 *
487 * @param string $favIcon
488 */
489 public function setFavIcon($favIcon)
490 {
491 $this->favIcon = $favIcon;
492 }
493
494 /**
495 * Sets icon mime type
496 *
497 * @param string $iconMimeType
498 */
499 public function setIconMimeType($iconMimeType)
500 {
501 $this->iconMimeType = $iconMimeType;
502 }
503
504 /**
505 * Sets HTML base URL
506 *
507 * @param string $baseUrl HTML base URL
508 */
509 public function setBaseUrl($baseUrl)
510 {
511 $this->baseUrl = $baseUrl;
512 }
513
514 /**
515 * Sets template file
516 *
517 * @param string $file
518 */
519 public function setTemplateFile($file)
520 {
521 $this->templateFile = $file;
522 }
523
524 /**
525 * Sets Content for Body
526 *
527 * @param string $content
528 */
529 public function setBodyContent($content)
530 {
531 $this->bodyContent = $content;
532 }
533
534 /**
535 * Sets path to requireJS library (relative to typo3 directory)
536 *
537 * @param string $path Path to requireJS library
538 */
539 public function setRequireJsPath($path)
540 {
541 $this->requireJsPath = $path;
542 }
543
544 /**
545 * @param string $scope
546 * @return array
547 */
548 public function getRequireJsConfig(string $scope = null): array
549 {
550 // return basic RequireJS configuration without shim, paths and packages
551 if ($scope === static::REQUIREJS_SCOPE_CONFIG) {
552 return array_replace_recursive(
553 $this->publicRequireJsConfig,
554 $this->filterArrayKeys(
555 $this->requireJsConfig,
556 ['shim', 'paths', 'packages'],
557 false
558 )
559 );
560 }
561 // return RequireJS configuration for resolving only shim, paths and packages
562 if ($scope === static::REQUIREJS_SCOPE_RESOLVE) {
563 return $this->filterArrayKeys(
564 $this->requireJsConfig,
565 ['shim', 'paths', 'packages'],
566 true
567 );
568 }
569 return [];
570 }
571
572 /*****************************************************/
573 /* */
574 /* Public Enablers / Disablers */
575 /* */
576 /* */
577 /*****************************************************/
578 /**
579 * Enables MoveJsFromHeaderToFooter
580 */
581 public function enableMoveJsFromHeaderToFooter()
582 {
583 $this->moveJsFromHeaderToFooter = true;
584 }
585
586 /**
587 * Disables MoveJsFromHeaderToFooter
588 */
589 public function disableMoveJsFromHeaderToFooter()
590 {
591 $this->moveJsFromHeaderToFooter = false;
592 }
593
594 /**
595 * Enables compression of javascript
596 */
597 public function enableCompressJavascript()
598 {
599 $this->compressJavascript = true;
600 }
601
602 /**
603 * Disables compression of javascript
604 */
605 public function disableCompressJavascript()
606 {
607 $this->compressJavascript = false;
608 }
609
610 /**
611 * Enables compression of css
612 */
613 public function enableCompressCss()
614 {
615 $this->compressCss = true;
616 }
617
618 /**
619 * Disables compression of css
620 */
621 public function disableCompressCss()
622 {
623 $this->compressCss = false;
624 }
625
626 /**
627 * Enables concatenation of js files
628 */
629 public function enableConcatenateJavascript()
630 {
631 $this->concatenateJavascript = true;
632 }
633
634 /**
635 * Disables concatenation of js files
636 */
637 public function disableConcatenateJavascript()
638 {
639 $this->concatenateJavascript = false;
640 }
641
642 /**
643 * Enables concatenation of css files
644 */
645 public function enableConcatenateCss()
646 {
647 $this->concatenateCss = true;
648 }
649
650 /**
651 * Disables concatenation of css files
652 */
653 public function disableConcatenateCss()
654 {
655 $this->concatenateCss = false;
656 }
657
658 /**
659 * Sets removal of all line breaks in template
660 */
661 public function enableRemoveLineBreaksFromTemplate()
662 {
663 $this->removeLineBreaksFromTemplate = true;
664 }
665
666 /**
667 * Unsets removal of all line breaks in template
668 */
669 public function disableRemoveLineBreaksFromTemplate()
670 {
671 $this->removeLineBreaksFromTemplate = false;
672 }
673
674 /**
675 * Enables Debug Mode
676 * This is a shortcut to switch off all compress/concatenate features to enable easier debug
677 */
678 public function enableDebugMode()
679 {
680 $this->compressJavascript = false;
681 $this->compressCss = false;
682 $this->concatenateCss = false;
683 $this->concatenateJavascript = false;
684 $this->removeLineBreaksFromTemplate = false;
685 }
686
687 /*****************************************************/
688 /* */
689 /* Public Getters */
690 /* */
691 /* */
692 /*****************************************************/
693 /**
694 * Gets the title
695 *
696 * @return string $title Title of webpage
697 */
698 public function getTitle()
699 {
700 return $this->title;
701 }
702
703 /**
704 * Gets the charSet
705 *
706 * @return string $charSet
707 */
708 public function getCharSet()
709 {
710 return $this->charSet;
711 }
712
713 /**
714 * Gets the language
715 *
716 * @return string $lang
717 */
718 public function getLanguage()
719 {
720 return $this->lang;
721 }
722
723 /**
724 * Returns rendering mode XHTML or HTML
725 *
726 * @return bool TRUE if XHTML, FALSE if HTML
727 */
728 public function getRenderXhtml()
729 {
730 return $this->renderXhtml;
731 }
732
733 /**
734 * Gets html tag
735 *
736 * @return string $htmlTag Html tag
737 */
738 public function getHtmlTag()
739 {
740 return $this->htmlTag;
741 }
742
743 /**
744 * Get meta charset
745 *
746 * @return string
747 */
748 public function getMetaCharsetTag()
749 {
750 return $this->metaCharsetTag;
751 }
752
753 /**
754 * Gets head tag
755 *
756 * @return string $tag Head tag
757 */
758 public function getHeadTag()
759 {
760 return $this->headTag;
761 }
762
763 /**
764 * Gets favicon
765 *
766 * @return string $favIcon
767 */
768 public function getFavIcon()
769 {
770 return $this->favIcon;
771 }
772
773 /**
774 * Gets icon mime type
775 *
776 * @return string $iconMimeType
777 */
778 public function getIconMimeType()
779 {
780 return $this->iconMimeType;
781 }
782
783 /**
784 * Gets HTML base URL
785 *
786 * @return string $url
787 */
788 public function getBaseUrl()
789 {
790 return $this->baseUrl;
791 }
792
793 /**
794 * Gets template file
795 *
796 * @return string
797 */
798 public function getTemplateFile()
799 {
800 return $this->templateFile;
801 }
802
803 /**
804 * Gets MoveJsFromHeaderToFooter
805 *
806 * @return bool
807 */
808 public function getMoveJsFromHeaderToFooter()
809 {
810 return $this->moveJsFromHeaderToFooter;
811 }
812
813 /**
814 * Gets compress of javascript
815 *
816 * @return bool
817 */
818 public function getCompressJavascript()
819 {
820 return $this->compressJavascript;
821 }
822
823 /**
824 * Gets compress of css
825 *
826 * @return bool
827 */
828 public function getCompressCss()
829 {
830 return $this->compressCss;
831 }
832
833 /**
834 * Gets concatenate of js files
835 *
836 * @return bool
837 */
838 public function getConcatenateJavascript()
839 {
840 return $this->concatenateJavascript;
841 }
842
843 /**
844 * Gets concatenate of css files
845 *
846 * @return bool
847 */
848 public function getConcatenateCss()
849 {
850 return $this->concatenateCss;
851 }
852
853 /**
854 * Gets remove of empty lines from template
855 *
856 * @return bool
857 */
858 public function getRemoveLineBreaksFromTemplate()
859 {
860 return $this->removeLineBreaksFromTemplate;
861 }
862
863 /**
864 * Gets content for body
865 *
866 * @return string
867 */
868 public function getBodyContent()
869 {
870 return $this->bodyContent;
871 }
872
873 /**
874 * Gets the inline language labels.
875 *
876 * @return array The inline language labels
877 */
878 public function getInlineLanguageLabels()
879 {
880 return $this->inlineLanguageLabels;
881 }
882
883 /**
884 * Gets the inline language files
885 *
886 * @return array
887 */
888 public function getInlineLanguageLabelFiles()
889 {
890 return $this->inlineLanguageLabelFiles;
891 }
892
893 /*****************************************************/
894 /* */
895 /* Public Functions to add Data */
896 /* */
897 /* */
898 /*****************************************************/
899
900 /**
901 * Sets a given meta tag
902 *
903 * @param string $type The type of the meta tag. Allowed values are property, name or http-equiv
904 * @param string $name The name of the property to add
905 * @param string $content The content of the meta tag
906 * @param array $subProperties Subproperties of the meta tag (like e.g. og:image:width)
907 * @param bool $replace Replace earlier set meta tag
908 * @throws \InvalidArgumentException
909 */
910 public function setMetaTag(string $type, string $name, string $content, array $subProperties = [], $replace = true)
911 {
912 // Lowercase all the things
913 $type = strtolower($type);
914 $name = strtolower($name);
915 if (!in_array($type, ['property', 'name', 'http-equiv'], true)) {
916 throw new \InvalidArgumentException(
917 'When setting a meta tag the only types allowed are property, name or http-equiv. "' . $type . '" given.',
918 1496402460
919 );
920 }
921
922 $manager = $this->metaTagRegistry->getManagerForProperty($name);
923 $manager->addProperty($name, $content, $subProperties, $replace, $type);
924 }
925
926 /**
927 * Returns the requested meta tag
928 *
929 * @param string $type
930 * @param string $name
931 *
932 * @return array
933 */
934 public function getMetaTag(string $type, string $name): array
935 {
936 // Lowercase all the things
937 $type = strtolower($type);
938 $name = strtolower($name);
939
940 $manager = $this->metaTagRegistry->getManagerForProperty($name);
941 $propertyContent = $manager->getProperty($name, $type);
942
943 if (!empty($propertyContent[0])) {
944 return [
945 'type' => $type,
946 'name' => $name,
947 'content' => $propertyContent[0]['content']
948 ];
949 }
950 return [];
951 }
952
953 /**
954 * Unset the requested meta tag
955 *
956 * @param string $type
957 * @param string $name
958 */
959 public function removeMetaTag(string $type, string $name)
960 {
961 // Lowercase all the things
962 $type = strtolower($type);
963 $name = strtolower($name);
964
965 $manager = $this->metaTagRegistry->getManagerForProperty($name);
966 $manager->removeProperty($name, $type);
967 }
968
969 /**
970 * Adds inline HTML comment
971 *
972 * @param string $comment
973 */
974 public function addInlineComment($comment)
975 {
976 if (!in_array($comment, $this->inlineComments)) {
977 $this->inlineComments[] = $comment;
978 }
979 }
980
981 /**
982 * Adds header data
983 *
984 * @param string $data Free header data for HTML header
985 */
986 public function addHeaderData($data)
987 {
988 if (!in_array($data, $this->headerData)) {
989 $this->headerData[] = $data;
990 }
991 }
992
993 /**
994 * Adds footer data
995 *
996 * @param string $data Free header data for HTML header
997 */
998 public function addFooterData($data)
999 {
1000 if (!in_array($data, $this->footerData)) {
1001 $this->footerData[] = $data;
1002 }
1003 }
1004
1005 /**
1006 * Adds JS Library. JS Library block is rendered on top of the JS files.
1007 *
1008 * @param string $name Arbitrary identifier
1009 * @param string $file File name
1010 * @param string $type Content Type
1011 * @param bool $compress Flag if library should be compressed
1012 * @param bool $forceOnTop Flag if added library should be inserted at begin of this block
1013 * @param string $allWrap
1014 * @param bool $excludeFromConcatenation
1015 * @param string $splitChar The char used to split the allWrap value, default is "|"
1016 * @param bool $async Flag if property 'async="async"' should be added to JavaScript tags
1017 * @param string $integrity Subresource Integrity (SRI)
1018 * @param bool $defer Flag if property 'defer="defer"' should be added to JavaScript tags
1019 * @param string $crossorigin CORS settings attribute
1020 */
1021 public function addJsLibrary($name, $file, $type = 'text/javascript', $compress = false, $forceOnTop = false, $allWrap = '', $excludeFromConcatenation = false, $splitChar = '|', $async = false, $integrity = '', $defer = false, $crossorigin = '')
1022 {
1023 if (!$type) {
1024 $type = 'text/javascript';
1025 }
1026 if (!in_array(strtolower($name), $this->jsLibs)) {
1027 $this->jsLibs[strtolower($name)] = [
1028 'file' => $file,
1029 'type' => $type,
1030 'section' => self::PART_HEADER,
1031 'compress' => $compress,
1032 'forceOnTop' => $forceOnTop,
1033 'allWrap' => $allWrap,
1034 'excludeFromConcatenation' => $excludeFromConcatenation,
1035 'splitChar' => $splitChar,
1036 'async' => $async,
1037 'integrity' => $integrity,
1038 'defer' => $defer,
1039 'crossorigin' => $crossorigin,
1040 ];
1041 }
1042 }
1043
1044 /**
1045 * Adds JS Library to Footer. JS Library block is rendered on top of the Footer JS files.
1046 *
1047 * @param string $name Arbitrary identifier
1048 * @param string $file File name
1049 * @param string $type Content Type
1050 * @param bool $compress Flag if library should be compressed
1051 * @param bool $forceOnTop Flag if added library should be inserted at begin of this block
1052 * @param string $allWrap
1053 * @param bool $excludeFromConcatenation
1054 * @param string $splitChar The char used to split the allWrap value, default is "|"
1055 * @param bool $async Flag if property 'async="async"' should be added to JavaScript tags
1056 * @param string $integrity Subresource Integrity (SRI)
1057 * @param bool $defer Flag if property 'defer="defer"' should be added to JavaScript tags
1058 * @param string $crossorigin CORS settings attribute
1059 */
1060 public function addJsFooterLibrary($name, $file, $type = 'text/javascript', $compress = false, $forceOnTop = false, $allWrap = '', $excludeFromConcatenation = false, $splitChar = '|', $async = false, $integrity = '', $defer = false, $crossorigin = '')
1061 {
1062 if (!$type) {
1063 $type = 'text/javascript';
1064 }
1065 $name .= '_jsFooterLibrary';
1066 if (!in_array(strtolower($name), $this->jsLibs)) {
1067 $this->jsLibs[strtolower($name)] = [
1068 'file' => $file,
1069 'type' => $type,
1070 'section' => self::PART_FOOTER,
1071 'compress' => $compress,
1072 'forceOnTop' => $forceOnTop,
1073 'allWrap' => $allWrap,
1074 'excludeFromConcatenation' => $excludeFromConcatenation,
1075 'splitChar' => $splitChar,
1076 'async' => $async,
1077 'integrity' => $integrity,
1078 'defer' => $defer,
1079 'crossorigin' => $crossorigin,
1080 ];
1081 }
1082 }
1083
1084 /**
1085 * Adds JS file
1086 *
1087 * @param string $file File name
1088 * @param string $type Content Type
1089 * @param bool $compress
1090 * @param bool $forceOnTop
1091 * @param string $allWrap
1092 * @param bool $excludeFromConcatenation
1093 * @param string $splitChar The char used to split the allWrap value, default is "|"
1094 * @param bool $async Flag if property 'async="async"' should be added to JavaScript tags
1095 * @param string $integrity Subresource Integrity (SRI)
1096 * @param bool $defer Flag if property 'defer="defer"' should be added to JavaScript tags
1097 * @param string $crossorigin CORS settings attribute
1098 */
1099 public function addJsFile($file, $type = 'text/javascript', $compress = true, $forceOnTop = false, $allWrap = '', $excludeFromConcatenation = false, $splitChar = '|', $async = false, $integrity = '', $defer = false, $crossorigin = '')
1100 {
1101 if (!$type) {
1102 $type = 'text/javascript';
1103 }
1104 if (!isset($this->jsFiles[$file])) {
1105 $this->jsFiles[$file] = [
1106 'file' => $file,
1107 'type' => $type,
1108 'section' => self::PART_HEADER,
1109 'compress' => $compress,
1110 'forceOnTop' => $forceOnTop,
1111 'allWrap' => $allWrap,
1112 'excludeFromConcatenation' => $excludeFromConcatenation,
1113 'splitChar' => $splitChar,
1114 'async' => $async,
1115 'integrity' => $integrity,
1116 'defer' => $defer,
1117 'crossorigin' => $crossorigin,
1118 ];
1119 }
1120 }
1121
1122 /**
1123 * Adds JS file to footer
1124 *
1125 * @param string $file File name
1126 * @param string $type Content Type
1127 * @param bool $compress
1128 * @param bool $forceOnTop
1129 * @param string $allWrap
1130 * @param bool $excludeFromConcatenation
1131 * @param string $splitChar The char used to split the allWrap value, default is "|"
1132 * @param bool $async Flag if property 'async="async"' should be added to JavaScript tags
1133 * @param string $integrity Subresource Integrity (SRI)
1134 * @param bool $defer Flag if property 'defer="defer"' should be added to JavaScript tags
1135 * @param string $crossorigin CORS settings attribute
1136 */
1137 public function addJsFooterFile($file, $type = 'text/javascript', $compress = true, $forceOnTop = false, $allWrap = '', $excludeFromConcatenation = false, $splitChar = '|', $async = false, $integrity = '', $defer = false, $crossorigin = '')
1138 {
1139 if (!$type) {
1140 $type = 'text/javascript';
1141 }
1142 if (!isset($this->jsFiles[$file])) {
1143 $this->jsFiles[$file] = [
1144 'file' => $file,
1145 'type' => $type,
1146 'section' => self::PART_FOOTER,
1147 'compress' => $compress,
1148 'forceOnTop' => $forceOnTop,
1149 'allWrap' => $allWrap,
1150 'excludeFromConcatenation' => $excludeFromConcatenation,
1151 'splitChar' => $splitChar,
1152 'async' => $async,
1153 'integrity' => $integrity,
1154 'defer' => $defer,
1155 'crossorigin' => $crossorigin,
1156 ];
1157 }
1158 }
1159
1160 /**
1161 * Adds JS inline code
1162 *
1163 * @param string $name
1164 * @param string $block
1165 * @param bool $compress
1166 * @param bool $forceOnTop
1167 */
1168 public function addJsInlineCode($name, $block, $compress = true, $forceOnTop = false)
1169 {
1170 if (!isset($this->jsInline[$name]) && !empty($block)) {
1171 $this->jsInline[$name] = [
1172 'code' => $block . LF,
1173 'section' => self::PART_HEADER,
1174 'compress' => $compress,
1175 'forceOnTop' => $forceOnTop
1176 ];
1177 }
1178 }
1179
1180 /**
1181 * Adds JS inline code to footer
1182 *
1183 * @param string $name
1184 * @param string $block
1185 * @param bool $compress
1186 * @param bool $forceOnTop
1187 */
1188 public function addJsFooterInlineCode($name, $block, $compress = true, $forceOnTop = false)
1189 {
1190 if (!isset($this->jsInline[$name]) && !empty($block)) {
1191 $this->jsInline[$name] = [
1192 'code' => $block . LF,
1193 'section' => self::PART_FOOTER,
1194 'compress' => $compress,
1195 'forceOnTop' => $forceOnTop
1196 ];
1197 }
1198 }
1199
1200 /**
1201 * Adds CSS file
1202 *
1203 * @param string $file
1204 * @param string $rel
1205 * @param string $media
1206 * @param string $title
1207 * @param bool $compress
1208 * @param bool $forceOnTop
1209 * @param string $allWrap
1210 * @param bool $excludeFromConcatenation
1211 * @param string $splitChar The char used to split the allWrap value, default is "|"
1212 * @param bool $inline
1213 */
1214 public function addCssFile($file, $rel = 'stylesheet', $media = 'all', $title = '', $compress = true, $forceOnTop = false, $allWrap = '', $excludeFromConcatenation = false, $splitChar = '|', $inline = false)
1215 {
1216 if (!isset($this->cssFiles[$file])) {
1217 $this->cssFiles[$file] = [
1218 'file' => $file,
1219 'rel' => $rel,
1220 'media' => $media,
1221 'title' => $title,
1222 'compress' => $compress,
1223 'forceOnTop' => $forceOnTop,
1224 'allWrap' => $allWrap,
1225 'excludeFromConcatenation' => $excludeFromConcatenation,
1226 'splitChar' => $splitChar,
1227 'inline' => $inline
1228 ];
1229 }
1230 }
1231
1232 /**
1233 * Adds CSS file
1234 *
1235 * @param string $file
1236 * @param string $rel
1237 * @param string $media
1238 * @param string $title
1239 * @param bool $compress
1240 * @param bool $forceOnTop
1241 * @param string $allWrap
1242 * @param bool $excludeFromConcatenation
1243 * @param string $splitChar The char used to split the allWrap value, default is "|"
1244 * @param bool $inline
1245 */
1246 public function addCssLibrary($file, $rel = 'stylesheet', $media = 'all', $title = '', $compress = true, $forceOnTop = false, $allWrap = '', $excludeFromConcatenation = false, $splitChar = '|', $inline = false)
1247 {
1248 if (!isset($this->cssLibs[$file])) {
1249 $this->cssLibs[$file] = [
1250 'file' => $file,
1251 'rel' => $rel,
1252 'media' => $media,
1253 'title' => $title,
1254 'compress' => $compress,
1255 'forceOnTop' => $forceOnTop,
1256 'allWrap' => $allWrap,
1257 'excludeFromConcatenation' => $excludeFromConcatenation,
1258 'splitChar' => $splitChar,
1259 'inline' => $inline
1260 ];
1261 }
1262 }
1263
1264 /**
1265 * Adds CSS inline code
1266 *
1267 * @param string $name
1268 * @param string $block
1269 * @param bool $compress
1270 * @param bool $forceOnTop
1271 */
1272 public function addCssInlineBlock($name, $block, $compress = false, $forceOnTop = false)
1273 {
1274 if (!isset($this->cssInline[$name]) && !empty($block)) {
1275 $this->cssInline[$name] = [
1276 'code' => $block,
1277 'compress' => $compress,
1278 'forceOnTop' => $forceOnTop
1279 ];
1280 }
1281 }
1282
1283 /**
1284 * Call function if you need the requireJS library
1285 * this automatically adds the JavaScript path of all loaded extensions in the requireJS path option
1286 * so it resolves names like TYPO3/CMS/MyExtension/MyJsFile to EXT:MyExtension/Resources/Public/JavaScript/MyJsFile.js
1287 * when using requireJS
1288 */
1289 public function loadRequireJs()
1290 {
1291 $this->addRequireJs = true;
1292 if (!empty($this->requireJsConfig) && !empty($this->publicRequireJsConfig)) {
1293 return;
1294 }
1295
1296 $loadedExtensions = ExtensionManagementUtility::getLoadedExtensionListArray();
1297 $isDevelopment = GeneralUtility::getApplicationContext()->isDevelopment();
1298 $cacheIdentifier = 'requireJS_' . md5(implode(',', $loadedExtensions) . ($isDevelopment ? ':dev' : '') . GeneralUtility::getIndpEnv('TYPO3_REQUEST_SCRIPT'));
1299 /** @var FrontendInterface $cache */
1300 $cache = static::$cache ?? GeneralUtility::makeInstance(CacheManager::class)->getCache('assets');
1301 $requireJsConfig = $cache->get($cacheIdentifier);
1302
1303 // if we did not get a configuration from the cache, compute and store it in the cache
1304 if (!isset($requireJsConfig['internal']) || !isset($requireJsConfig['public'])) {
1305 $requireJsConfig = $this->computeRequireJsConfig($isDevelopment, $loadedExtensions);
1306 $cache->set($cacheIdentifier, $requireJsConfig);
1307 }
1308
1309 $this->requireJsConfig = $requireJsConfig['internal'];
1310 $this->publicRequireJsConfig = $requireJsConfig['public'];
1311 $this->internalRequireJsPathModuleNames = $requireJsConfig['internalNames'];
1312 }
1313
1314 /**
1315 * Computes the RequireJS configuration, mainly consisting of the paths to the core and all extension JavaScript
1316 * resource folders plus some additional generic configuration.
1317 *
1318 * @param bool $isDevelopment
1319 * @param array $loadedExtensions
1320 * @return array The RequireJS configuration
1321 */
1322 protected function computeRequireJsConfig($isDevelopment, array $loadedExtensions)
1323 {
1324 // load all paths to map to package names / namespaces
1325 $requireJsConfig = [
1326 'public' => [],
1327 'internal' => [],
1328 'internalNames' => [],
1329 ];
1330
1331 // In order to avoid browser caching of JS files, adding a GET parameter to the files loaded via requireJS
1332 if ($isDevelopment) {
1333 $requireJsConfig['public']['urlArgs'] = 'bust=' . $GLOBALS['EXEC_TIME'];
1334 } else {
1335 $requireJsConfig['public']['urlArgs'] = 'bust=' . GeneralUtility::hmac(TYPO3_version . Environment::getProjectPath());
1336 }
1337 $corePath = ExtensionManagementUtility::extPath('core', 'Resources/Public/JavaScript/Contrib/');
1338 $corePath = PathUtility::getAbsoluteWebPath($corePath);
1339 // first, load all paths for the namespaces, and configure contrib libs.
1340 $requireJsConfig['public']['paths'] = [
1341 'jquery' => $corePath . '/jquery/jquery',
1342 'jquery-ui' => $corePath . 'jquery-ui',
1343 'datatables' => $corePath . 'jquery.dataTables',
1344 'nprogress' => $corePath . 'nprogress',
1345 'moment' => $corePath . 'moment',
1346 'cropper' => $corePath . 'cropper.min',
1347 'imagesloaded' => $corePath . 'imagesloaded.pkgd.min',
1348 'bootstrap' => $corePath . 'bootstrap/bootstrap',
1349 'twbs/bootstrap-datetimepicker' => $corePath . 'bootstrap-datetimepicker',
1350 'autosize' => $corePath . 'autosize',
1351 'taboverride' => $corePath . 'taboverride.min',
1352 'twbs/bootstrap-slider' => $corePath . 'bootstrap-slider.min',
1353 'jquery/autocomplete' => $corePath . 'jquery.autocomplete',
1354 'd3' => $corePath . 'd3/d3'
1355 ];
1356 $requireJsConfig['public']['waitSeconds'] = 30;
1357 $requireJsConfig['public']['typo3BaseUrl'] = false;
1358 $publicPackageNames = ['core', 'frontend', 'backend'];
1359 foreach ($loadedExtensions as $packageName) {
1360 $jsPath = 'EXT:' . $packageName . '/Resources/Public/JavaScript/';
1361 $absoluteJsPath = GeneralUtility::getFileAbsFileName($jsPath);
1362 $fullJsPath = PathUtility::getAbsoluteWebPath($absoluteJsPath);
1363 $fullJsPath = rtrim($fullJsPath, '/');
1364 if (!empty($fullJsPath) && file_exists($absoluteJsPath)) {
1365 $type = in_array($packageName, $publicPackageNames, true) ? 'public' : 'internal';
1366 $requireJsConfig[$type]['paths']['TYPO3/CMS/' . GeneralUtility::underscoredToUpperCamelCase($packageName)] = $fullJsPath;
1367 }
1368 }
1369 // sanitize module names in internal 'paths'
1370 $internalPathModuleNames = array_keys($requireJsConfig['internal']['paths'] ?? []);
1371 $sanitizedInternalPathModuleNames = array_map(
1372 function ($moduleName) {
1373 // trim spaces and slashes & add ending slash
1374 return trim($moduleName, ' /') . '/';
1375 },
1376 $internalPathModuleNames
1377 );
1378 $requireJsConfig['internalNames'] = array_combine(
1379 $sanitizedInternalPathModuleNames,
1380 $internalPathModuleNames
1381 );
1382
1383 // check if additional AMD modules need to be loaded if a single AMD module is initialized
1384 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['RequireJS']['postInitializationModules'] ?? false)) {
1385 $this->addInlineSettingArray(
1386 'RequireJS.PostInitializationModules',
1387 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['RequireJS']['postInitializationModules']
1388 );
1389 }
1390
1391 return $requireJsConfig;
1392 }
1393
1394 /**
1395 * Add additional configuration to require js.
1396 *
1397 * Configuration will be merged recursive with overrule.
1398 *
1399 * To add another path mapping deliver the following configuration:
1400 * 'paths' => array(
1401 * 'EXTERN/mybootstrapjs' => 'sysext/.../twbs/bootstrap.min',
1402 * ),
1403 *
1404 * @param array $configuration The configuration that will be merged with existing one.
1405 */
1406 public function addRequireJsConfiguration(array $configuration)
1407 {
1408 if (TYPO3_MODE === 'BE') {
1409 // Load RequireJS in backend context at first. Doing this in FE could break the output
1410 $this->loadRequireJs();
1411 }
1412 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($this->requireJsConfig, $configuration);
1413 }
1414
1415 /**
1416 * Generates RequireJS loader HTML markup.
1417 *
1418 * @return string
1419 * @throws \TYPO3\CMS\Backend\Routing\Exception\RouteNotFoundException
1420 */
1421 protected function getRequireJsLoader(): string
1422 {
1423 $html = '';
1424 $backendRequest = TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_BE;
1425 $backendUserLoggedIn = !empty($GLOBALS['BE_USER']->user['uid']);
1426
1427 // no backend request - basically frontend
1428 if (!$backendRequest) {
1429 $requireJsConfig = $this->getRequireJsConfig(static::REQUIREJS_SCOPE_CONFIG);
1430 $requireJsConfig['typo3BaseUrl'] = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH') . '?eID=requirejs';
1431 // backend request, but no backend user logged in
1432 } elseif (!$backendUserLoggedIn) {
1433 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
1434 $requireJsConfig = $this->getRequireJsConfig(static::REQUIREJS_SCOPE_CONFIG);
1435 $requireJsConfig['typo3BaseUrl'] = (string)$uriBuilder->buildUriFromRoute('ajax_core_requirejs');
1436 // backend request, having backend user logged in
1437 } else {
1438 $requireJsConfig = array_replace_recursive(
1439 $this->publicRequireJsConfig,
1440 $this->requireJsConfig
1441 );
1442 }
1443
1444 // add (probably filtered) RequireJS configuration
1445 $html .= GeneralUtility::wrapJS('var require = ' . json_encode($requireJsConfig)) . LF;
1446 // directly after that, include the require.js file
1447 $html .= '<script src="'
1448 . $this->processJsFile($this->requireJsPath . 'require.js')
1449 . '" type="text/javascript"></script>' . LF;
1450
1451 if (!empty($requireJsConfig['typo3BaseUrl'])) {
1452 $html .= '<script src="'
1453 . $this->processJsFile(
1454 'EXT:core/Resources/Public/JavaScript/requirejs-loader.js'
1455 )
1456 . '" type="text/javascript"></script>' . LF;
1457 }
1458
1459 return $html;
1460 }
1461
1462 /**
1463 * @param array $array
1464 * @param string[] $keys
1465 * @param bool $keep
1466 * @return array
1467 */
1468 protected function filterArrayKeys(array $array, array $keys, bool $keep = true): array
1469 {
1470 return array_filter(
1471 $array,
1472 function (string $key) use ($keys, $keep) {
1473 return in_array($key, $keys, true) === $keep;
1474 },
1475 ARRAY_FILTER_USE_KEY
1476 );
1477 }
1478
1479 /**
1480 * includes an AMD-compatible JS file by resolving the ModuleName, and then requires the file via a requireJS request,
1481 * additionally allowing to execute JavaScript code afterwards
1482 *
1483 * this function only works for AMD-ready JS modules, used like "define('TYPO3/CMS/Backend/FormEngine..."
1484 * in the JS file
1485 *
1486 * TYPO3/CMS/Backend/FormEngine =>
1487 * "TYPO3": Vendor Name
1488 * "CMS": Product Name
1489 * "Backend": Extension Name
1490 * "FormEngine": FileName in the Resources/Public/JavaScript folder
1491 *
1492 * @param string $mainModuleName Must be in the form of "TYPO3/CMS/PackageName/ModuleName" e.g. "TYPO3/CMS/Backend/FormEngine"
1493 * @param string $callBackFunction loaded right after the requireJS loading, must be wrapped in function() {}
1494 */
1495 public function loadRequireJsModule($mainModuleName, $callBackFunction = null)
1496 {
1497 $inlineCodeKey = $mainModuleName;
1498 // make sure requireJS is initialized
1499 $this->loadRequireJs();
1500 // move internal module path definition to public module definition
1501 // (since loading a module ends up disclosing the existence anyway)
1502 $baseModuleName = $this->findRequireJsBaseModuleName($mainModuleName);
1503 if ($baseModuleName !== null && isset($this->requireJsConfig['paths'][$baseModuleName])) {
1504 $this->publicRequireJsConfig['paths'][$baseModuleName] = $this->requireJsConfig['paths'][$baseModuleName];
1505 unset($this->requireJsConfig['paths'][$baseModuleName]);
1506 }
1507 // execute the main module, and load a possible callback function
1508 $javaScriptCode = 'require(["' . $mainModuleName . '"]';
1509 if ($callBackFunction !== null) {
1510 $inlineCodeKey .= sha1($callBackFunction);
1511 $javaScriptCode .= ', ' . $callBackFunction;
1512 }
1513 $javaScriptCode .= ');';
1514 $this->addJsInlineCode('RequireJS-Module-' . $inlineCodeKey, $javaScriptCode);
1515 }
1516
1517 /**
1518 * Determines requireJS base module name (if defined).
1519 *
1520 * @param string $moduleName
1521 * @return string|null
1522 */
1523 protected function findRequireJsBaseModuleName(string $moduleName)
1524 {
1525 // trim spaces and slashes & add ending slash
1526 $sanitizedModuleName = trim($moduleName, ' /') . '/';
1527 foreach ($this->internalRequireJsPathModuleNames as $sanitizedBaseModuleName => $baseModuleName) {
1528 if (strpos($sanitizedModuleName, $sanitizedBaseModuleName) === 0) {
1529 return $baseModuleName;
1530 }
1531 }
1532 return null;
1533 }
1534
1535 /**
1536 * Adds Javascript Inline Label. This will occur in TYPO3.lang - object
1537 * The label can be used in scripts with TYPO3.lang.<key>
1538 *
1539 * @param string $key
1540 * @param string $value
1541 */
1542 public function addInlineLanguageLabel($key, $value)
1543 {
1544 $this->inlineLanguageLabels[$key] = $value;
1545 }
1546
1547 /**
1548 * Adds Javascript Inline Label Array. This will occur in TYPO3.lang - object
1549 * The label can be used in scripts with TYPO3.lang.<key>
1550 * Array will be merged with existing array.
1551 *
1552 * @param array $array
1553 */
1554 public function addInlineLanguageLabelArray(array $array)
1555 {
1556 $this->inlineLanguageLabels = array_merge($this->inlineLanguageLabels, $array);
1557 }
1558
1559 /**
1560 * Gets labels to be used in JavaScript fetched from a locallang file.
1561 *
1562 * @param string $fileRef Input is a file-reference (see GeneralUtility::getFileAbsFileName). That file is expected to be a 'locallang.xlf' file containing a valid XML TYPO3 language structure.
1563 * @param string $selectionPrefix Prefix to select the correct labels (default: '')
1564 * @param string $stripFromSelectionName String to be removed from the label names in the output. (default: '')
1565 */
1566 public function addInlineLanguageLabelFile($fileRef, $selectionPrefix = '', $stripFromSelectionName = '')
1567 {
1568 $index = md5($fileRef . $selectionPrefix . $stripFromSelectionName);
1569 if ($fileRef && !isset($this->inlineLanguageLabelFiles[$index])) {
1570 $this->inlineLanguageLabelFiles[$index] = [
1571 'fileRef' => $fileRef,
1572 'selectionPrefix' => $selectionPrefix,
1573 'stripFromSelectionName' => $stripFromSelectionName
1574 ];
1575 }
1576 }
1577
1578 /**
1579 * Adds Javascript Inline Setting. This will occur in TYPO3.settings - object
1580 * The label can be used in scripts with TYPO3.setting.<key>
1581 *
1582 * @param string $namespace
1583 * @param string $key
1584 * @param mixed $value
1585 */
1586 public function addInlineSetting($namespace, $key, $value)
1587 {
1588 if ($namespace) {
1589 if (strpos($namespace, '.')) {
1590 $parts = explode('.', $namespace);
1591 $a = &$this->inlineSettings;
1592 foreach ($parts as $part) {
1593 $a = &$a[$part];
1594 }
1595 $a[$key] = $value;
1596 } else {
1597 $this->inlineSettings[$namespace][$key] = $value;
1598 }
1599 } else {
1600 $this->inlineSettings[$key] = $value;
1601 }
1602 }
1603
1604 /**
1605 * Adds Javascript Inline Setting. This will occur in TYPO3.settings - object
1606 * The label can be used in scripts with TYPO3.setting.<key>
1607 * Array will be merged with existing array.
1608 *
1609 * @param string $namespace
1610 * @param array $array
1611 */
1612 public function addInlineSettingArray($namespace, array $array)
1613 {
1614 if ($namespace) {
1615 if (strpos($namespace, '.')) {
1616 $parts = explode('.', $namespace);
1617 $a = &$this->inlineSettings;
1618 foreach ($parts as $part) {
1619 $a = &$a[$part];
1620 }
1621 $a = array_merge((array)$a, $array);
1622 } else {
1623 $this->inlineSettings[$namespace] = array_merge((array)$this->inlineSettings[$namespace], $array);
1624 }
1625 } else {
1626 $this->inlineSettings = array_merge($this->inlineSettings, $array);
1627 }
1628 }
1629
1630 /**
1631 * Adds content to body content
1632 *
1633 * @param string $content
1634 */
1635 public function addBodyContent($content)
1636 {
1637 $this->bodyContent .= $content;
1638 }
1639
1640 /*****************************************************/
1641 /* */
1642 /* Render Functions */
1643 /* */
1644 /*****************************************************/
1645 /**
1646 * Render the section (Header or Footer)
1647 *
1648 * @param int $part Section which should be rendered: self::PART_COMPLETE, self::PART_HEADER or self::PART_FOOTER
1649 * @return string Content of rendered section
1650 */
1651 public function render($part = self::PART_COMPLETE)
1652 {
1653 $this->prepareRendering();
1654 list($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs) = $this->renderJavaScriptAndCss();
1655 $metaTags = implode(LF, array_merge($this->metaTags, $this->renderMetaTagsFromAPI()));
1656 $markerArray = $this->getPreparedMarkerArray($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs, $metaTags);
1657 $template = $this->getTemplateForPart($part);
1658
1659 // The page renderer needs a full reset, even when only rendering one part of the page
1660 // This means that you can only register footer files *after* the header has been already rendered.
1661 // In case you render the footer part first, header files can only be added *after* the footer has been rendered
1662 $this->reset();
1663 $templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
1664 return trim($templateService->substituteMarkerArray($template, $markerArray, '###|###'));
1665 }
1666
1667 /**
1668 * Renders metaTags based on tags added via the API
1669 *
1670 * @return array
1671 */
1672 protected function renderMetaTagsFromAPI()
1673 {
1674 $metaTags = [];
1675 $metaTagManagers = $this->metaTagRegistry->getAllManagers();
1676 try {
1677 $cache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pages');
1678 } catch (NoSuchCacheException $e) {
1679 $cache = null;
1680 }
1681
1682 foreach ($metaTagManagers as $manager => $managerObject) {
1683 $cacheIdentifier = $this->getTypoScriptFrontendController()->newHash . '-metatag-' . $manager;
1684
1685 $existingCacheEntry = false;
1686 if ($cache instanceof FrontendInterface && $properties = $cache->get($cacheIdentifier)) {
1687 $existingCacheEntry = true;
1688 } else {
1689 $properties = $managerObject->renderAllProperties();
1690 }
1691
1692 if (!empty($properties)) {
1693 $metaTags[] = $properties;
1694
1695 if ($cache instanceof FrontendInterface && !$existingCacheEntry && ($this->getTypoScriptFrontendController()->page['uid'] ?? false)) {
1696 $cache->set(
1697 $cacheIdentifier,
1698 $properties,
1699 ['pageId_' . $this->getTypoScriptFrontendController()->page['uid']],
1700 $this->getTypoScriptFrontendController()->get_cache_timeout()
1701 );
1702 }
1703 }
1704 }
1705 return $metaTags;
1706 }
1707
1708 /**
1709 * Render the page but not the JavaScript and CSS Files
1710 *
1711 * @param string $substituteHash The hash that is used for the placehoder markers
1712 * @internal
1713 * @return string Content of rendered section
1714 */
1715 public function renderPageWithUncachedObjects($substituteHash)
1716 {
1717 $this->prepareRendering();
1718 $markerArray = $this->getPreparedMarkerArrayForPageWithUncachedObjects($substituteHash);
1719 $template = $this->getTemplateForPart(self::PART_COMPLETE);
1720 $templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
1721 return trim($templateService->substituteMarkerArray($template, $markerArray, '###|###'));
1722 }
1723
1724 /**
1725 * Renders the JavaScript and CSS files that have been added during processing
1726 * of uncached content objects (USER_INT, COA_INT)
1727 *
1728 * @param string $cachedPageContent
1729 * @param string $substituteHash The hash that is used for the placehoder markers
1730 * @internal
1731 * @return string
1732 */
1733 public function renderJavaScriptAndCssForProcessingOfUncachedContentObjects($cachedPageContent, $substituteHash)
1734 {
1735 $this->prepareRendering();
1736 list($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs) = $this->renderJavaScriptAndCss();
1737 $title = $this->title ? str_replace('|', htmlspecialchars($this->title), $this->titleTag) : '';
1738 $markerArray = [
1739 '<!-- ###TITLE' . $substituteHash . '### -->' => $title,
1740 '<!-- ###CSS_LIBS' . $substituteHash . '### -->' => $cssLibs,
1741 '<!-- ###CSS_INCLUDE' . $substituteHash . '### -->' => $cssFiles,
1742 '<!-- ###CSS_INLINE' . $substituteHash . '### -->' => $cssInline,
1743 '<!-- ###JS_INLINE' . $substituteHash . '### -->' => $jsInline,
1744 '<!-- ###JS_INCLUDE' . $substituteHash . '### -->' => $jsFiles,
1745 '<!-- ###JS_LIBS' . $substituteHash . '### -->' => $jsLibs,
1746 '<!-- ###META' . $substituteHash . '### -->' => implode(LF, array_merge($this->metaTags, $this->renderMetaTagsFromAPI())),
1747 '<!-- ###HEADERDATA' . $substituteHash . '### -->' => implode(LF, $this->headerData),
1748 '<!-- ###FOOTERDATA' . $substituteHash . '### -->' => implode(LF, $this->footerData),
1749 '<!-- ###JS_LIBS_FOOTER' . $substituteHash . '### -->' => $jsFooterLibs,
1750 '<!-- ###JS_INCLUDE_FOOTER' . $substituteHash . '### -->' => $jsFooterFiles,
1751 '<!-- ###JS_INLINE_FOOTER' . $substituteHash . '### -->' => $jsFooterInline
1752 ];
1753 foreach ($markerArray as $placeHolder => $content) {
1754 $cachedPageContent = str_replace($placeHolder, $content, $cachedPageContent);
1755 }
1756 $this->reset();
1757 return $cachedPageContent;
1758 }
1759
1760 /**
1761 * Remove ending slashes from static header block
1762 * if the page is being rendered as html (not xhtml)
1763 * and define property $this->endingSlash for further use
1764 */
1765 protected function prepareRendering()
1766 {
1767 if ($this->getRenderXhtml()) {
1768 $this->endingSlash = ' /';
1769 } else {
1770 $this->metaCharsetTag = str_replace(' />', '>', $this->metaCharsetTag);
1771 $this->baseUrlTag = str_replace(' />', '>', $this->baseUrlTag);
1772 $this->shortcutTag = str_replace(' />', '>', $this->shortcutTag);
1773 $this->endingSlash = '';
1774 }
1775 }
1776
1777 /**
1778 * Renders all JavaScript and CSS
1779 *
1780 * @return array<string>
1781 */
1782 protected function renderJavaScriptAndCss()
1783 {
1784 $this->executePreRenderHook();
1785 $mainJsLibs = $this->renderMainJavaScriptLibraries();
1786 if ($this->concatenateJavascript || $this->concatenateCss) {
1787 // Do the file concatenation
1788 $this->doConcatenate();
1789 }
1790 if ($this->compressCss || $this->compressJavascript) {
1791 // Do the file compression
1792 $this->doCompress();
1793 }
1794 $this->executeRenderPostTransformHook();
1795 $cssLibs = $this->renderCssLibraries();
1796 $cssFiles = $this->renderCssFiles();
1797 $cssInline = $this->renderCssInline();
1798 list($jsLibs, $jsFooterLibs) = $this->renderAdditionalJavaScriptLibraries();
1799 list($jsFiles, $jsFooterFiles) = $this->renderJavaScriptFiles();
1800 list($jsInline, $jsFooterInline) = $this->renderInlineJavaScript();
1801 $jsLibs = $mainJsLibs . $jsLibs;
1802 if ($this->moveJsFromHeaderToFooter) {
1803 $jsFooterLibs = $jsLibs . LF . $jsFooterLibs;
1804 $jsLibs = '';
1805 $jsFooterFiles = $jsFiles . LF . $jsFooterFiles;
1806 $jsFiles = '';
1807 $jsFooterInline = $jsInline . LF . $jsFooterInline;
1808 $jsInline = '';
1809 }
1810 $this->executePostRenderHook($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs);
1811 return [$jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs];
1812 }
1813
1814 /**
1815 * Fills the marker array with the given strings and trims each value
1816 *
1817 * @param string $jsLibs
1818 * @param string $jsFiles
1819 * @param string $jsFooterFiles
1820 * @param string $cssLibs
1821 * @param string $cssFiles
1822 * @param string $jsInline
1823 * @param string $cssInline
1824 * @param string $jsFooterInline
1825 * @param string $jsFooterLibs
1826 * @param string $metaTags
1827 * @return array Marker array
1828 */
1829 protected function getPreparedMarkerArray($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs, $metaTags)
1830 {
1831 $markerArray = [
1832 'XMLPROLOG_DOCTYPE' => $this->xmlPrologAndDocType,
1833 'HTMLTAG' => $this->htmlTag,
1834 'HEADTAG' => $this->headTag,
1835 'METACHARSET' => $this->charSet ? str_replace('|', htmlspecialchars($this->charSet), $this->metaCharsetTag) : '',
1836 'INLINECOMMENT' => $this->inlineComments ? LF . LF . '<!-- ' . LF . implode(LF, $this->inlineComments) . '-->' . LF . LF : '',
1837 'BASEURL' => $this->baseUrl ? str_replace('|', $this->baseUrl, $this->baseUrlTag) : '',
1838 'SHORTCUT' => $this->favIcon ? sprintf($this->shortcutTag, htmlspecialchars($this->favIcon), $this->iconMimeType) : '',
1839 'CSS_LIBS' => $cssLibs,
1840 'CSS_INCLUDE' => $cssFiles,
1841 'CSS_INLINE' => $cssInline,
1842 'JS_INLINE' => $jsInline,
1843 'JS_INCLUDE' => $jsFiles,
1844 'JS_LIBS' => $jsLibs,
1845 'TITLE' => $this->title ? str_replace('|', htmlspecialchars($this->title), $this->titleTag) : '',
1846 'META' => $metaTags,
1847 'HEADERDATA' => $this->headerData ? implode(LF, $this->headerData) : '',
1848 'FOOTERDATA' => $this->footerData ? implode(LF, $this->footerData) : '',
1849 'JS_LIBS_FOOTER' => $jsFooterLibs,
1850 'JS_INCLUDE_FOOTER' => $jsFooterFiles,
1851 'JS_INLINE_FOOTER' => $jsFooterInline,
1852 'BODY' => $this->bodyContent
1853 ];
1854 $markerArray = array_map('trim', $markerArray);
1855 return $markerArray;
1856 }
1857
1858 /**
1859 * Fills the marker array with the given strings and trims each value
1860 *
1861 * @param string $substituteHash The hash that is used for the placehoder markers
1862 * @return array Marker array
1863 */
1864 protected function getPreparedMarkerArrayForPageWithUncachedObjects($substituteHash)
1865 {
1866 $markerArray = [
1867 'XMLPROLOG_DOCTYPE' => $this->xmlPrologAndDocType,
1868 'HTMLTAG' => $this->htmlTag,
1869 'HEADTAG' => $this->headTag,
1870 'METACHARSET' => $this->charSet ? str_replace('|', htmlspecialchars($this->charSet), $this->metaCharsetTag) : '',
1871 'INLINECOMMENT' => $this->inlineComments ? LF . LF . '<!-- ' . LF . implode(LF, $this->inlineComments) . '-->' . LF . LF : '',
1872 'BASEURL' => $this->baseUrl ? str_replace('|', $this->baseUrl, $this->baseUrlTag) : '',
1873 'SHORTCUT' => $this->favIcon ? sprintf($this->shortcutTag, htmlspecialchars($this->favIcon), $this->iconMimeType) : '',
1874 'META' => '<!-- ###META' . $substituteHash . '### -->',
1875 'BODY' => $this->bodyContent,
1876 'TITLE' => '<!-- ###TITLE' . $substituteHash . '### -->',
1877 'CSS_LIBS' => '<!-- ###CSS_LIBS' . $substituteHash . '### -->',
1878 'CSS_INCLUDE' => '<!-- ###CSS_INCLUDE' . $substituteHash . '### -->',
1879 'CSS_INLINE' => '<!-- ###CSS_INLINE' . $substituteHash . '### -->',
1880 'JS_INLINE' => '<!-- ###JS_INLINE' . $substituteHash . '### -->',
1881 'JS_INCLUDE' => '<!-- ###JS_INCLUDE' . $substituteHash . '### -->',
1882 'JS_LIBS' => '<!-- ###JS_LIBS' . $substituteHash . '### -->',
1883 'HEADERDATA' => '<!-- ###HEADERDATA' . $substituteHash . '### -->',
1884 'FOOTERDATA' => '<!-- ###FOOTERDATA' . $substituteHash . '### -->',
1885 'JS_LIBS_FOOTER' => '<!-- ###JS_LIBS_FOOTER' . $substituteHash . '### -->',
1886 'JS_INCLUDE_FOOTER' => '<!-- ###JS_INCLUDE_FOOTER' . $substituteHash . '### -->',
1887 'JS_INLINE_FOOTER' => '<!-- ###JS_INLINE_FOOTER' . $substituteHash . '### -->'
1888 ];
1889 $markerArray = array_map('trim', $markerArray);
1890 return $markerArray;
1891 }
1892
1893 /**
1894 * Reads the template file and returns the requested part as string
1895 *
1896 * @param int $part
1897 * @return string
1898 */
1899 protected function getTemplateForPart($part)
1900 {
1901 $templateFile = GeneralUtility::getFileAbsFileName($this->templateFile);
1902 if (is_file($templateFile)) {
1903 $template = file_get_contents($templateFile);
1904 if ($this->removeLineBreaksFromTemplate) {
1905 $template = strtr($template, [LF => '', CR => '']);
1906 }
1907 if ($part !== self::PART_COMPLETE) {
1908 $templatePart = explode('###BODY###', $template);
1909 $template = $templatePart[$part - 1];
1910 }
1911 } else {
1912 $template = '';
1913 }
1914 return $template;
1915 }
1916
1917 /**
1918 * Helper function for render the main JavaScript libraries,
1919 * currently: RequireJS
1920 *
1921 * @return string Content with JavaScript libraries
1922 */
1923 protected function renderMainJavaScriptLibraries()
1924 {
1925 $out = '';
1926
1927 // Include RequireJS
1928 if ($this->addRequireJs) {
1929 $out .= $this->getRequireJsLoader();
1930 }
1931
1932 $this->loadJavaScriptLanguageStrings();
1933 if (TYPO3_MODE === 'BE') {
1934 $noBackendUserLoggedIn = empty($GLOBALS['BE_USER']->user['uid']);
1935 $this->addAjaxUrlsToInlineSettings($noBackendUserLoggedIn);
1936 }
1937 $inlineSettings = '';
1938 $languageLabels = $this->parseLanguageLabelsForJavaScript();
1939 if (!empty($languageLabels)) {
1940 $inlineSettings .= 'TYPO3.lang = ' . json_encode($languageLabels) . ';';
1941 }
1942 $inlineSettings .= $this->inlineSettings ? 'TYPO3.settings = ' . json_encode($this->inlineSettings) . ';' : '';
1943
1944 if ($inlineSettings !== '') {
1945 // make sure the global TYPO3 is available
1946 $inlineSettings = 'var TYPO3 = TYPO3 || {};' . CRLF . $inlineSettings;
1947 $out .= $this->inlineJavascriptWrap[0] . $inlineSettings . $this->inlineJavascriptWrap[1];
1948 }
1949
1950 return $out;
1951 }
1952
1953 /**
1954 * Converts the language labels for usage in JavaScript
1955 *
1956 * @return array
1957 */
1958 protected function parseLanguageLabelsForJavaScript(): array
1959 {
1960 if (empty($this->inlineLanguageLabels)) {
1961 return [];
1962 }
1963
1964 $labels = [];
1965 foreach ($this->inlineLanguageLabels as $key => $translationUnit) {
1966 if (is_array($translationUnit)) {
1967 $translationUnit = current($translationUnit);
1968 $labels[$key] = $translationUnit['target'] ?? $translationUnit['source'];
1969 } else {
1970 $labels[$key] = $translationUnit;
1971 }
1972 }
1973
1974 return $labels;
1975 }
1976
1977 /**
1978 * Load the language strings into JavaScript
1979 */
1980 protected function loadJavaScriptLanguageStrings()
1981 {
1982 if (!empty($this->inlineLanguageLabelFiles)) {
1983 foreach ($this->inlineLanguageLabelFiles as $languageLabelFile) {
1984 $this->includeLanguageFileForInline($languageLabelFile['fileRef'], $languageLabelFile['selectionPrefix'], $languageLabelFile['stripFromSelectionName']);
1985 }
1986 }
1987 $this->inlineLanguageLabelFiles = [];
1988 // Convert settings back to UTF-8 since json_encode() only works with UTF-8:
1989 if ($this->getCharSet() && $this->getCharSet() !== 'utf-8' && is_array($this->inlineSettings)) {
1990 $this->convertCharsetRecursivelyToUtf8($this->inlineSettings, $this->getCharSet());
1991 }
1992 }
1993
1994 /**
1995 * Small helper function to convert charsets for arrays into utf-8
1996 *
1997 * @param mixed $data given by reference (string/array usually)
1998 * @param string $fromCharset convert FROM this charset
1999 */
2000 protected function convertCharsetRecursivelyToUtf8(&$data, string $fromCharset)
2001 {
2002 foreach ($data as $key => $value) {
2003 if (is_array($data[$key])) {
2004 $this->convertCharsetRecursivelyToUtf8($data[$key], $fromCharset);
2005 } elseif (is_string($data[$key])) {
2006 $data[$key] = mb_convert_encoding($data[$key], 'utf-8', $fromCharset);
2007 }
2008 }
2009 }
2010
2011 /**
2012 * Make URLs to all backend ajax handlers available as inline setting.
2013 *
2014 * @param bool $publicRoutesOnly
2015 */
2016 protected function addAjaxUrlsToInlineSettings(bool $publicRoutesOnly = false)
2017 {
2018 $ajaxUrls = [];
2019 // Add the ajax-based routes
2020 /** @var UriBuilder $uriBuilder */
2021 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2022 /** @var Router $router */
2023 $router = GeneralUtility::makeInstance(Router::class);
2024 $routes = $router->getRoutes();
2025 foreach ($routes as $routeIdentifier => $route) {
2026 if ($publicRoutesOnly && $route->getOption('access') !== 'public') {
2027 continue;
2028 }
2029 if ($route->getOption('ajax')) {
2030 $uri = (string)$uriBuilder->buildUriFromRoute($routeIdentifier);
2031 // use the shortened value in order to use this in JavaScript
2032 $routeIdentifier = str_replace('ajax_', '', $routeIdentifier);
2033 $ajaxUrls[$routeIdentifier] = $uri;
2034 }
2035 }
2036
2037 $this->inlineSettings['ajaxUrls'] = $ajaxUrls;
2038 }
2039
2040 /**
2041 * Render CSS library files
2042 *
2043 * @return string
2044 */
2045 protected function renderCssLibraries()
2046 {
2047 $cssFiles = '';
2048 if (!empty($this->cssLibs)) {
2049 foreach ($this->cssLibs as $file => $properties) {
2050 $tag = $this->createCssTag($properties, $file);
2051 if ($properties['forceOnTop']) {
2052 $cssFiles = $tag . $cssFiles;
2053 } else {
2054 $cssFiles .= $tag;
2055 }
2056 }
2057 }
2058 return $cssFiles;
2059 }
2060
2061 /**
2062 * Render CSS files
2063 *
2064 * @return string
2065 */
2066 protected function renderCssFiles()
2067 {
2068 $cssFiles = '';
2069 if (!empty($this->cssFiles)) {
2070 foreach ($this->cssFiles as $file => $properties) {
2071 $tag = $this->createCssTag($properties, $file);
2072 if ($properties['forceOnTop']) {
2073 $cssFiles = $tag . $cssFiles;
2074 } else {
2075 $cssFiles .= $tag;
2076 }
2077 }
2078 }
2079 return $cssFiles;
2080 }
2081
2082 /**
2083 * Create link (inline=0) or style (inline=1) tag
2084 *
2085 * @param array $properties
2086 * @param string $file
2087 * @return string
2088 */
2089 private function createCssTag(array $properties, string $file): string
2090 {
2091 if ($properties['inline'] && @is_file($file)) {
2092 $tag = $this->createInlineCssTagFromFile($file, $properties);
2093 } else {
2094 $href = $this->getStreamlinedFileName($file);
2095 $tag = '<link rel="' . htmlspecialchars($properties['rel'])
2096 . '" type="text/css" href="' . htmlspecialchars($href)
2097 . '" media="' . htmlspecialchars($properties['media']) . '"'
2098 . ($properties['title'] ? ' title="' . htmlspecialchars($properties['title']) . '"' : '')
2099 . $this->endingSlash . '>';
2100 }
2101 if ($properties['allWrap']) {
2102 $wrapArr = explode($properties['splitChar'] ?: '|', $properties['allWrap'], 2);
2103 $tag = $wrapArr[0] . $tag . $wrapArr[1];
2104 }
2105 $tag .= LF;
2106
2107 return $tag;
2108 }
2109
2110 /**
2111 * Render inline CSS
2112 *
2113 * @return string
2114 */
2115 protected function renderCssInline()
2116 {
2117 $cssInline = '';
2118 if (!empty($this->cssInline)) {
2119 foreach ($this->cssInline as $name => $properties) {
2120 $cssCode = '/*' . htmlspecialchars($name) . '*/' . LF . $properties['code'] . LF;
2121 if ($properties['forceOnTop']) {
2122 $cssInline = $cssCode . $cssInline;
2123 } else {
2124 $cssInline .= $cssCode;
2125 }
2126 }
2127 $cssInline = $this->inlineCssWrap[0] . $cssInline . $this->inlineCssWrap[1];
2128 }
2129 return $cssInline;
2130 }
2131
2132 /**
2133 * Render JavaScipt libraries
2134 *
2135 * @return array<string> jsLibs and jsFooterLibs strings
2136 */
2137 protected function renderAdditionalJavaScriptLibraries()
2138 {
2139 $jsLibs = '';
2140 $jsFooterLibs = '';
2141 if (!empty($this->jsLibs)) {
2142 foreach ($this->jsLibs as $properties) {
2143 $properties['file'] = $this->getStreamlinedFileName($properties['file']);
2144 $async = $properties['async'] ? ' async="async"' : '';
2145 $defer = $properties['defer'] ? ' defer="defer"' : '';
2146 $integrity = $properties['integrity'] ? ' integrity="' . htmlspecialchars($properties['integrity']) . '"' : '';
2147 $crossorigin = $properties['crossorigin'] ? ' crossorigin="' . htmlspecialchars($properties['crossorigin']) . '"' : '';
2148 $tag = '<script src="' . htmlspecialchars($properties['file']) . '" type="' . htmlspecialchars($properties['type']) . '"' . $async . $defer . $integrity . $crossorigin . '></script>';
2149 if ($properties['allWrap']) {
2150 $wrapArr = explode($properties['splitChar'] ?: '|', $properties['allWrap'], 2);
2151 $tag = $wrapArr[0] . $tag . $wrapArr[1];
2152 }
2153 $tag .= LF;
2154 if ($properties['forceOnTop']) {
2155 if ($properties['section'] === self::PART_HEADER) {
2156 $jsLibs = $tag . $jsLibs;
2157 } else {
2158 $jsFooterLibs = $tag . $jsFooterLibs;
2159 }
2160 } else {
2161 if ($properties['section'] === self::PART_HEADER) {
2162 $jsLibs .= $tag;
2163 } else {
2164 $jsFooterLibs .= $tag;
2165 }
2166 }
2167 }
2168 }
2169 if ($this->moveJsFromHeaderToFooter) {
2170 $jsFooterLibs = $jsLibs . LF . $jsFooterLibs;
2171 $jsLibs = '';
2172 }
2173 return [$jsLibs, $jsFooterLibs];
2174 }
2175
2176 /**
2177 * Render JavaScript files
2178 *
2179 * @return array<string> jsFiles and jsFooterFiles strings
2180 */
2181 protected function renderJavaScriptFiles()
2182 {
2183 $jsFiles = '';
2184 $jsFooterFiles = '';
2185 if (!empty($this->jsFiles)) {
2186 foreach ($this->jsFiles as $file => $properties) {
2187 $file = $this->getStreamlinedFileName($file);
2188 $async = $properties['async'] ? ' async="async"' : '';
2189 $defer = $properties['defer'] ? ' defer="defer"' : '';
2190 $integrity = $properties['integrity'] ? ' integrity="' . htmlspecialchars($properties['integrity']) . '"' : '';
2191 $crossorigin = $properties['crossorigin'] ? ' crossorigin="' . htmlspecialchars($properties['crossorigin']) . '"' : '';
2192 $tag = '<script src="' . htmlspecialchars($file) . '" type="' . htmlspecialchars($properties['type']) . '"' . $async . $defer . $integrity . $crossorigin . '></script>';
2193 if ($properties['allWrap']) {
2194 $wrapArr = explode($properties['splitChar'] ?: '|', $properties['allWrap'], 2);
2195 $tag = $wrapArr[0] . $tag . $wrapArr[1];
2196 }
2197 $tag .= LF;
2198 if ($properties['forceOnTop']) {
2199 if ($properties['section'] === self::PART_HEADER) {
2200 $jsFiles = $tag . $jsFiles;
2201 } else {
2202 $jsFooterFiles = $tag . $jsFooterFiles;
2203 }
2204 } else {
2205 if ($properties['section'] === self::PART_HEADER) {
2206 $jsFiles .= $tag;
2207 } else {
2208 $jsFooterFiles .= $tag;
2209 }
2210 }
2211 }
2212 }
2213 if ($this->moveJsFromHeaderToFooter) {
2214 $jsFooterFiles = $jsFiles . $jsFooterFiles;
2215 $jsFiles = '';
2216 }
2217 return [$jsFiles, $jsFooterFiles];
2218 }
2219
2220 /**
2221 * Render inline JavaScript
2222 *
2223 * @return array<string> jsInline and jsFooterInline string
2224 */
2225 protected function renderInlineJavaScript()
2226 {
2227 $jsInline = '';
2228 $jsFooterInline = '';
2229 if (!empty($this->jsInline)) {
2230 foreach ($this->jsInline as $name => $properties) {
2231 $jsCode = '/*' . htmlspecialchars($name) . '*/' . LF . $properties['code'] . LF;
2232 if ($properties['forceOnTop']) {
2233 if ($properties['section'] === self::PART_HEADER) {
2234 $jsInline = $jsCode . $jsInline;
2235 } else {
2236 $jsFooterInline = $jsCode . $jsFooterInline;
2237 }
2238 } else {
2239 if ($properties['section'] === self::PART_HEADER) {
2240 $jsInline .= $jsCode;
2241 } else {
2242 $jsFooterInline .= $jsCode;
2243 }
2244 }
2245 }
2246 }
2247 if ($jsInline) {
2248 $jsInline = $this->inlineJavascriptWrap[0] . $jsInline . $this->inlineJavascriptWrap[1];
2249 }
2250 if ($jsFooterInline) {
2251 $jsFooterInline = $this->inlineJavascriptWrap[0] . $jsFooterInline . $this->inlineJavascriptWrap[1];
2252 }
2253 if ($this->moveJsFromHeaderToFooter) {
2254 $jsFooterInline = $jsInline . $jsFooterInline;
2255 $jsInline = '';
2256 }
2257 return [$jsInline, $jsFooterInline];
2258 }
2259
2260 /**
2261 * Include language file for inline usage
2262 *
2263 * @param string $fileRef
2264 * @param string $selectionPrefix
2265 * @param string $stripFromSelectionName
2266 * @throws \RuntimeException
2267 */
2268 protected function includeLanguageFileForInline($fileRef, $selectionPrefix = '', $stripFromSelectionName = '')
2269 {
2270 if (!isset($this->lang) || !isset($this->charSet)) {
2271 throw new \RuntimeException('Language and character encoding are not set.', 1284906026);
2272 }
2273 $labelsFromFile = [];
2274 $allLabels = $this->readLLfile($fileRef);
2275 if ($allLabels !== false) {
2276 // Merge language specific translations:
2277 if ($this->lang !== 'default' && isset($allLabels[$this->lang])) {
2278 $labels = array_merge($allLabels['default'], $allLabels[$this->lang]);
2279 } else {
2280 $labels = $allLabels['default'];
2281 }
2282 // Iterate through all locallang labels:
2283 foreach ($labels as $label => $value) {
2284 // If $selectionPrefix is set, only respect labels that start with $selectionPrefix
2285 if ($selectionPrefix === '' || strpos($label, $selectionPrefix) === 0) {
2286 // Remove substring $stripFromSelectionName from label
2287 $label = str_replace($stripFromSelectionName, '', $label);
2288 $labelsFromFile[$label] = $value;
2289 }
2290 }
2291 $this->inlineLanguageLabels = array_merge($this->inlineLanguageLabels, $labelsFromFile);
2292 }
2293 }
2294
2295 /**
2296 * Reads a locallang file.
2297 *
2298 * @param string $fileRef Reference to a relative filename to include.
2299 * @return array Returns the $LOCAL_LANG array found in the file. If no array found, returns empty array.
2300 */
2301 protected function readLLfile($fileRef)
2302 {
2303 /** @var LocalizationFactory $languageFactory */
2304 $languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class);
2305
2306 if ($this->lang !== 'default') {
2307 $languages = array_reverse($this->languageDependencies);
2308 // At least we need to have English
2309 if (empty($languages)) {
2310 $languages[] = 'default';
2311 }
2312 } else {
2313 $languages = ['default'];
2314 }
2315
2316 $localLanguage = [];
2317 foreach ($languages as $language) {
2318 $tempLL = $languageFactory->getParsedData($fileRef, $language);
2319
2320 $localLanguage['default'] = $tempLL['default'];
2321 if (!isset($localLanguage[$this->lang])) {
2322 $localLanguage[$this->lang] = $localLanguage['default'];
2323 }
2324 if ($this->lang !== 'default' && isset($tempLL[$language])) {
2325 // Merge current language labels onto labels from previous language
2326 // This way we have a labels with fall back applied
2327 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($localLanguage[$this->lang], $tempLL[$language], true, false);
2328 }
2329 }
2330
2331 return $localLanguage;
2332 }
2333
2334 /*****************************************************/
2335 /* */
2336 /* Tools */
2337 /* */
2338 /*****************************************************/
2339 /**
2340 * Concatenate files into one file
2341 * registered handler
2342 */
2343 protected function doConcatenate()
2344 {
2345 $this->doConcatenateCss();
2346 $this->doConcatenateJavaScript();
2347 }
2348
2349 /**
2350 * Concatenate JavaScript files according to the configuration.
2351 */
2352 protected function doConcatenateJavaScript()
2353 {
2354 if ($this->concatenateJavascript) {
2355 if (!empty($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['jsConcatenateHandler'])) {
2356 // use external concatenation routine
2357 $params = [
2358 'jsLibs' => &$this->jsLibs,
2359 'jsFiles' => &$this->jsFiles,
2360 'jsFooterFiles' => &$this->jsFooterFiles,
2361 'headerData' => &$this->headerData,
2362 'footerData' => &$this->footerData
2363 ];
2364 GeneralUtility::callUserFunction($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['jsConcatenateHandler'], $params, $this);
2365 } else {
2366 $this->jsLibs = $this->getCompressor()->concatenateJsFiles($this->jsLibs);
2367 $this->jsFiles = $this->getCompressor()->concatenateJsFiles($this->jsFiles);
2368 $this->jsFooterFiles = $this->getCompressor()->concatenateJsFiles($this->jsFooterFiles);
2369 }
2370 }
2371 }
2372
2373 /**
2374 * Concatenate CSS files according to configuration.
2375 */
2376 protected function doConcatenateCss()
2377 {
2378 if ($this->concatenateCss) {
2379 if (!empty($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['cssConcatenateHandler'])) {
2380 // use external concatenation routine
2381 $params = [
2382 'cssFiles' => &$this->cssFiles,
2383 'cssLibs' => &$this->cssLibs,
2384 'headerData' => &$this->headerData,
2385 'footerData' => &$this->footerData
2386 ];
2387 GeneralUtility::callUserFunction($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['cssConcatenateHandler'], $params, $this);
2388 } else {
2389 $cssOptions = [];
2390 if (TYPO3_MODE === 'BE') {
2391 $cssOptions = ['baseDirectories' => GeneralUtility::makeInstance(DocumentTemplate::class)->getSkinStylesheetDirectories()];
2392 }
2393 $this->cssLibs = $this->getCompressor()->concatenateCssFiles($this->cssLibs, $cssOptions);
2394 $this->cssFiles = $this->getCompressor()->concatenateCssFiles($this->cssFiles, $cssOptions);
2395 }
2396 }
2397 }
2398
2399 /**
2400 * Compresses inline code
2401 */
2402 protected function doCompress()
2403 {
2404 $this->doCompressJavaScript();
2405 $this->doCompressCss();
2406 }
2407
2408 /**
2409 * Compresses CSS according to configuration.
2410 */
2411 protected function doCompressCss()
2412 {
2413 if ($this->compressCss) {
2414 if (!empty($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['cssCompressHandler'])) {
2415 // Use external compression routine
2416 $params = [
2417 'cssInline' => &$this->cssInline,
2418 'cssFiles' => &$this->cssFiles,
2419 'cssLibs' => &$this->cssLibs,
2420 'headerData' => &$this->headerData,
2421 'footerData' => &$this->footerData
2422 ];
2423 GeneralUtility::callUserFunction($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['cssCompressHandler'], $params, $this);
2424 } else {
2425 $this->cssLibs = $this->getCompressor()->compressCssFiles($this->cssLibs);
2426 $this->cssFiles = $this->getCompressor()->compressCssFiles($this->cssFiles);
2427 }
2428 }
2429 }
2430
2431 /**
2432 * Compresses JavaScript according to configuration.
2433 */
2434 protected function doCompressJavaScript()
2435 {
2436 if ($this->compressJavascript) {
2437 if (!empty($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['jsCompressHandler'])) {
2438 // Use external compression routine
2439 $params = [
2440 'jsInline' => &$this->jsInline,
2441 'jsFooterInline' => &$this->jsFooterInline,
2442 'jsLibs' => &$this->jsLibs,
2443 'jsFiles' => &$this->jsFiles,
2444 'jsFooterFiles' => &$this->jsFooterFiles,
2445 'headerData' => &$this->headerData,
2446 'footerData' => &$this->footerData
2447 ];
2448 GeneralUtility::callUserFunction($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['jsCompressHandler'], $params, $this);
2449 } else {
2450 // Traverse the arrays, compress files
2451 if (!empty($this->jsInline)) {
2452 foreach ($this->jsInline as $name => $properties) {
2453 if ($properties['compress']) {
2454 $error = '';
2455 $this->jsInline[$name]['code'] = GeneralUtility::minifyJavaScript($properties['code'], $error);
2456 if ($error) {
2457 $this->compressError .= 'Error with minify JS Inline Block "' . $name . '": ' . $error . LF;
2458 }
2459 }
2460 }
2461 }
2462 $this->jsLibs = $this->getCompressor()->compressJsFiles($this->jsLibs);
2463 $this->jsFiles = $this->getCompressor()->compressJsFiles($this->jsFiles);
2464 $this->jsFooterFiles = $this->getCompressor()->compressJsFiles($this->jsFooterFiles);
2465 }
2466 }
2467 }
2468
2469 /**
2470 * Returns instance of \TYPO3\CMS\Core\Resource\ResourceCompressor
2471 *
2472 * @return \TYPO3\CMS\Core\Resource\ResourceCompressor
2473 */
2474 protected function getCompressor()
2475 {
2476 if ($this->compressor === null) {
2477 $this->compressor = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ResourceCompressor::class);
2478 }
2479 return $this->compressor;
2480 }
2481
2482 /**
2483 * Processes a Javascript file dependent on the current context
2484 *
2485 * Adds the version number for Frontend, compresses the file for Backend
2486 *
2487 * @param string $filename Filename
2488 * @return string New filename
2489 */
2490 protected function processJsFile($filename)
2491 {
2492 $filename = $this->getStreamlinedFileName($filename, false);
2493 if ($this->compressJavascript) {
2494 $filename = $this->getCompressor()->compressJsFile($filename);
2495 } elseif (TYPO3_MODE === 'FE') {
2496 $filename = GeneralUtility::createVersionNumberedFilename($filename);
2497 }
2498 return $this->getAbsoluteWebPath($filename);
2499 }
2500
2501 /**
2502 * This function acts as a wrapper to allow relative and paths starting with EXT: to be dealt with
2503 * in this very case to always return the absolute web path to be included directly before output.
2504 *
2505 * This is mainly added so the EXT: syntax can be resolved for PageRenderer in one central place,
2506 * and hopefully removed in the future by one standard API call.
2507 *
2508 * @param string $file the filename to process
2509 * @param bool $prepareForOutput whether the file should be prepared as version numbered file and prefixed as absolute webpath
2510 * @return string
2511 * @internal
2512 */
2513 protected function getStreamlinedFileName($file, $prepareForOutput = true)
2514 {
2515 if (strpos($file, 'EXT:') === 0) {
2516 $file = GeneralUtility::getFileAbsFileName($file);
2517 // as the path is now absolute, make it "relative" to the current script to stay compatible
2518 $file = PathUtility::getRelativePathTo($file);
2519 $file = rtrim($file, '/');
2520 } else {
2521 $file = GeneralUtility::resolveBackPath($file);
2522 }
2523 if ($prepareForOutput) {
2524 $file = GeneralUtility::createVersionNumberedFilename($file);
2525 $file = $this->getAbsoluteWebPath($file);
2526 }
2527 return $file;
2528 }
2529
2530 /**
2531 * Gets absolute web path of filename for backend disposal.
2532 * Resolving the absolute path in the frontend with conflict with
2533 * applying config.absRefPrefix in frontend rendering process.
2534 *
2535 * @param string $file
2536 * @return string
2537 * @see TypoScriptFrontendController::setAbsRefPrefix()
2538 */
2539 protected function getAbsoluteWebPath(string $file): string
2540 {
2541 if (TYPO3_MODE === 'FE') {
2542 return $file;
2543 }
2544 return PathUtility::getAbsoluteWebPath($file);
2545 }
2546
2547 /**
2548 * Returns global frontend controller
2549 *
2550 * @return TypoScriptFrontendController
2551 */
2552 protected function getTypoScriptFrontendController()
2553 {
2554 return $GLOBALS['TSFE'];
2555 }
2556
2557 /*****************************************************/
2558 /* */
2559 /* Hooks */
2560 /* */
2561 /*****************************************************/
2562 /**
2563 * Execute PreRenderHook for possible manipulation
2564 */
2565 protected function executePreRenderHook()
2566 {
2567 $hooks = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-preProcess'] ?? false;
2568 if (!$hooks) {
2569 return;
2570 }
2571 $params = [
2572 'jsLibs' => &$this->jsLibs,
2573 'jsFooterLibs' => &$this->jsFooterLibs,
2574 'jsFiles' => &$this->jsFiles,
2575 'jsFooterFiles' => &$this->jsFooterFiles,
2576 'cssLibs' => &$this->cssLibs,
2577 'cssFiles' => &$this->cssFiles,
2578 'headerData' => &$this->headerData,
2579 'footerData' => &$this->footerData,
2580 'jsInline' => &$this->jsInline,
2581 'jsFooterInline' => &$this->jsFooterInline,
2582 'cssInline' => &$this->cssInline
2583 ];
2584 foreach ($hooks as $hook) {
2585 GeneralUtility::callUserFunction($hook, $params, $this);
2586 }
2587 }
2588
2589 /**
2590 * PostTransform for possible manipulation of concatenated and compressed files
2591 */
2592 protected function executeRenderPostTransformHook()
2593 {
2594 $hooks = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-postTransform'] ?? false;
2595 if (!$hooks) {
2596 return;
2597 }
2598 $params = [
2599 'jsLibs' => &$this->jsLibs,
2600 'jsFooterLibs' => &$this->jsFooterLibs,
2601 'jsFiles' => &$this->jsFiles,
2602 'jsFooterFiles' => &$this->jsFooterFiles,
2603 'cssLibs' => &$this->cssLibs,
2604 'cssFiles' => &$this->cssFiles,
2605 'headerData' => &$this->headerData,
2606 'footerData' => &$this->footerData,
2607 'jsInline' => &$this->jsInline,
2608 'jsFooterInline' => &$this->jsFooterInline,
2609 'cssInline' => &$this->cssInline
2610 ];
2611 foreach ($hooks as $hook) {
2612 GeneralUtility::callUserFunction($hook, $params, $this);
2613 }
2614 }
2615
2616 /**
2617 * Execute postRenderHook for possible manipulation
2618 *
2619 * @param string $jsLibs
2620 * @param string $jsFiles
2621 * @param string $jsFooterFiles
2622 * @param string $cssLibs
2623 * @param string $cssFiles
2624 * @param string $jsInline
2625 * @param string $cssInline
2626 * @param string $jsFooterInline
2627 * @param string $jsFooterLibs
2628 */
2629 protected function executePostRenderHook(&$jsLibs, &$jsFiles, &$jsFooterFiles, &$cssLibs, &$cssFiles, &$jsInline, &$cssInline, &$jsFooterInline, &$jsFooterLibs)
2630 {
2631 $hooks = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-postProcess'] ?? false;
2632 if (!$hooks) {
2633 return;
2634 }
2635 $params = [
2636 'jsLibs' => &$jsLibs,
2637 'jsFiles' => &$jsFiles,
2638 'jsFooterFiles' => &$jsFooterFiles,
2639 'cssLibs' => &$cssLibs,
2640 'cssFiles' => &$cssFiles,
2641 'headerData' => &$this->headerData,
2642 'footerData' => &$this->footerData,
2643 'jsInline' => &$jsInline,
2644 'cssInline' => &$cssInline,
2645 'xmlPrologAndDocType' => &$this->xmlPrologAndDocType,
2646 'htmlTag' => &$this->htmlTag,
2647 'headTag' => &$this->headTag,
2648 'charSet' => &$this->charSet,
2649 'metaCharsetTag' => &$this->metaCharsetTag,
2650 'shortcutTag' => &$this->shortcutTag,
2651 'inlineComments' => &$this->inlineComments,
2652 'baseUrl' => &$this->baseUrl,
2653 'baseUrlTag' => &$this->baseUrlTag,
2654 'favIcon' => &$this->favIcon,
2655 'iconMimeType' => &$this->iconMimeType,
2656 'titleTag' => &$this->titleTag,
2657 'title' => &$this->title,
2658 'metaTags' => &$this->metaTags,
2659 'jsFooterInline' => &$jsFooterInline,
2660 'jsFooterLibs' => &$jsFooterLibs,
2661 'bodyContent' => &$this->bodyContent
2662 ];
2663 foreach ($hooks as $hook) {
2664 GeneralUtility::callUserFunction($hook, $params, $this);
2665 }
2666 }
2667
2668 /**
2669 * Creates an CSS inline tag
2670 *
2671 * @param string $file the filename to process
2672 * @param array $properties
2673 * @return string
2674 */
2675 protected function createInlineCssTagFromFile(string $file, array $properties): string
2676 {
2677 $cssInline = file_get_contents($file);
2678
2679 return '<style type="text/css"'
2680 . ' media="' . htmlspecialchars($properties['media']) . '"'
2681 . ($properties['title'] ? ' title="' . htmlspecialchars($properties['title']) . '"' : '')
2682 . '>' . LF
2683 . '/*<![CDATA[*/' . LF . '<!-- ' . LF
2684 . $cssInline
2685 . '-->' . LF . '/*]]>*/' . LF . '</style>' . LF;
2686 }
2687 }