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