PluginProbe
Autoptimize / 3.0.3
Autoptimize v3.0.3
2.2.2 2.3.0 2.3.1 2.3.2 2.3.3 2.3.4 2.4.0 2.4.1 2.4.2 2.4.3 2.4.4 2.5.0 2.5.1 2.6.0 2.6.1 2.6.2 2.7.0 2.7.1 2.7.2 2.7.3 2.7.4 2.7.5 2.7.6 2.7.7 2.7.8 All 107 releases
← All changes | classes/autoptimizeScripts.php +420 -153 2.5.13.0.3 View file →
@@ -1,5 +1,8 @@
1 1 <?php
2 +/**
3 + * Class for JS optimization.
4 + */
2 5
3 6 if ( ! defined( 'ABSPATH' ) ) {
4 7 exit;
5 8 }
@@ -5,62 +8,243 @@
5 8 }
6 9
7 10 class autoptimizeScripts extends autoptimizeBase
8 11 {
12 +
13 + /**
14 + * Stores founds scripts.
15 + *
16 + * @var array
17 + */
9 18 private $scripts = array();
10 - private $move = array(
19 +
20 + /**
21 + * Stores to be moved JS.
22 + *
23 + * @var array
24 + */
25 + private $move = array(
11 26 'first' => array(),
12 - 'last' => array()
27 + 'last' => array(),
13 28 );
14 29
30 + /**
31 + * List of not to be moved JS.
32 + *
33 + * @var array
34 + */
15 35 private $dontmove = array(
16 - 'document.write','html5.js','show_ads.js','google_ad','histats.com/js','statcounter.com/counter/counter.js',
17 - 'ws.amazon.com/widgets','media.fastclick.net','/ads/','comment-form-quicktags/quicktags.php','edToolbar',
18 - 'intensedebate.com','scripts.chitika.net/','_gaq.push','jotform.com/','admin-bar.min.js','GoogleAnalyticsObject',
19 - 'plupload.full.min.js','syntaxhighlighter','adsbygoogle','gist.github.com','_stq','nonce','post_id','data-noptimize'
20 - ,'logHuman'
36 + 'document.write',
37 + 'html5.js',
38 + 'show_ads.js',
39 + 'google_ad',
40 + 'histats.com/js',
41 + 'statcounter.com/counter/counter.js',
42 + 'ws.amazon.com/widgets',
43 + 'media.fastclick.net',
44 + '/ads/',
45 + 'comment-form-quicktags/quicktags.php',
46 + 'edToolbar',
47 + 'intensedebate.com',
48 + 'scripts.chitika.net/',
49 + '_gaq.push',
50 + 'jotform.com/',
51 + 'admin-bar.min.js',
52 + 'GoogleAnalyticsObject',
53 + 'plupload.full.min.js',
54 + 'syntaxhighlighter',
55 + 'adsbygoogle',
56 + 'gist.github.com',
57 + '_stq',
58 + 'nonce',
59 + 'post_id',
60 + 'data-noptimize',
61 + 'data-cfasync',
62 + 'data-pagespeed-no-defer',
63 + 'logHuman',
64 + 'amp-mobile-version-switcher',
65 + 'data-rocketlazyloadscript',
66 + 'rocket-browser-checker-js-after',
21 67 );
22 - private $domove = array(
23 - 'gaJsHost','load_cmc','jd.gallery.transitions.js','swfobject.embedSWF(','tiny_mce.js','tinyMCEPreInit.go'
68 +
69 + /**
70 + * List of to be moved JS.
71 + *
72 + * @var array
73 + */
74 + private $domove = array(
75 + 'gaJsHost',
76 + 'load_cmc',
77 + 'jd.gallery.transitions.js',
78 + 'swfobject.embedSWF(',
79 + 'tiny_mce.js',
80 + 'tinyMCEPreInit.go',
24 81 );
82 +
83 + /**
84 + * List of JS that can be moved last (not used any more).
85 + *
86 + * @var array
87 + */
25 88 private $domovelast = array(
26 - 'addthis.com','/afsonline/show_afs_search.js','disqus.js','networkedblogs.com/getnetworkwidget','infolinks.com/js/',
27 - 'jd.gallery.js.php','jd.gallery.transitions.js','swfobject.embedSWF(','linkwithin.com/widget.js','tiny_mce.js','tinyMCEPreInit.go'
89 + 'addthis.com',
90 + '/afsonline/show_afs_search.js',
91 + 'disqus.js',
92 + 'networkedblogs.com/getnetworkwidget',
93 + 'infolinks.com/js/',
94 + 'jd.gallery.js.php',
95 + 'jd.gallery.transitions.js',
96 + 'swfobject.embedSWF(',
97 + 'linkwithin.com/widget.js',
98 + 'tiny_mce.js',
99 + 'tinyMCEPreInit.go',
28 100 );
101 +
102 + /**
103 + * Setting CDN base URL.
104 + *
105 + * @var string
106 + */
29 107 public $cdn_url = '';
30 108
31 - private $aggregate = true;
32 - private $trycatch = false;
109 + /**
110 + * Setting; aggregate or not.
111 + *
112 + * @var bool
113 + */
114 + private $aggregate = true;
115 +
116 + /**
117 + * Setting; if not aggregated, should we defer?
118 + *
119 + * @var bool
120 + */
121 + private $defer_not_aggregate = false;
122 +
123 + /**
124 + * Setting; defer inline JS?
125 + *
126 + * @var bool
127 + */
128 + private $defer_inline = false;
129 +
130 + /**
131 + * Setting; try/catch wrapping or not.
132 + *
133 + * @var bool
134 + */
135 + private $trycatch = false;
136 +
137 + /**
138 + * State; is JS already minified.
139 + *
140 + * @var bool
141 + */
33 142 private $alreadyminified = false;
34 - private $forcehead = true;
35 - private $include_inline = false;
36 - private $jscode = '';
37 - private $url = '';
38 - private $restofcontent = '';
39 - private $md5hash = '';
40 - private $whitelist = '';
41 - private $jsremovables = array();
42 - private $inject_min_late = '';
143 +
144 + /**
145 + * Setting; force JS in head or not.
146 + *
147 + * @var bool
148 + */
149 + private $forcehead = true;
150 +
151 + /**
152 + * Setting; aggregate inline JS or not.
153 + *
154 + * @var bool
155 + */
156 + private $include_inline = false;
157 +
158 + /**
159 + * State; holds JS code.
160 + *
161 + * @var string
162 + */
163 + private $jscode = '';
164 +
165 + /**
166 + * State; holds URL of JS-file.
167 + *
168 + * @var string
169 + */
170 + private $url = '';
171 +
172 + /**
173 + * State; stores rest of HTML if (old) option "only in head" is on.
174 + *
175 + * @var string
176 + */
177 + private $restofcontent = '';
178 +
179 + /**
180 + * State; holds md5-hash.
181 + *
182 + * @var string
183 + */
184 + private $md5hash = '';
185 +
186 + /**
187 + * Setting (filter); allowlist of to be aggregated JS.
188 + *
189 + * @var string
190 + */
191 + private $allowlist = '';
192 +
193 + /**
194 + * Setting (filter); holds JS that should be removed.
195 + *
196 + * @var array
197 + */
198 + private $jsremovables = array();
199 +
200 + /**
201 + * Setting (filter); can we inject already minified files after the
202 + * unminified aggregate JS has been minified.
203 + *
204 + * @var bool
205 + */
206 + private $inject_min_late = true;
207 +
208 + /**
209 + * Setting; should excluded JS be minified (if not already).
210 + *
211 + * @var bool
212 + */
43 213 private $minify_excluded = true;
44 214
45 - // Reads the page and collects script tags.
46 - public function read($options)
215 + /**
216 + * Reads the page and collects script tags.
217 + *
218 + * @param array $options all options.
219 + */
220 + public function read( $options )
47 221 {
48 - $noptimizeJS = apply_filters( 'autoptimize_filter_js_noptimize', false, $this->content );
49 - if ( $noptimizeJS ) {
222 + $noptimize_js = false;
223 +
224 + // If page/ post check post_meta to see if optimize is off.
225 + if ( false === autoptimizeConfig::get_post_meta_ao_settings( 'ao_post_js_optimize' ) ) {
226 + $noptimize_js = true;
227 + }
228 +
229 + // And a filter to enforce JS noptimize.
230 + $noptimize_js = apply_filters( 'autoptimize_filter_js_noptimize', $noptimize_js, $this->content );
231 +
232 + // And finally bail if noptimize_js is true.
233 + if ( $noptimize_js ) {
50 234 return false;
51 235 }
52 236
53 237 // only optimize known good JS?
54 - $whitelistJS = apply_filters( 'autoptimize_filter_js_whitelist', '', $this->content );
55 - if ( ! empty( $whitelistJS ) ) {
56 - $this->whitelist = array_filter( array_map( 'trim', explode( ',', $whitelistJS ) ) );
238 + $allowlist_js = apply_filters( 'autoptimize_filter_js_allowlist', '', $this->content );
239 + if ( ! empty( $allowlist_js ) ) {
240 + $this->allowlist = array_filter( array_map( 'trim', explode( ',', $allowlist_js ) ) );
57 241 }
58 242
59 243 // is there JS we should simply remove?
60 - $removableJS = apply_filters( 'autoptimize_filter_js_removables', '', $this->content );
61 - if (!empty($removableJS)) {
62 - $this->jsremovables = array_filter( array_map( 'trim', explode( ',', $removableJS ) ) );
244 + $removable_js = apply_filters( 'autoptimize_filter_js_removables', '', $this->content );
245 + if ( ! empty( $removable_js ) ) {
246 + $this->jsremovables = array_filter( array_map( 'trim', explode( ',', $removable_js ) ) );
63 247 }
64 248
65 249 // only header?
66 250 if ( apply_filters( 'autoptimize_filter_js_justhead', $options['justhead'] ) ) {
@@ -76,8 +260,20 @@
76 260 // Returning true for "dontaggregate" turns off aggregation.
77 261 if ( $this->aggregate && apply_filters( 'autoptimize_filter_js_dontaggregate', false ) ) {
78 262 $this->aggregate = false;
79 263 }
264 + // and the filter that should have been there to begin with.
265 + $this->aggregate = apply_filters( 'autoptimize_filter_js_aggregate', $this->aggregate );
266 +
267 + // Defer when not aggregating.
268 + if ( false === $this->aggregate && apply_filters( 'autoptimize_filter_js_defer_not_aggregate', $options['defer_not_aggregate'] ) ) {
269 + $this->defer_not_aggregate = true;
270 + }
271 +
272 + // Defer inline JS?
273 + if ( ( true === $this->defer_not_aggregate && apply_filters( 'autoptimize_js_filter_defer_inline', $options['defer_inline'] ) ) || apply_filters( 'autoptimize_js_filter_force_defer_inline', false ) ) {
274 + $this->defer_inline = true;
275 + }
80 276
81 277 // include inline?
82 278 if ( apply_filters( 'autoptimize_js_include_inline', $options['include_inline'] ) ) {
83 279 $this->include_inline = true;
@@ -86,34 +282,36 @@
86 282 // filter to "late inject minified JS", default to true for now (it is faster).
87 283 $this->inject_min_late = apply_filters( 'autoptimize_filter_js_inject_min_late', true );
88 284
89 285 // filters to override hardcoded do(nt)move(last) array contents (array in, array out!).
90 - $this->dontmove = apply_filters( 'autoptimize_filter_js_dontmove', $this->dontmove );
286 + $this->dontmove = apply_filters( 'autoptimize_filter_js_dontmove', $this->dontmove );
91 287 $this->domovelast = apply_filters( 'autoptimize_filter_js_movelast', $this->domovelast );
92 - $this->domove = apply_filters( 'autoptimize_filter_js_domove', $this->domove );
288 + $this->domove = apply_filters( 'autoptimize_filter_js_domove', $this->domove );
93 289
94 290 // Determine whether excluded files should be minified if not yet so.
95 291 if ( ! $options['minify_excluded'] && $options['aggregate'] ) {
96 292 $this->minify_excluded = false;
97 293 }
294 + $this->minify_excluded = apply_filters( 'autoptimize_filter_js_minify_excluded', $this->minify_excluded, '' );
98 295
99 296 // get extra exclusions settings or filter.
100 - $excludeJS = $options['js_exclude'];
101 - $excludeJS = apply_filters( 'autoptimize_filter_js_exclude', $excludeJS, $this->content );
297 + $exclude_js = $options['js_exclude'];
298 + $exclude_js = apply_filters( 'autoptimize_filter_js_exclude', $exclude_js, $this->content );
102 299
103 - if ( '' !== $excludeJS ) {
104 - if ( is_array( $excludeJS ) ) {
105 - if ( ( $removeKeys = array_keys( $excludeJS, 'remove' ) ) !== false ) {
106 - foreach ( $removeKeys as $removeKey ) {
107 - unset( $excludeJS[$removeKey] );
108 - $this->jsremovables[] = $removeKey;
300 + if ( '' !== $exclude_js ) {
301 + if ( is_array( $exclude_js ) ) {
302 + $remove_keys = array_keys( $exclude_js, 'remove' );
303 + if ( false !== $remove_keys ) {
304 + foreach ( $remove_keys as $remove_key ) {
305 + unset( $exclude_js[ $remove_key ] );
306 + $this->jsremovables[] = $remove_key;
109 307 }
110 308 }
111 - $exclJSArr = array_keys( $excludeJS );
309 + $excl_js_arr = array_keys( $exclude_js );
112 310 } else {
113 - $exclJSArr = array_filter( array_map( 'trim', explode( ',', $excludeJS ) ) );
311 + $excl_js_arr = array_filter( array_map( 'trim', explode( ',', $exclude_js ) ) );
114 312 }
115 - $this->dontmove = array_merge( $exclJSArr, $this->dontmove );
313 + $this->dontmove = array_merge( $excl_js_arr, $this->dontmove );
116 314 }
117 315
118 316 // Should we add try-catch?
119 317 if ( $options['trycatch'] ) {
@@ -132,21 +330,21 @@
132 330 // get cdn url.
133 331 $this->cdn_url = $options['cdn_url'];
134 332
135 333 // noptimize me.
136 - $this->content = $this->hide_noptimize($this->content);
334 + $this->content = $this->hide_noptimize( $this->content );
137 335
138 336 // Save IE hacks.
139 - $this->content = $this->hide_iehacks($this->content);
337 + $this->content = $this->hide_iehacks( $this->content );
140 338
141 339 // comments.
142 - $this->content = $this->hide_comments($this->content);
340 + $this->content = $this->hide_comments( $this->content );
143 341
144 342 // Get script files.
145 343 if ( preg_match_all( '#<script.*</script>#Usmi', $this->content, $matches ) ) {
146 - foreach( $matches[0] as $tag ) {
147 - // only consider script aggregation for types whitelisted in should_aggregate-function.
148 - $should_aggregate = $this->should_aggregate($tag);
344 + foreach ( $matches[0] as $tag ) {
345 + // only consider script aggregation for types allowlisted in should_aggregate-function.
346 + $should_aggregate = $this->should_aggregate( $tag );
149 347 if ( ! $should_aggregate ) {
150 348 $tag = '';
151 349 continue;
152 350 }
@@ -152,59 +350,73 @@
152 350 }
153 351
154 352 if ( preg_match( '#<script[^>]*src=("|\')([^>]*)("|\')#Usmi', $tag, $source ) ) {
155 353 // non-inline script.
156 - if ( $this->isremovable($tag, $this->jsremovables) ) {
354 + if ( $this->isremovable( $tag, $this->jsremovables ) ) {
157 355 $this->content = str_replace( $tag, '', $this->content );
158 356 continue;
159 357 }
160 358
161 - $origTag = null;
162 - $url = current( explode( '?', $source[2], 2 ) );
163 - $path = $this->getpath($url);
164 - if ( false !== $path && preg_match( '#\.js$#', $path ) && $this->ismergeable($tag) ) {
359 + $orig_tag = null;
360 + $url = current( explode( '?', $source[2], 2 ) );
361 + $path = $this->getpath( $url );
362 + if ( false !== $path && preg_match( '#\.js$#', $path ) && $this->ismergeable( $tag ) ) {
165 363 // ok to optimize, add to array.
166 364 $this->scripts[] = $path;
167 365 } else {
168 - $origTag = $tag;
169 - $newTag = $tag;
366 + $orig_tag = $tag;
367 + $new_tag = $tag;
170 368
171 369 // non-mergeable script (excluded or dynamic or external).
172 - if ( is_array( $excludeJS ) ) {
370 + if ( is_array( $exclude_js ) ) {
173 371 // should we add flags?
174 - foreach ( $excludeJS as $exclTag => $exclFlags) {
175 - if ( false !== strpos( $origTag, $exclTag ) && in_array( $exclFlags, array( 'async', 'defer' ) ) ) {
176 - $newTag = str_replace( '<script ', '<script ' . $exclFlags . ' ', $newTag );
372 + foreach ( $exclude_js as $excl_tag => $excl_flags ) {
373 + if ( false !== strpos( $orig_tag, $excl_tag ) && in_array( $excl_flags, array( 'async', 'defer' ) ) ) {
374 + $new_tag = str_replace( '<script ', '<script ' . $excl_flags . ' ', $new_tag );
177 375 }
178 376 }
179 377 }
180 378
379 + // not aggregating but deferring?
380 + if ( $this->defer_not_aggregate && false === $this->aggregate && ( str_replace( $this->dontmove, '', $path ) === $path || ( apply_filters( 'autoptimize_filter_js_defer_external', true ) && str_replace( $this->dontmove, '', $orig_tag ) === $orig_tag ) ) && strpos( $new_tag, ' defer' ) === false && strpos( $new_tag, ' async' ) === false ) {
381 + $new_tag = str_replace( '<script ', '<script defer ', $new_tag );
382 + }
383 +
181 384 // Should we minify the non-aggregated script?
182 385 // -> if aggregate is on and exclude minify is on
183 386 // -> if aggregate is off and the file is not in dontmove.
184 - if ( $path && ( $this->minify_excluded || apply_filters( 'autoptimize_filter_js_minify_excluded', false, $url ) ) ) {
387 + if ( $path && $this->minify_excluded ) {
185 388 $consider_minified_array = apply_filters( 'autoptimize_filter_js_consider_minified', false );
186 389 if ( ( false === $this->aggregate && str_replace( $this->dontmove, '', $path ) === $path ) || ( true === $this->aggregate && ( false === $consider_minified_array || str_replace( $consider_minified_array, '', $path ) === $path ) ) ) {
187 390 $minified_url = $this->minify_single( $path );
188 - // replace orig URL with minified URL from cache if so.
189 391 if ( ! empty( $minified_url ) ) {
190 - $newTag = str_replace( $url, $minified_url, $newTag );
392 + // Replace original URL with minified URL from cache.
393 + $new_tag = str_replace( $url, $minified_url, $new_tag );
394 + } elseif ( apply_filters( 'autoptimize_filter_ccsjs_remove_empty_minified_url', false ) ) {
395 + // Remove the original script tag, because cache content is empty but only if filter
396 + // is trued because $minified_url is also false if original JS is minified already.
397 + $new_tag = '';
191 398 }
192 399 }
193 400 }
194 401
195 - if ( $this->ismovable($newTag) ) {
402 + // Check if we still need to CDN (esp. for already minified resources).
403 + if ( ! empty( $this->cdn_url ) || has_filter( 'autoptimize_filter_base_replace_cdn' ) ) {
404 + $new_tag = str_replace( $url, $this->url_replace_cdn( $url ), $new_tag );
405 + }
406 +
407 + if ( $this->ismovable( $new_tag ) ) {
196 408 // can be moved, flags and all.
197 - if ( $this->movetolast($newTag) ) {
198 - $this->move['last'][] = $newTag;
409 + if ( $this->movetolast( $new_tag ) ) {
410 + $this->move['last'][] = $new_tag;
199 411 } else {
200 - $this->move['first'][] = $newTag;
412 + $this->move['first'][] = $new_tag;
201 413 }
202 414 } else {
203 415 // cannot be moved, so if flag was added re-inject altered tag immediately.
204 - if ( $origTag !== $newTag ) {
205 - $this->content = str_replace( $origTag, $newTag, $this->content );
206 - $origTag = '';
416 + if ( ( '' !== $new_tag && $orig_tag !== $new_tag ) || ( '' === $new_tag && apply_filters( 'autoptimize_filter_js_remove_empty_files', false ) ) ) {
417 + $this->content = str_replace( $orig_tag, $new_tag, $this->content );
418 + $orig_tag = '';
207 419 }
208 420 // and forget about the $tag (not to be touched any more).
209 421 $tag = '';
210 422 }
@@ -210,39 +422,57 @@
210 422 }
211 423 }
212 424 } else {
213 425 // Inline script.
214 - if ( $this->isremovable($tag, $this->jsremovables) ) {
426 + if ( $this->isremovable( $tag, $this->jsremovables ) ) {
215 427 $this->content = str_replace( $tag, '', $this->content );
216 428 continue;
217 429 }
218 430
219 431 // unhide comments, as javascript may be wrapped in comment-tags for old times' sake.
220 - $tag = $this->restore_comments($tag);
221 - if ( $this->ismergeable($tag) && $this->include_inline ) {
222 - preg_match( '#<script.*>(.*)</script>#Usmi', $tag , $code );
223 - $code = preg_replace('#.*<!\[CDATA\[(?:\s*\*/)?(.*)(?://|/\*)\s*?\]\]>.*#sm', '$1', $code[1] );
224 - $code = preg_replace('/(?:^\\s*<!--\\s*|\\s*(?:\\/\\/)?\\s*-->\\s*$)/', '', $code );
432 + $tag = $this->restore_comments( $tag );
433 + if ( $this->ismergeable( $tag ) && $this->include_inline ) {
434 + preg_match( '#<script.*>(.*)</script>#Usmi', $tag, $code );
435 + $code = preg_replace( '#.*<!\[CDATA\[(?:\s*\*/)?(.*)(?://|/\*)\s*?\]\]>.*#sm', '$1', $code[1] );
436 + $code = preg_replace( '/(?:^\\s*<!--\\s*|\\s*(?:\\/\\/)?\\s*-->\\s*$)/', '', $code );
225 437 $this->scripts[] = 'INLINE;' . $code;
226 438 } else {
227 - // Can we move this?
228 - $autoptimize_js_moveable = apply_filters( 'autoptimize_js_moveable', '', $tag );
229 - if ( $this->ismovable($tag) || '' !== $autoptimize_js_moveable ) {
230 - if ( $this->movetolast($tag) || 'last' === $autoptimize_js_moveable ) {
231 - $this->move['last'][] = $tag;
439 + $_inline_deferable = apply_filters( 'autoptimize_filters_js_inline_deferable', array( 'nonce', 'post_id', 'syntaxhighlighter' ) );
440 + $_inline_dontmove = array_values( array_diff( $this->dontmove, $_inline_deferable ) );
441 + if ( false === $this->defer_inline ) {
442 + // Can we move this?
443 + $autoptimize_js_moveable = apply_filters( 'autoptimize_js_moveable', '', $tag );
444 + if ( $this->ismovable( $tag ) || '' !== $autoptimize_js_moveable ) {
445 + if ( $this->movetolast( $tag ) || 'last' === $autoptimize_js_moveable ) {
446 + $this->move['last'][] = $tag;
447 + } else {
448 + $this->move['first'][] = $tag;
449 + }
232 450 } else {
233 - $this->move['first'][] = $tag;
451 + $tag = '';
234 452 }
453 + } else if ( str_replace( $_inline_dontmove, '', $tag ) === $tag ) {
454 + // defer inline JS by base64 encoding it.
455 + // preg_match( '#<script.*>(.*)</script>#Usmi', $tag, $match );
456 + preg_match( '#<script(?:[^>](?!id=))*\s*(?:id=(["\'])([^"\']+)\1)*+[^>]*+>(.*?)<\/script>#is', $tag, $match );
457 + if ( $match[2] ) {
458 + $_id = 'id="' . $match[2] . '" ';
459 + } else {
460 + $_id = '';
461 + }
462 +
463 + $new_tag = '<script defer ' . $_id . 'src="data:text/javascript;base64,' . base64_encode( $match[3] ) . '"></script>';
464 + $this->content = str_replace( $tag, $new_tag, $this->content );
465 + $tag = '';
235 466 } else {
236 - // We shouldn't touch this.
237 467 $tag = '';
238 468 }
239 469 }
240 470 // Re-hide comments to be able to do the removal based on tag from $this->content.
241 - $tag = $this->hide_comments($tag);
471 + $tag = $this->hide_comments( $tag );
242 472 }
243 473
244 - //Remove the original script tag.
474 + // Remove the original script tag.
245 475 $this->content = str_replace( $tag, '', $this->content );
246 476 }
247 477
248 478 return true;
@@ -247,9 +477,9 @@
247 477
248 478 return true;
249 479 }
250 480
251 - // No script files, great ;-)
481 + // No script files, great ;-) .
252 482 return false;
253 483 }
254 484
255 485 /**
@@ -263,17 +493,21 @@
263 493 * Everything else should return false.
264 494 *
265 495 * @link https://developer.mozilla.org/en/docs/Web/HTML/Element/script#attr-type
266 496 *
267 - * @param string $tag
497 + * @param string $tag Script node & child(ren).
268 498 * @return bool
269 499 */
270 - public function should_aggregate($tag)
500 + public static function should_aggregate( $tag )
271 501 {
502 + if ( empty( $tag ) ) {
503 + return false;
504 + }
505 +
272 506 // We're only interested in the type attribute of the <script> tag itself, not any possible
273 507 // inline code that might just contain the 'type=' string...
274 508 $tag_parts = array();
275 - preg_match( '#<(script[^>]*)>#i', $tag, $tag_parts);
509 + preg_match( '#<(script[^>]*)>#i', $tag, $tag_parts );
276 510 $tag_without_contents = null;
277 511 if ( ! empty( $tag_parts[1] ) ) {
278 512 $tag_without_contents = $tag_parts[1];
279 513 }
@@ -292,15 +526,21 @@
292 526
293 527 return $should_aggregate;
294 528 }
295 529
296 - //Joins and optimizes JS
530 + /**
531 + * Joins and optimizes JS.
532 + */
297 533 public function minify()
298 534 {
299 535 foreach ( $this->scripts as $script ) {
300 - // TODO/FIXME: some duplicate code here, can be reduced/simplified
536 + if ( empty( $script ) ) {
537 + continue;
538 + }
539 +
540 + // TODO/FIXME: some duplicate code here, can be reduced/simplified.
301 541 if ( preg_match( '#^INLINE;#', $script ) ) {
302 - // Inline script
542 + // Inline script.
303 543 $script = preg_replace( '#^INLINE;#', '', $script );
304 544 $script = rtrim( $script, ";\n\t\r" ) . ';';
305 545 // Add try-catch?
306 546 if ( $this->trycatch ) {
@@ -307,14 +547,14 @@
307 547 $script = 'try{' . $script . '}catch(e){}';
308 548 }
309 549 $tmpscript = apply_filters( 'autoptimize_js_individual_script', $script, '' );
310 550 if ( has_filter( 'autoptimize_js_individual_script' ) && ! empty( $tmpscript ) ) {
311 - $script = $tmpscript;
551 + $script = $tmpscript;
312 552 $this->alreadyminified = true;
313 553 }
314 554 $this->jscode .= "\n" . $script;
315 555 } else {
316 - // External script
556 + // External script.
317 557 if ( false !== $script && file_exists( $script ) && is_readable( $script ) ) {
318 558 $scriptsrc = file_get_contents( $script );
319 559 $scriptsrc = preg_replace( '/\x{EF}\x{BB}\x{BF}/', '', $scriptsrc );
320 560 $scriptsrc = rtrim( $scriptsrc, ";\n\t\r" ) . ';';
@@ -323,23 +563,21 @@
323 563 $scriptsrc = 'try{' . $scriptsrc . '}catch(e){}';
324 564 }
325 565 $tmpscriptsrc = apply_filters( 'autoptimize_js_individual_script', $scriptsrc, $script );
326 566 if ( has_filter( 'autoptimize_js_individual_script' ) && ! empty( $tmpscriptsrc ) ) {
327 - $scriptsrc = $tmpscriptsrc;
567 + $scriptsrc = $tmpscriptsrc;
328 568 $this->alreadyminified = true;
329 - } else if ( $this->can_inject_late($script) ) {
330 - $scriptsrc = self::build_injectlater_marker($script, md5($scriptsrc));
569 + } elseif ( $this->can_inject_late( $script ) ) {
570 + $scriptsrc = self::build_injectlater_marker( $script, md5( $scriptsrc ) );
331 571 }
332 572 $this->jscode .= "\n" . $scriptsrc;
333 - }/*else{
334 - //Couldn't read JS. Maybe getpath isn't working?
335 - }*/
573 + }
336 574 }
337 575 }
338 576
339 - // Check for already-minified code
577 + // Check for already-minified code.
340 578 $this->md5hash = md5( $this->jscode );
341 - $ccheck = new autoptimizeCache($this->md5hash, 'js');
579 + $ccheck = new autoptimizeCache( $this->md5hash, 'js' );
342 580 if ( $ccheck->check() ) {
343 581 $this->jscode = $ccheck->retrieve();
344 582 return true;
345 583 }
@@ -365,51 +603,59 @@
365 603 $this->jscode = apply_filters( 'autoptimize_js_after_minify', $this->jscode );
366 604 return true;
367 605 }
368 606
369 - // Caches the JS in uncompressed, deflated and gzipped form.
607 + /**
608 + * Caches the JS in uncompressed, deflated and gzipped form.
609 + */
370 610 public function cache()
371 611 {
372 - $cache = new autoptimizeCache($this->md5hash, 'js');
612 + $cache = new autoptimizeCache( $this->md5hash, 'js' );
373 613 if ( ! $cache->check() ) {
374 - // Cache our code
375 - $cache->cache($this->jscode, 'text/javascript');
614 + // Cache our code.
615 + $cache->cache( $this->jscode, 'text/javascript' );
376 616 }
377 617 $this->url = AUTOPTIMIZE_CACHE_URL . $cache->getname();
378 - $this->url = $this->url_replace_cdn($this->url);
618 + $this->url = $this->url_replace_cdn( $this->url );
379 619 }
380 620
381 - // Returns the content
621 + /**
622 + * Returns the content.
623 + */
382 624 public function getcontent()
383 625 {
384 - // Restore the full content
626 + // Restore the full content.
385 627 if ( ! empty( $this->restofcontent ) ) {
386 - $this->content .= $this->restofcontent;
628 + $this->content .= $this->restofcontent;
387 629 $this->restofcontent = '';
388 630 }
389 631
390 - // Add the scripts taking forcehead/ deferred (default) into account
632 + // Add the scripts taking forcehead/ deferred (default) into account.
391 633 if ( $this->forcehead ) {
392 - $replaceTag = array( '</head>', 'before' );
393 - $defer = '';
634 + $replace_tag = array( '</head>', 'before' );
635 + $defer = '';
394 636 } else {
395 - $replaceTag = array( '</body>', 'before' );
396 - $defer = 'defer ';
637 + $replace_tag = array( '</body>', 'before' );
638 + $defer = 'defer ';
397 639 }
398 640
399 - $defer = apply_filters( 'autoptimize_filter_js_defer', $defer );
641 + $defer = apply_filters( 'autoptimize_filter_js_defer', $defer );
642 + $type_js = '';
643 + if ( apply_filters( 'autoptimize_filter_cssjs_addtype', false ) ) {
644 + $type_js = 'type="text/javascript" ';
645 + }
400 646
401 - $bodyreplacementpayload = '<script type="text/javascript" ' . $defer . 'src="' . $this->url . '"></script>';
647 + $bodyreplacementpayload = '<script ' . $type_js . $defer . 'src="' . $this->url . '"></script>';
402 648 $bodyreplacementpayload = apply_filters( 'autoptimize_filter_js_bodyreplacementpayload', $bodyreplacementpayload );
403 649
404 - $bodyreplacement = implode( '', $this->move['first'] );
650 + $bodyreplacement = implode( '', $this->move['first'] );
405 651 $bodyreplacement .= $bodyreplacementpayload;
406 652 $bodyreplacement .= implode( '', $this->move['last'] );
407 653
408 - $replaceTag = apply_filters( 'autoptimize_filter_js_replacetag', $replaceTag );
654 + $replace_tag = apply_filters( 'autoptimize_filter_js_replacetag', $replace_tag );
409 655
410 656 if ( strlen( $this->jscode ) > 0 ) {
411 - $this->inject_in_html( $bodyreplacement, $replaceTag );
657 + $this->inject_in_html( $bodyreplacement, $replace_tag );
412 658 }
413 659
414 660 // Restore comments.
415 661 $this->content = $this->restore_comments( $this->content );
@@ -423,86 +669,98 @@
423 669 // Return the modified HTML.
424 670 return $this->content;
425 671 }
426 672
427 - // Checks against the white- and blacklists
428 - private function ismergeable($tag)
673 + /**
674 + * Checks against the allow- and blocklists.
675 + *
676 + * @param string $tag JS tag.
677 + */
678 + private function ismergeable( $tag )
429 679 {
430 - if ( ! $this->aggregate ) {
680 + if ( empty( $tag ) || ! $this->aggregate ) {
431 681 return false;
432 682 }
433 683
434 - if ( ! empty( $this->whitelist ) ) {
435 - foreach ( $this->whitelist as $match ) {
436 - if (false !== strpos( $tag, $match ) ) {
684 + if ( ! empty( $this->allowlist ) ) {
685 + foreach ( $this->allowlist as $match ) {
686 + if ( false !== strpos( $tag, $match ) ) {
437 687 return true;
438 688 }
439 689 }
440 - // no match with whitelist
690 + // No match with allowlist.
441 691 return false;
442 692 } else {
443 - foreach($this->domove as $match) {
693 + foreach ( $this->domove as $match ) {
444 694 if ( false !== strpos( $tag, $match ) ) {
445 - // Matched something
695 + // Matched something.
446 696 return false;
447 697 }
448 698 }
449 699
450 - if ( $this->movetolast($tag) ) {
700 + if ( $this->movetolast( $tag ) ) {
451 701 return false;
452 702 }
453 703
454 - foreach( $this->dontmove as $match ) {
704 + foreach ( $this->dontmove as $match ) {
455 705 if ( false !== strpos( $tag, $match ) ) {
456 - // Matched something
706 + // Matched something.
457 707 return false;
458 708 }
459 709 }
460 710
461 - // If we're here it's safe to merge
711 + // If we're here it's safe to merge.
462 712 return true;
463 713 }
464 714 }
465 715
466 - // Checks agains the blacklist
467 - private function ismovable($tag)
716 + /**
717 + * Checks agains the blocklist.
718 + *
719 + * @param string $tag tag to check for blocklist (exclusions).
720 + */
721 + private function ismovable( $tag )
468 722 {
469 - if ( true !== $this->include_inline || apply_filters( 'autoptimize_filter_js_unmovable', true ) ) {
723 + if ( empty( $tag ) || true !== $this->include_inline || apply_filters( 'autoptimize_filter_js_unmovable', true ) ) {
470 724 return false;
471 725 }
472 726
473 727 foreach ( $this->domove as $match ) {
474 728 if ( false !== strpos( $tag, $match ) ) {
475 - // Matched something
729 + // Matched something.
476 730 return true;
477 731 }
478 732 }
479 733
480 - if ( $this->movetolast($tag) ) {
734 + if ( $this->movetolast( $tag ) ) {
481 735 return true;
482 736 }
483 737
484 738 foreach ( $this->dontmove as $match ) {
485 739 if ( false !== strpos( $tag, $match ) ) {
486 - // Matched something
740 + // Matched something.
487 741 return false;
488 742 }
489 743 }
490 744
491 - // If we're here it's safe to move
745 + // If we're here it's safe to move.
492 746 return true;
493 747 }
494 748
495 - private function movetolast($tag)
749 + private function movetolast( $tag )
496 750 {
751 + if ( empty( $tag ) ) {
752 + return false;
753 + }
754 +
497 755 foreach ( $this->domovelast as $match ) {
498 756 if ( false !== strpos( $tag, $match ) ) {
499 - // Matched, return true
757 + // Matched, return true.
500 758 return true;
501 759 }
502 760 }
503 761
504 - // Should be in 'first'
762 + // Should be in 'first'.
505 763 return false;
506 764 }
507 765
508 766 /**
@@ -508,24 +766,24 @@
508 766 /**
509 767 * Determines wheter a <script> $tag can be excluded from minification (as already minified) based on:
510 768 * - inject_min_late being active
511 769 * - filename ending in `min.js`
512 - * - filename matching `js/jquery/jquery.js` (wordpress core jquery, is minified)
770 + * - filename matching `js/jquery/jquery.js` (WordPress core jquery, is minified)
513 771 * - filename matching one passed in the consider minified filter
514 772 *
515 - * @param string $jsPath
773 + * @param string $js_path Path to JS file.
516 774 * @return bool
517 775 */
518 - private function can_inject_late($jsPath) {
776 + private function can_inject_late( $js_path ) {
519 777 $consider_minified_array = apply_filters( 'autoptimize_filter_js_consider_minified', false );
520 778 if ( true !== $this->inject_min_late ) {
521 - // late-inject turned off
779 + // late-inject turned off.
522 780 return false;
523 - } else if ( ( false === strpos( $jsPath, 'min.js' ) ) && ( false === strpos( $jsPath, 'wp-includes/js/jquery/jquery.js' ) ) && ( str_replace( $consider_minified_array, '', $jsPath ) === $jsPath ) ) {
524 - // file not minified based on filename & filter
781 + } elseif ( ( false === strpos( $js_path, 'min.js' ) ) && ( false === strpos( $js_path, 'wp-includes/js/jquery/jquery.js' ) ) && ( str_replace( $consider_minified_array, '', $js_path ) === $js_path ) ) {
782 + // file not minified based on filename & filter.
525 783 return false;
526 784 } else {
527 - // phew, all is safe, we can late-inject
785 + // phew, all is safe, we can late-inject.
528 786 return true;
529 787 }
530 788 }
531 789
@@ -542,9 +800,9 @@
542 800 /**
543 801 * Minifies a single local js file and returns its (cached) url.
544 802 *
545 803 * @param string $filepath Filepath.
546 - * @param bool $cache_miss Optional. Force a cache miss. Default false.
804 + * @param bool $cache_miss Optional. Force a cache miss. Default false.
547 805 *
548 806 * @return bool|string Url pointing to the minified js file or false.
549 807 */
550 808 public function minify_single( $filepath, $cache_miss = false )
@@ -561,8 +819,17 @@
561 819
562 820 // If not in cache already, minify...
563 821 if ( ! $cache->check() || $cache_miss ) {
564 822 $contents = trim( JSMin::minify( $contents ) );
823 +
824 + // Check if minified cache content is empty.
825 + if ( empty( $contents ) ) {
826 + return false;
827 + }
828 +
829 + // Filter contents of excluded minified CSS.
830 + $contents = apply_filters( 'autoptimize_filter_js_single_after_minify', $contents );
831 +
565 832 // Store in cache.
566 833 $cache->cache( $contents, 'text/javascript' );
567 834 }
568 835