-
Notifications
You must be signed in to change notification settings - Fork 821
/
Requirements_Backend.php
1546 lines (1416 loc) · 51.6 KB
/
Requirements_Backend.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace SilverStripe\View;
use Exception;
use InvalidArgumentException;
use SilverStripe\Assets\File;
use SilverStripe\Assets\Storage\GeneratedAssetHandler;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Manifest\ModuleResourceLoader;
use SilverStripe\Core\Manifest\ResourceURLGenerator;
use SilverStripe\Core\Path;
use SilverStripe\Dev\Debug;
use SilverStripe\i18n\i18n;
use SilverStripe\ORM\FieldType\DBField;
use Symfony\Component\Filesystem\Path as FilesystemPath;
class Requirements_Backend
{
use Injectable;
/**
* Whether to add caching query params to the requests for file-based requirements.
* Eg: themes/myTheme/js/main.js?m=123456789. The parameter is a timestamp generated by
* filemtime. This has the benefit of allowing the browser to cache the URL infinitely,
* while automatically busting this cache every time the file is changed.
*
* @var bool
*/
protected $suffixRequirements = true;
/**
* Whether to combine CSS and JavaScript files
*
* @var bool|null
*/
protected $combinedFilesEnabled = null;
/**
* Determine if files should be combined automatically on dev mode.
*
* By default combined files will not be combined except in test or
* live environments. Turning this on will allow for pre-combining of files in development mode.
*
* @config
* @var bool
*/
private static $combine_in_dev = false;
/**
* Determine if relative urls in the combined files should be converted to absolute.
*
* By default combined files will be parsed for relative URLs to image/font assets and those
* URLs will be changed to absolute to accomodate the fact that the combined css is placed
* in a totally different folder than the source css files.
*
* Turn this off if you see some unexpected results.
*
* @config
* @var bool
*/
private static $resolve_relative_css_refs = false;
/**
* Paths to all required JavaScript files relative to docroot
*
* @var array
*/
protected $javascript = [];
/**
* Map of included scripts to array of contained files.
* To be used alongside front-end combination mechanisms.
*
* @var array Map of providing filepath => array(provided filepaths)
*/
protected $providedJavascript = [];
/**
* Paths to all required CSS files relative to the docroot.
*
* @var array
*/
protected $css = [];
/**
* All custom javascript code that is inserted into the page's HTML
*
* @var array
*/
protected $customScript = [];
/**
* Maintains attributes for each entry in the `$customScript` array, indexed by either a
* unique identifier (uniquenessID) or the script's array position.
*
* @var array
*/
private array $customScriptAttributes = [];
/**
* All custom CSS rules which are inserted directly at the bottom of the HTML `<head>` tag
*
* @var array
*/
protected $customCSS = [];
/**
* All custom HTML markup which is added before the closing `<head>` tag, e.g. additional
* metatags.
*
* @var array
*/
protected $customHeadTags = [];
/**
* Remembers the file paths or uniquenessIDs of all Requirements cleared through
* {@link clear()}, so that they can be restored later.
*
* @var array
*/
protected $disabled = [];
/**
* The file paths (relative to docroot) or uniquenessIDs of any included requirements which
* should be blocked when executing {@link inlcudeInHTML()}. This is useful, for example,
* to block scripts included by a superclass without having to override entire functions and
* duplicate a lot of code.
*
* Use {@link unblock()} or {@link unblock_all()} to revert changes.
*
* @var array
*/
protected $blocked = [];
/**
* A list of combined files registered via {@link combine_files()}. Keys are the output file
* names, values are lists of input files.
*
* @var array
*/
protected $combinedFiles = [];
/**
* Whether or not file headers should be written when combining files
*
* @var boolean
*/
protected $writeHeaderComment = true;
/**
* Where to save combined files. By default they're placed in assets/_combinedfiles, however
* this may be an issue depending on your setup, especially for CSS files which often contain
* relative paths.
*
* @var string
*/
protected $combinedFilesFolder = null;
/**
* Put all JavaScript includes at the bottom of the template before the closing `<body>` tag,
* rather than the default behaviour of placing them at the end of the `<head>` tag. This means
* script downloads won't block other HTTP requests, which can be a performance improvement.
*
* @var bool
*/
public $writeJavascriptToBody = true;
/**
* Force the JavaScript to the bottom of the page, even if there's a script tag in the body already
*
* @var boolean
*/
protected $forceJSToBottom = false;
/**
* Configures the default prefix for combined files.
*
* This defaults to `_combinedfiles`, and is the folder within the configured asset backend that
* combined files will be stored in. If using a backend shared with other systems, it is usually
* necessary to distinguish combined files from other assets.
*
* @config
* @var string
*/
private static $default_combined_files_folder = '_combinedfiles';
/**
* Flag to include the hash in the querystring instead of the filename for combined files.
*
* By default the `<hash>` of the source files is appended to the end of the combined file
* (prior to the file extension). If combined files are versioned in source control or running
* in a distributed environment (such as one where the newest version of a file may not always be
* immediately available) then it may sometimes be necessary to disable this. When this is set to true,
* the hash will instead be appended via a querystring parameter to enable cache busting, but not in
* the filename itself. I.e. `assets/_combinedfiles/name.js?m=<hash>`
*
* @config
* @var bool
*/
private static $combine_hash_querystring = false;
/**
* @var GeneratedAssetHandler
*/
protected $assetHandler = null;
/**
* Gets the backend storage for generated files
*
* @return GeneratedAssetHandler
*/
public function getAssetHandler()
{
return $this->assetHandler;
}
/**
* Set a new asset handler for this backend
*
* @param GeneratedAssetHandler $handler
*/
public function setAssetHandler(GeneratedAssetHandler $handler)
{
$this->assetHandler = $handler;
}
/**
* Enable or disable the combination of CSS and JavaScript files
*
* @param bool $enable
*/
public function setCombinedFilesEnabled($enable)
{
$this->combinedFilesEnabled = (bool)$enable;
}
/**
* Check if header comments are written
*
* @return bool
*/
public function getWriteHeaderComment()
{
return $this->writeHeaderComment;
}
/**
* Flag whether header comments should be written for each combined file
*
* @param bool $write
* @return $this
*/
public function setWriteHeaderComment($write)
{
$this->writeHeaderComment = $write;
return $this;
}
/**
* Set the folder to save combined files in. By default they're placed in _combinedfiles,
* however this may be an issue depending on your setup, especially for CSS files which often
* contain relative paths.
*
* This must not include any 'assets' prefix
*
* @param string $folder
*/
public function setCombinedFilesFolder($folder)
{
$this->combinedFilesFolder = $folder;
}
/**
* Retrieve the combined files folder prefix
*
* @return string
*/
public function getCombinedFilesFolder()
{
if ($this->combinedFilesFolder) {
return $this->combinedFilesFolder;
}
return Config::inst()->get(__CLASS__, 'default_combined_files_folder');
}
/**
* Set whether to add caching query params to the requests for file-based requirements.
* Eg: themes/myTheme/js/main.js?m=123456789. The parameter is a timestamp generated by
* filemtime. This has the benefit of allowing the browser to cache the URL infinitely,
* while automatically busting this cache every time the file is changed.
*
* @param bool $var
*/
public function setSuffixRequirements($var)
{
$this->suffixRequirements = $var;
}
/**
* Check whether we want to suffix requirements
*
* @return bool
*/
public function getSuffixRequirements()
{
return $this->suffixRequirements;
}
/**
* Set whether you want to write the JS to the body of the page rather than at the end of the
* head tag.
*
* @param bool $var
* @return $this
*/
public function setWriteJavascriptToBody($var)
{
$this->writeJavascriptToBody = $var;
return $this;
}
/**
* Check whether you want to write the JS to the body of the page rather than at the end of the
* head tag.
*
* @return bool
*/
public function getWriteJavascriptToBody()
{
return $this->writeJavascriptToBody;
}
/**
* Forces the JavaScript requirements to the end of the body, right before the closing tag
*
* @param bool $var
* @return $this
*/
public function setForceJSToBottom($var)
{
$this->forceJSToBottom = $var;
return $this;
}
/**
* Check if the JavaScript requirements are written to the end of the body, right before the closing tag
*
* @return bool
*/
public function getForceJSToBottom()
{
return $this->forceJSToBottom;
}
/**
* Register the given JavaScript file as required.
*
* @param string $file Either relative to docroot or in the form "vendor/package:resource"
* @param array $options List of options. Available options include:
* - 'provides' : List of scripts files included in this file
* - 'async' : Boolean value to set async attribute to script tag
* - 'defer' : Boolean value to set defer attribute to script tag
* - 'type' : Override script type= value.
* - 'integrity' : SubResource Integrity hash
* - 'crossorigin' : Cross-origin policy for the resource
*/
public function javascript($file, $options = [])
{
$file = ModuleResourceLoader::singleton()->resolvePath($file);
// Get type
$type = null;
if (isset($this->javascript[$file]['type'])) {
$type = $this->javascript[$file]['type'];
}
if (isset($options['type'])) {
$type = $options['type'];
}
// make sure that async/defer is set if it is set once even if file is included multiple times
$async = (
isset($options['async']) && $options['async']
|| (
isset($this->javascript[$file])
&& isset($this->javascript[$file]['async'])
&& $this->javascript[$file]['async']
)
);
$defer = (
isset($options['defer']) && $options['defer']
|| (
isset($this->javascript[$file])
&& isset($this->javascript[$file]['defer'])
&& $this->javascript[$file]['defer']
)
);
$integrity = $options['integrity'] ?? null;
$crossorigin = $options['crossorigin'] ?? null;
$this->javascript[$file] = [
'async' => $async,
'defer' => $defer,
'type' => $type,
'integrity' => $integrity,
'crossorigin' => $crossorigin,
];
// Record scripts included in this file
if (isset($options['provides'])) {
$this->providedJavascript[$file] = array_values($options['provides'] ?? []);
}
}
/**
* Remove a javascript requirement
*
* @param string $file
*/
protected function unsetJavascript($file)
{
unset($this->javascript[$file]);
}
/**
* Gets all scripts that are already provided by prior scripts.
* This follows these rules:
* - Files will not be considered provided if they are separately
* included prior to the providing file.
* - Providing files can be blocked, and don't provide anything
* - Provided files can't be blocked (you need to block the provider)
* - If a combined file includes files that are provided by prior
* scripts, then these should be excluded from the combined file.
* - If a combined file includes files that are provided by later
* scripts, then these files should be included in the combined
* file, but we can't block the later script either (possible double
* up of file).
*
* @return array Array of provided files (map of $path => $path)
*/
public function getProvidedScripts()
{
$providedScripts = [];
$includedScripts = [];
foreach ($this->javascript as $script => $options) {
// Ignore scripts that are explicitly blocked
if (isset($this->blocked[$script])) {
continue;
}
// At this point, the file is included.
// This might also be combined at this point, potentially.
$includedScripts[$script] = true;
// Record any files this provides, EXCEPT those already included by now
if (isset($this->providedJavascript[$script])) {
foreach ($this->providedJavascript[$script] as $provided) {
if (!isset($includedScripts[$provided])) {
$providedScripts[$provided] = $provided;
}
}
}
}
return $providedScripts;
}
/**
* Returns an array of required JavaScript, excluding blocked
* and duplicates of provided files.
*
* @return array
*/
public function getJavascript()
{
return array_diff_key(
$this->javascript ?? [],
$this->getBlocked(),
$this->getProvidedScripts()
);
}
/**
* Gets all javascript, including blocked files. Unwraps the array into a non-associative list
*
* @return array Indexed array of javascript files
*/
protected function getAllJavascript()
{
return $this->javascript;
}
/**
* Register the given JavaScript code into the list of requirements
*
* @param string $script The script content as a string (without enclosing `<script>` tag)
* @param string $uniquenessID A unique ID that ensures a piece of code is only added once
*/
public function customScript($script, $uniquenessID = null)
{
if ($uniquenessID) {
if (isset($this->customScriptAttributes[$uniquenessID])) {
unset($this->customScriptAttributes[$uniquenessID]);
}
$this->customScript[$uniquenessID] = $script;
} else {
$this->customScript[] = $script;
}
}
/**
* Register the given Javascript code into the list of requirements with optional tag
* attributes.
*
* @param string $script The script content as a string (without enclosing `<script>` tag)
* @param array $options List of options. Available options include:
* - 'type' : Specifies the type of script
* - 'crossorigin' : Cross-origin policy for the resource
* @param string|int $uniquenessID A unique ID that ensures a piece of code is only added once
*/
public function customScriptWithAttributes(string $script, array $attributes = [], string|int|null $uniquenessID = null)
{
$attrs = [];
foreach (['type', 'crossorigin'] as $attrKey) {
if (isset($attributes[$attrKey])) {
$attrs[$attrKey] = strtolower($attributes[$attrKey]);
}
}
if ($uniquenessID) {
$this->customScript[$uniquenessID] = $script;
$this->customScriptAttributes[$uniquenessID] = $attrs;
} else {
$this->customScript[] = $script;
$index = count($this->customScript) - 1;
$this->customScriptAttributes[$index] = $attrs;
}
}
/**
* Return all registered custom scripts
*
* @return array
*/
public function getCustomScripts()
{
return array_diff_key($this->customScript ?? [], $this->blocked);
}
/**
* Register the given CSS styles into the list of requirements
*
* @param string $script CSS selectors as a string (without enclosing `<style>` tag)
* @param string $uniquenessID A unique ID that ensures a piece of code is only added once
*/
public function customCSS($script, $uniquenessID = null)
{
if ($uniquenessID) {
$this->customCSS[$uniquenessID] = $script;
} else {
$this->customCSS[] = $script;
}
}
/**
* Return all registered custom CSS
*
* @return array
*/
public function getCustomCSS()
{
return array_diff_key($this->customCSS ?? [], $this->blocked);
}
/**
* Add the following custom HTML code to the `<head>` section of the page
*
* @param string $html Custom HTML code
* @param string $uniquenessID A unique ID that ensures a piece of code is only added once
*/
public function insertHeadTags($html, $uniquenessID = null)
{
if ($uniquenessID) {
$this->customHeadTags[$uniquenessID] = $html;
} else {
$this->customHeadTags[] = $html;
}
}
/**
* Return all custom head tags
*
* @return array
*/
public function getCustomHeadTags()
{
return array_diff_key($this->customHeadTags ?? [], $this->blocked);
}
/**
* Include the content of the given JavaScript file in the list of requirements. Dollar-sign
* variables will be interpolated with values from $vars similar to a .ss template.
*
* @param string $file The template file to load, relative to docroot
* @param string[] $vars The array of variables to interpolate.
* @param string $uniquenessID A unique ID that ensures a piece of code is only added once
*/
public function javascriptTemplate($file, $vars, $uniquenessID = null)
{
$file = ModuleResourceLoader::singleton()->resolvePath($file);
$absolutePath = Director::getAbsFile($file);
if (!file_exists($absolutePath ?? '')) {
throw new InvalidArgumentException("Javascript template file {$file} does not exist");
}
$script = file_get_contents($absolutePath ?? '');
$search = [];
$replace = [];
if ($vars) {
foreach ($vars as $k => $v) {
$search[] = '$' . $k;
$replace[] = str_replace("\\'", "'", Convert::raw2js($v) ?? '');
}
}
$script = str_replace($search ?? '', $replace ?? '', $script ?? '');
$this->customScript($script, $uniquenessID);
}
/**
* Register the given stylesheet into the list of requirements.
*
* @param string $file The CSS file to load, relative to site root
* @param string $media Comma-separated list of media types to use in the link tag
* (e.g. 'screen,projector')
* @param array $options List of options. Available options include:
* - 'integrity' : SubResource Integrity hash
* - 'crossorigin' : Cross-origin policy for the resource
*/
public function css($file, $media = null, $options = [])
{
$file = ModuleResourceLoader::singleton()->resolvePath($file);
$integrity = $options['integrity'] ?? null;
$crossorigin = $options['crossorigin'] ?? null;
$this->css[$file] = [
"media" => $media,
"integrity" => $integrity,
"crossorigin" => $crossorigin,
];
}
/**
* Remove a css requirement
*
* @param string $file
*/
protected function unsetCSS($file)
{
unset($this->css[$file]);
}
/**
* Get the list of registered CSS file requirements, excluding blocked files
*
* @return array Associative array of file to spec
*/
public function getCSS()
{
return array_diff_key($this->css ?? [], $this->blocked);
}
/**
* Gets all CSS files requirements, including blocked
*
* @return array Associative array of file to spec
*/
protected function getAllCSS()
{
return $this->css;
}
/**
* Gets the list of all blocked files
*
* @return array
*/
public function getBlocked()
{
return $this->blocked;
}
/**
* Clear either a single or all requirements
*
* Caution: Clearing single rules added via customCSS and customScript only works if you
* originally specified a $uniquenessID.
*
* @param string|int $fileOrID
*/
public function clear($fileOrID = null)
{
$types = [
'javascript',
'css',
'customScript',
'customCSS',
'customHeadTags',
'combinedFiles',
];
foreach ($types as $type) {
if ($fileOrID) {
if (isset($this->{$type}[$fileOrID])) {
$this->disabled[$type][$fileOrID] = $this->{$type}[$fileOrID];
unset($this->{$type}[$fileOrID]);
}
} else {
$this->disabled[$type] = $this->{$type};
$this->{$type} = [];
}
}
}
/**
* Restore requirements cleared by call to Requirements::clear
*/
public function restore()
{
$types = [
'javascript',
'css',
'customScript',
'customCSS',
'customHeadTags',
'combinedFiles',
];
foreach ($types as $type) {
$this->{$type} = $this->disabled[$type];
}
}
/**
* Block inclusion of a specific file
*
* The difference between this and {@link clear} is that the calling order does not matter;
* {@link clear} must be called after the initial registration, whereas {@link block} can be
* used in advance. This is useful, for example, to block scripts included by a superclass
* without having to override entire functions and duplicate a lot of code.
*
* Note that blocking should be used sparingly because it's hard to trace where an file is
* being blocked from.
*
* @param string|int $fileOrID Relative path from webroot, module resource reference or
* requirement API ID
*/
public function block($fileOrID)
{
if (is_string($fileOrID)) {
$fileOrID = ModuleResourceLoader::singleton()->resolvePath($fileOrID);
}
$this->blocked[$fileOrID] = $fileOrID;
}
/**
* Remove an item from the block list
*
* @param string|int $fileOrID
*/
public function unblock($fileOrID)
{
unset($this->blocked[$fileOrID]);
}
/**
* Removes all items from the block list
*/
public function unblockAll()
{
$this->blocked = [];
}
/**
* Update the given HTML content with the appropriate include tags for the registered
* requirements. Needs to receive a valid HTML/XHTML template in the $content parameter,
* including a head and body tag.
*
* @param string $content HTML content that has already been parsed from the $templateFile
* through {@link SSViewer}
* @return string HTML content augmented with the requirements tags
*/
public function includeInHTML($content)
{
// Skip if content isn't injectable, or there is nothing to inject
$tagsAvailable = preg_match('#</head\b#', $content ?? '');
$hasFiles = $this->css || $this->javascript || $this->customCSS || $this->customScript || $this->customHeadTags;
if (!$tagsAvailable || !$hasFiles) {
return $content;
}
$requirements = '';
$jsRequirements = '';
// Combine files - updates $this->javascript and $this->css
$this->processCombinedFiles();
// Script tags for js links
foreach ($this->getJavascript() as $file => $attributes) {
// Build html attributes
$htmlAttributes = [
'type' => isset($attributes['type']) ? $attributes['type'] : "application/javascript",
'src' => $this->pathForFile($file),
];
if (!empty($attributes['async'])) {
$htmlAttributes['async'] = 'async';
}
if (!empty($attributes['defer'])) {
$htmlAttributes['defer'] = 'defer';
}
if (!empty($attributes['integrity'])) {
$htmlAttributes['integrity'] = $attributes['integrity'];
}
if (!empty($attributes['crossorigin'])) {
$htmlAttributes['crossorigin'] = $attributes['crossorigin'];
}
$jsRequirements .= HTML::createTag('script', $htmlAttributes);
$jsRequirements .= "\n";
}
// Add all inline JavaScript *after* including external files they might rely on
foreach ($this->getCustomScripts() as $key => $script) {
// Build html attributes
$customHtmlAttributes = ['type' => 'application/javascript'];
if (isset($this->customScriptAttributes[$key])) {
foreach ($this->customScriptAttributes[$key] as $attrKey => $attrValue) {
$customHtmlAttributes[$attrKey] = $attrValue;
}
}
$jsRequirements .= HTML::createTag(
'script',
$customHtmlAttributes,
"//<![CDATA[\n{$script}\n//]]>"
);
$jsRequirements .= "\n";
}
// CSS file links
foreach ($this->getCSS() as $file => $params) {
$htmlAttributes = [
'rel' => 'stylesheet',
'type' => 'text/css',
'href' => $this->pathForFile($file),
];
if (!empty($params['media'])) {
$htmlAttributes['media'] = $params['media'];
}
if (!empty($params['integrity'])) {
$htmlAttributes['integrity'] = $params['integrity'];
}
if (!empty($params['crossorigin'])) {
$htmlAttributes['crossorigin'] = $params['crossorigin'];
}
$requirements .= HTML::createTag('link', $htmlAttributes);
$requirements .= "\n";
}
// Literal custom CSS content
foreach ($this->getCustomCSS() as $css) {
$requirements .= HTML::createTag('style', ['type' => 'text/css'], "\n{$css}\n");
$requirements .= "\n";
}
foreach ($this->getCustomHeadTags() as $customHeadTag) {
$requirements .= "{$customHeadTag}\n";
}
// Inject CSS into body
$content = $this->insertTagsIntoHead($requirements, $content);
// Inject scripts
if ($this->getForceJSToBottom()) {
$content = $this->insertScriptsAtBottom($jsRequirements, $content);
} elseif ($this->getWriteJavascriptToBody()) {
$content = $this->insertScriptsIntoBody($jsRequirements, $content);
} else {
$content = $this->insertTagsIntoHead($jsRequirements, $content);
}
return $content;
}
/**
* Given a block of HTML, insert the given scripts at the bottom before
* the closing `</body>` tag
*
* @param string $jsRequirements String containing one or more javascript `<script />` tags
* @param string $content HTML body
* @return string Merged HTML
*/
protected function insertScriptsAtBottom($jsRequirements, $content)
{
// Forcefully put the scripts at the bottom of the body instead of before the first
// script tag.
$content = preg_replace(
'/(<\/body[^>]*>)/i',
$this->escapeReplacement($jsRequirements) . '\\1',
$content ?? ''
);
return $content;
}
/**
* Given a block of HTML, insert the given scripts inside the `<body></body>`
*
* @param string $jsRequirements String containing one or more javascript `<script />` tags
* @param string $content HTML body
* @return string Merged HTML
*/
protected function insertScriptsIntoBody($jsRequirements, $content)
{
// If your template already has script tags in the body, then we try to put our script
// tags just before those. Otherwise, we put it at the bottom.
$bodyTagPosition = stripos($content ?? '', '<body');
$scriptTagPosition = stripos($content ?? '', '<script', $bodyTagPosition ?? 0);
$commentTags = [];
$canWriteToBody = ($scriptTagPosition !== false)
&&
// Check that the script tag is not inside a html comment tag
!(
preg_match('/.*(?|(<!--)|(-->))/U', $content ?? '', $commentTags, 0, $scriptTagPosition ?? 0)
&&
$commentTags[1] == '-->'
);
if ($canWriteToBody) {
// Insert content before existing script tags
$content = substr($content ?? '', 0, $scriptTagPosition)
. $jsRequirements
. substr($content ?? '', $scriptTagPosition ?? 0);
} else {
// Insert content at bottom of page otherwise
$content = $this->insertScriptsAtBottom($jsRequirements, $content);
}
return $content;
}
/**
* Given a block of HTML, insert the given code inside the `<head></head>` block
*
* @param string $jsRequirements String containing one or more html tags
* @param string $content HTML body
* @return string Merged HTML
*/
protected function insertTagsIntoHead($jsRequirements, $content)
{
$content = preg_replace(
'/(<\/head>)/i',
$this->escapeReplacement($jsRequirements) . '\\1',
$content ?? ''
);
return $content;
}
/**
* Safely escape a literal string for use in preg_replace replacement
*
* @param string $replacement
* @return string
*/
protected function escapeReplacement($replacement)
{
return addcslashes($replacement ?? '', '\\$');
}
/**
* Attach requirements inclusion to X-Include-JS and X-Include-CSS headers on the given
* HTTP Response
*
* @param HTTPResponse $response
*/
public function includeInResponse(HTTPResponse $response)
{
$this->processCombinedFiles();
$jsRequirements = [];
$cssRequirements = [];
foreach ($this->getJavascript() as $file => $attributes) {
$path = $this->pathForFile($file);
if ($path) {
$jsRequirements[] = str_replace(',', '%2C', $path ?? '');
}
}
if (count($jsRequirements ?? [])) {
$response->addHeader('X-Include-JS', implode(',', $jsRequirements));
}