1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LeKoala\DeferBackend; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use SilverStripe\View\HTML; |
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use SilverStripe\View\SSViewer; |
9
|
|
|
use SilverStripe\View\Requirements; |
10
|
|
|
use SilverStripe\View\ThemeResourceLoader; |
11
|
|
|
use SilverStripe\View\Requirements_Backend; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* A backend that defers everything by default |
15
|
|
|
* |
16
|
|
|
* Also insert custom head tags first because order may matter |
17
|
|
|
* |
18
|
|
|
* @link https://flaviocopes.com/javascript-async-defer/ |
19
|
|
|
*/ |
20
|
|
|
class DeferBackend extends Requirements_Backend |
21
|
|
|
{ |
22
|
|
|
// It's better to write to the head with defer |
23
|
|
|
public $writeJavascriptToBody = false; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @return $this |
27
|
|
|
*/ |
28
|
|
|
public static function getDeferBackend() |
29
|
|
|
{ |
30
|
|
|
$backend = Requirements::backend(); |
31
|
|
|
if (!$backend instanceof self) { |
32
|
|
|
throw new Exception("Requirements backend is currently of class " . get_class($backend)); |
33
|
|
|
} |
34
|
|
|
return $backend; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param Requirements_Backend $oldBackend defaults to current backend |
39
|
|
|
* @return $this |
40
|
|
|
*/ |
41
|
|
|
public static function replaceBackend(Requirements_Backend $oldBackend = null) |
42
|
|
|
{ |
43
|
|
|
if ($oldBackend === null) { |
44
|
|
|
$oldBackend = Requirements::backend(); |
45
|
|
|
} |
46
|
|
|
$deferBackend = new static; |
47
|
|
|
foreach ($oldBackend->getCSS() as $file => $opts) { |
48
|
|
|
$deferBackend->css($file, null, $opts); |
49
|
|
|
} |
50
|
|
|
foreach ($oldBackend->getJavascript() as $file => $opts) { |
51
|
|
|
$deferBackend->javascript($file, null, $opts); |
|
|
|
|
52
|
|
|
} |
53
|
|
|
foreach ($oldBackend->getCustomCSS() as $id => $script) { |
54
|
|
|
$deferBackend->customCSS($script, $id); |
55
|
|
|
} |
56
|
|
|
foreach ($oldBackend->getCustomScripts() as $id => $script) { |
57
|
|
|
$deferBackend->customScript($script, $id); |
58
|
|
|
} |
59
|
|
|
Requirements::set_backend($deferBackend); |
60
|
|
|
return $deferBackend; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Register the given JavaScript file as required. |
65
|
|
|
* |
66
|
|
|
* @param string $file Either relative to docroot or in the form "vendor/package:resource" |
67
|
|
|
* @param array $options List of options. Available options include: |
68
|
|
|
* - 'provides' : List of scripts files included in this file |
69
|
|
|
* - 'async' : Boolean value to set async attribute to script tag |
70
|
|
|
* - 'defer' : Boolean value to set defer attribute to script tag (true by default) |
71
|
|
|
* - 'type' : Override script type= value. |
72
|
|
|
* - 'integrity' : SubResource Integrity hash |
73
|
|
|
* - 'crossorigin' : Cross-origin policy for the resource |
74
|
|
|
* - 'cookie-consent' : Type of cookie for conditionnal loading : strictly-necessary,functionality,tracking,targeting |
75
|
|
|
*/ |
76
|
|
|
public function javascript($file, $options = array()) |
77
|
|
|
{ |
78
|
|
|
// We want to defer by default, but we can disable it if needed |
79
|
|
|
if (!isset($options['defer'])) { |
80
|
|
|
$options['defer'] = true; |
81
|
|
|
} |
82
|
|
|
if (isset($options['cookie-consent'])) { |
83
|
|
|
if (!in_array($options['cookie-consent'], ['strictly-necessary', 'functionality', 'tracking', 'targeting'])) { |
84
|
|
|
throw new InvalidArgumentException("The cookie-consent value is invalid, it must be one of: strictly-necessary,functionality,tracking,targeting"); |
85
|
|
|
} |
86
|
|
|
// switch to text plain for conditional loading |
87
|
|
|
$options['type'] = 'text/plain'; |
88
|
|
|
} |
89
|
|
|
parent::javascript($file, $options); |
90
|
|
|
if (isset($options['cookie-consent'])) { |
91
|
|
|
$this->javascript[$file]['cookie-consent'] = $options['cookie-consent']; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
/** |
96
|
|
|
* @param string $name |
97
|
|
|
* @param string|array $type Pass the type or an array of options |
98
|
|
|
* @return void |
99
|
|
|
*/ |
100
|
|
|
public function themedJavascript($name, $type = null) |
101
|
|
|
{ |
102
|
|
|
$path = ThemeResourceLoader::inst()->findThemedJavascript($name, SSViewer::get_themes()); |
103
|
|
|
if ($path) { |
104
|
|
|
$opts = []; |
105
|
|
|
if ($type) { |
106
|
|
|
if (is_string($type)) { |
107
|
|
|
$opts['type'] = $type; |
108
|
|
|
} elseif (is_array($type)) { |
|
|
|
|
109
|
|
|
$opts = $type; |
110
|
|
|
} |
111
|
|
|
} |
112
|
|
|
$this->javascript($path, $opts); |
113
|
|
|
} else { |
114
|
|
|
throw new InvalidArgumentException( |
115
|
|
|
"The javascript file doesn't exist. Please check if the file $name.js exists in any " |
116
|
|
|
. "context or search for themedJavascript references calling this file in your templates." |
117
|
|
|
); |
118
|
|
|
} |
119
|
|
|
} |
120
|
|
|
|
121
|
|
|
/** |
122
|
|
|
* @inheritDoc |
123
|
|
|
*/ |
124
|
|
|
public function customScript($script, $uniquenessID = null) |
125
|
|
|
{ |
126
|
|
|
// Wrap script in a DOMContentLoaded |
127
|
|
|
// Make sure we don't add the eventListener twice |
128
|
|
|
// @link https://stackoverflow.com/questions/41394983/how-to-defer-inline-javascript |
129
|
|
|
if (strpos($script, 'window.addEventListener') === false) { |
130
|
|
|
$script = "window.addEventListener('DOMContentLoaded', function() { $script });"; |
131
|
|
|
} |
132
|
|
|
|
133
|
|
|
// Remove comments if any |
134
|
|
|
$script = preg_replace('/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/', '', $script); |
135
|
|
|
|
136
|
|
|
return parent::customScript($script, $uniquenessID); |
|
|
|
|
137
|
|
|
} |
138
|
|
|
|
139
|
|
|
/** |
140
|
|
|
* Get all css files |
141
|
|
|
* |
142
|
|
|
* @return array |
143
|
|
|
*/ |
144
|
|
|
public function getCSS() |
145
|
|
|
{ |
146
|
|
|
$css = array_diff_key($this->css, $this->blocked); |
147
|
|
|
// Theme and assets files should always come last to have a proper cascade |
148
|
|
|
$allCss = []; |
149
|
|
|
$themeCss = []; |
150
|
|
|
foreach ($css as $file => $arr) { |
151
|
|
|
if (strpos($file, 'themes') === 0 || strpos($file, '/assets') === 0) { |
152
|
|
|
$themeCss[$file] = $arr; |
153
|
|
|
} else { |
154
|
|
|
$allCss[$file] = $arr; |
155
|
|
|
} |
156
|
|
|
} |
157
|
|
|
return array_merge($allCss, $themeCss); |
158
|
|
|
} |
159
|
|
|
|
160
|
|
|
/** |
161
|
|
|
* Update the given HTML content with the appropriate include tags for the registered |
162
|
|
|
* requirements. Needs to receive a valid HTML/XHTML template in the $content parameter, |
163
|
|
|
* including a head and body tag. |
164
|
|
|
* |
165
|
|
|
* @param string $content HTML content that has already been parsed from the $templateFile through {@link SSViewer} |
166
|
|
|
* @return string HTML content augmented with the requirements tags |
167
|
|
|
*/ |
168
|
|
|
public function includeInHTML($content) |
169
|
|
|
{ |
170
|
|
|
// Get our CSP nonce, it's always good to have even if we don't use it :-) |
171
|
|
|
$nonce = CspProvider::getCspNonce(); |
172
|
|
|
|
173
|
|
|
// Skip if content isn't injectable, or there is nothing to inject |
174
|
|
|
$tagsAvailable = preg_match('#</head\b#', $content); |
175
|
|
|
$hasFiles = $this->css || $this->javascript || $this->customCSS || $this->customScript || $this->customHeadTags; |
|
|
|
|
176
|
|
|
if (!$tagsAvailable || !$hasFiles) { |
177
|
|
|
return $content; |
178
|
|
|
} |
179
|
|
|
$requirements = ''; |
180
|
|
|
$jsRequirements = ''; |
181
|
|
|
|
182
|
|
|
// Combine files - updates $this->javascript and $this->css |
183
|
|
|
$this->processCombinedFiles(); |
184
|
|
|
|
185
|
|
|
// Script tags for js links |
186
|
|
|
foreach ($this->getJavascript() as $file => $attributes) { |
187
|
|
|
// Build html attributes |
188
|
|
|
$htmlAttributes = [ |
189
|
|
|
'type' => isset($attributes['type']) ? $attributes['type'] : "application/javascript", |
190
|
|
|
'src' => $this->pathForFile($file), |
191
|
|
|
'nonce' => $nonce, |
192
|
|
|
]; |
193
|
|
|
if (!empty($attributes['async'])) { |
194
|
|
|
$htmlAttributes['async'] = 'async'; |
195
|
|
|
} |
196
|
|
|
if (!empty($attributes['defer'])) { |
197
|
|
|
$htmlAttributes['defer'] = 'defer'; |
198
|
|
|
} |
199
|
|
|
$jsRequirements .= HTML::createTag('script', $htmlAttributes); |
200
|
|
|
$jsRequirements .= "\n"; |
201
|
|
|
} |
202
|
|
|
|
203
|
|
|
// Add all inline JavaScript *after* including external files they might rely on |
204
|
|
|
foreach ($this->getCustomScripts() as $script) { |
205
|
|
|
$jsRequirements .= HTML::createTag( |
206
|
|
|
'script', |
207
|
|
|
[ |
208
|
|
|
'type' => 'application/javascript', |
209
|
|
|
'nonce' => $nonce, |
210
|
|
|
], |
211
|
|
|
"//<![CDATA[\n{$script}\n//]]>" |
212
|
|
|
); |
213
|
|
|
$jsRequirements .= "\n"; |
214
|
|
|
} |
215
|
|
|
|
216
|
|
|
// Custom head tags (comes first) |
217
|
|
|
foreach ($this->getCustomHeadTags() as $customHeadTag) { |
218
|
|
|
$requirements .= "{$customHeadTag}\n"; |
219
|
|
|
} |
220
|
|
|
|
221
|
|
|
// CSS file links |
222
|
|
|
foreach ($this->getCSS() as $file => $params) { |
223
|
|
|
$htmlAttributes = [ |
224
|
|
|
'rel' => 'stylesheet', |
225
|
|
|
'type' => 'text/css', |
226
|
|
|
'href' => $this->pathForFile($file), |
227
|
|
|
]; |
228
|
|
|
if (!empty($params['media'])) { |
229
|
|
|
$htmlAttributes['media'] = $params['media']; |
230
|
|
|
} |
231
|
|
|
$requirements .= HTML::createTag('link', $htmlAttributes); |
232
|
|
|
$requirements .= "\n"; |
233
|
|
|
} |
234
|
|
|
|
235
|
|
|
// Literal custom CSS content |
236
|
|
|
foreach ($this->getCustomCSS() as $css) { |
237
|
|
|
$requirements .= HTML::createTag('style', ['type' => 'text/css'], "\n{$css}\n"); |
238
|
|
|
$requirements .= "\n"; |
239
|
|
|
} |
240
|
|
|
|
241
|
|
|
// Inject CSS into body |
242
|
|
|
$content = $this->insertTagsIntoHead($requirements, $content); |
243
|
|
|
|
244
|
|
|
// Inject scripts |
245
|
|
|
if ($this->getForceJSToBottom()) { |
246
|
|
|
$content = $this->insertScriptsAtBottom($jsRequirements, $content); |
247
|
|
|
} elseif ($this->getWriteJavascriptToBody()) { |
248
|
|
|
$content = $this->insertScriptsIntoBody($jsRequirements, $content); |
249
|
|
|
} else { |
250
|
|
|
$content = $this->insertTagsIntoHead($jsRequirements, $content); |
251
|
|
|
} |
252
|
|
|
return $content; |
253
|
|
|
} |
254
|
|
|
} |
255
|
|
|
|
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.