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