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