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