PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.7.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.7.0
4.7.0 4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 All 111 releases
← All changes | minify/class-wp-optimize-minify-front-end.php +532 -177 3.3.0 → 4.7.0 View file →
@@ -64,8 +64,14 @@
64 64 if ($this->options['enable_js']) {
65 65 $this->process_js();
66 66 }
67 67
68 + if ($this->options['host_local_google_fonts']) {
69 + // Add filter to replace Goole fonts urls to local if needed
70 + add_filter('wpo_minify_css_string', array($this, 'replace_gfont_urls_with_local'));
71 + add_filter('wpo_minify_get_css', array($this, 'replace_gfont_urls_with_local'));
72 + }
73 +
68 74 if ($this->options['enable_css']) {
69 75 $this->process_css();
70 76 }
71 77
@@ -74,9 +80,9 @@
74 80 add_action('wp_head', array($this, 'add_assets_preload'), 2);
75 81 }
76 82
77 83 if ($this->should_process_html()) {
78 - add_action('template_redirect', array('WP_Optimize_Minify_Functions', 'html_compression_start'), 9);
84 + add_action('template_redirect', array('WP_Optimize_Minify_Functions', 'html_compression_start'));
79 85 }
80 86
81 87 if ($this->should_use_loadCSS()) {
82 88 add_action('wp_footer', array('WP_Optimize_Minify_Print', 'add_load_css'), PHP_INT_MAX);
@@ -85,14 +91,24 @@
85 91 $this->remove_query_string_from_static_assets();
86 92 }
87 93
88 94 /**
95 + * Replace Google fonts urls to local versions
96 + *
97 + * @param string $content
98 + * @return string
99 + */
100 + public function replace_gfont_urls_with_local($content): string {
101 + return WP_Optimize_Host_Google_Fonts::instance()->replace_gfont_urls_with_local($content);
102 + }
103 +
104 + /**
89 105 * Detects whether cache preloading is running or not
90 106 *
91 107 * @return bool
92 108 */
93 109 private function is_cache_preload() {
94 - return isset($_SERVER['HTTP_X_WP_OPTIMIZE_CACHE_PRELOAD']) && 0 === strcmp($_SERVER['HTTP_X_WP_OPTIMIZE_CACHE_PRELOAD'], 'Yes');
110 + return isset($_SERVER['HTTP_X_WP_OPTIMIZE_CACHE_PRELOAD']) && 0 === strcmp(sanitize_text_field(wp_unslash($_SERVER['HTTP_X_WP_OPTIMIZE_CACHE_PRELOAD'])), 'Yes');
95 111 }
96 112
97 113 /**
98 114 * Set initial values for the meta log object
@@ -108,9 +124,9 @@
108 124 );
109 125 }
110 126
111 127 /**
112 - * Wether to run the feature on a page or not
128 + * Whether to run the feature on a page or not
113 129 *
114 130 * @param string $context - Optional, The context where the check is done
115 131 * @return boolean
116 132 */
@@ -115,14 +131,14 @@
115 131 * @return boolean
116 132 */
117 133 public function run_on_page($context = 'default') {
118 134 /**
119 - * Filters wether the functionality is ran on the current page.
135 + * Filters whether the functionality is run on the current page.
120 136 *
121 137 * @param boolean $run_on_page
122 138 * @param string $context - Optional, The feature where the check is done
123 139 */
124 - return apply_filters(
140 + $filtered_value = apply_filters(
125 141 'wpo_minify_run_on_page',
126 142 !is_admin()
127 143 && (!defined('SCRIPT_DEBUG') || !SCRIPT_DEBUG)
128 144 && !is_preview()
@@ -131,19 +147,20 @@
131 147 && !(function_exists('is_amp_endpoint') && is_amp_endpoint())
132 148 && !WP_Optimize_Minify_Functions::exclude_contents(),
133 149 $context
134 150 );
151 + return is_bool($filtered_value) ? $filtered_value : false;
135 152 }
136 153
137 154 /**
138 155 * Inline css in place, instead of inlining the large file
139 156 *
140 - * @param String $html
141 - * @param String $handle
142 - * @param String $href
143 - * @param String $media
157 + * @param string $html
158 + * @param string $handle
159 + * @param string $href
160 + * @param mixed $media
144 161 *
145 - * @return String
162 + * @return string|boolean
146 163 */
147 164 public function inline_css($html, $handle, $href, $media) {
148 165 $exclude_css = $this->get_excluded_css_list();
149 166 $ignore_list = WP_Optimize_Minify_Functions::compile_ignore_list($exclude_css);
@@ -154,9 +171,9 @@
154 171 // make sure href is complete
155 172 $href = WP_Optimize_Minify_Functions::get_hurl($href);
156 173
157 174 if ($this->options['debug']) {
158 - echo "<!-- wpo_min DEBUG: Inline CSS processing start $handle / $href -->\n";
175 + echo "<!-- wpo_min DEBUG: Inline CSS processing start ". esc_html($handle) . " / " . esc_html($href) . " -->\n";
159 176 }
160 177
161 178
162 179 // skip all this, if the async css option is enabled
@@ -166,17 +183,16 @@
166 183 // leave conditionals alone
167 184 if (wp_styles()->get_data($handle, 'conditional')) return $html;
168 185
169 186 // mediatype fix for some plugins + remove print mediatypes
170 - if ('screen' == $media
171 - || 'screen, print' == $media
172 - || empty($media)
173 - || is_null($media)
174 - || false == $media
187 + if (!is_string($media)
188 + || '' === $media
189 + || 'screen' === $media
190 + || 'screen, print' === $media
175 191 ) {
176 192 $media = 'all';
177 193 }
178 - if (!empty($this->options['remove_print_mediatypes']) && 'print' == $media) {
194 + if (!empty($this->options['remove_print_mediatypes']) && 'print' === $media) {
179 195 return false;
180 196 }
181 197
182 198 // Exclude specific CSS files from PageSpeedInsights?
@@ -192,12 +208,17 @@
192 208 if (count($master_ignore) > 0 && WP_Optimize_Minify_Functions::in_arrayi($href, $master_ignore)) {
193 209 return $html;
194 210 }
195 211
196 - // check if working with a font awesom link
212 + // return if already minified
213 + if (WP_Optimize_Minify_Functions::is_minified_css_js_filename($href)) {
214 + return $html;
215 + }
216 +
217 + // check if working with a font awesome link
197 218 if (WP_Optimize_Minify_Functions::is_font_awesome($href)) {
198 219 // font awesome processing, async css
199 - if ('async' == $this->options['fawesome_method']) {
220 + if ('async' === $this->options['fawesome_method']) {
200 221 WP_Optimize_Minify_Print::async_style($href, $media);
201 222 return false;
202 223 } elseif ('exclude' === $this->options['fawesome_method']) {
203 224 // font awesome processing, async and exclude from PageSpeedIndex
@@ -202,17 +223,19 @@
202 223 } elseif ('exclude' === $this->options['fawesome_method']) {
203 224 // font awesome processing, async and exclude from PageSpeedIndex
204 225 WP_Optimize_Minify_Print::exclude_style($href);
205 226 return false;
206 - } elseif ('inline' == $this->options['fawesome_method']) {
227 + } elseif ('inline' === $this->options['fawesome_method']) {
207 228 WP_Optimize_Minify_Print::inline_style($handle, $href);
208 229 return false;
209 230 }
210 231 }
211 232
212 - // Check if working with google font url
233 + // Check if working with Google font url
213 234
214 - if ('fonts.googleapis.com' == parse_url($href, PHP_URL_HOST)) {
235 + if ('fonts.googleapis.com' === wp_parse_url($href, PHP_URL_HOST)) {
236 + // if option disabled google fonts processing
237 + if ($this->options['disable_google_fonts_processing']) return $html;
215 238 // check if google fonts should be removed
216 239 if ($this->options['remove_googlefonts']) return false;
217 240 // check if google fonts should be merged
218 241 if ($this->options['merge_google_fonts']) {
@@ -234,9 +257,9 @@
234 257 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
235 258 if (false === $json) {
236 259 $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $this->options['enable_css_minification'], 'css', $handle);
237 260 if ($this->options['debug']) {
238 - echo "<!-- wpo_min DEBUG: Uncached file processing now for $handle / $href -->\n";
261 + echo "<!-- wpo_min DEBUG: Uncached file processing now for " . esc_html($handle) . " / " . esc_html($href) . " -->\n";
239 262 }
240 263 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
241 264 }
242 265
@@ -243,18 +266,20 @@
243 266 // decode
244 267 $res = json_decode($json, true);
245 268
246 269 // inline css or fail
247 - if (null !== $res && false != $res['status']) {
270 + if (null !== $res && false !== $res['status']) {
248 271 // add font-display
249 272 // https://developers.google.com/web/updates/2016/02/font-display
250 273 $res['code'] = str_ireplace('font-style:normal;', 'font-display:block;font-style:normal;', $res['code']);
251 274
252 - echo '<style class="optimize_css_1" type="text/css" media="all">'.$res['code'].'</style>' . "\n";
275 + echo '<style class="optimize_css_1" type="text/css" media="all">';
276 + echo $res['code']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is already escaped
277 + echo '</style>' . "\n";
253 278 return false;
254 279 } else {
255 280 if ($this->options['debug']) {
256 - echo "<!-- wpo_min DEBUG: Google fonts request failed for $href -->\n";
281 + echo "<!-- wpo_min DEBUG: Google fonts request failed for " . esc_html($href) . " -->\n";
257 282 }
258 283 return $html;
259 284 }
260 285 } elseif ('async' === $this->options['gfonts_method']) {
@@ -286,9 +311,9 @@
286 311 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
287 312 if (false === $json) {
288 313 $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $this->options['enable_css_minification'], 'css', $handle);
289 314 if ($this->options['debug']) {
290 - echo "<!-- wpo_min DEBUG: Uncached file processing now for $handle / $href -->" . "\n";
315 + echo "<!-- wpo_min DEBUG: Uncached file processing now for " . esc_html($handle) . " / " . esc_html($href) . " -->" . "\n";
291 316 }
292 317 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
293 318 }
294 319
@@ -295,21 +320,25 @@
295 320 // decode
296 321 $res = json_decode($json, true);
297 322
298 323 // inline it + other inlined children styles
299 - if (null !== $res && false != $res['status']) {
300 - echo '<style class="optimize_css_2" type="text/css" media="'.$media.'">'.$res['code'].'</style>' . "\n";
324 + if (null !== $res && $res['status']) {
325 + echo '<style class="optimize_css_2" type="text/css" media="'.esc_attr($media).'">';
326 + echo $res['code']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is already escaped
327 + echo '</style>' . "\n";
301 328
302 329 // get inline_styles for this handle, minify and print
303 330 $inline_styles = array();
304 331 $inline_styles = wp_styles()->get_data($handle, 'after');
305 - if (false != $inline_styles) {
332 + if ($inline_styles) {
306 333
307 334 // string type
308 335 if (is_string($inline_styles)) {
309 336 $code = WP_Optimize_Minify_Functions::get_css($href, $inline_styles, $this->options['enable_css_minification']);
310 - if (!empty($code) && false != $code) {
311 - echo '<style class="optimize_css_3" type="text/css" media="'.$media.'">'.$code.'</style>' . "\n";
337 + if (!empty($code)) {
338 + echo '<style class="optimize_css_3" type="text/css" media="'.esc_attr($media).'">';
339 + echo $code; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is already escaped
340 + echo '</style>' . "\n";
312 341 }
313 342 }
314 343
315 344 // array type
@@ -315,10 +344,12 @@
315 344 // array type
316 345 if (is_array($inline_styles)) {
317 346 foreach ($inline_styles as $st) {
318 347 $code = WP_Optimize_Minify_Functions::get_css($href, $st, $this->options['enable_css_minification']);
319 - if (!empty($code) && false != $code) {
320 - echo '<style class="optimize_css_4" type="text/css" media="'.$media.'">'.$code.'</style>' . "\n";
348 + if (!empty($code)) {
349 + echo '<style class="optimize_css_4" type="text/css" media="'.esc_attr($media).'">';
350 + echo $code; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is already escaped
351 + echo '</style>' . "\n";
321 352 }
322 353 }
323 354 }
324 355 }
@@ -326,9 +357,9 @@
326 357 // prevent default
327 358 return false;
328 359 } else {
329 360 if ($this->options['debug']) {
330 - echo "<!-- wpo_min DEBUG: $handle / $href returned an empty from minification -->" . "\n";
361 + echo "<!-- wpo_min DEBUG: " . esc_html($handle) . " / " . esc_html($href) . " returned an empty from minification -->" . "\n";
331 362 }
332 363 return $html;
333 364 }
334 365 echo "<!-- ERROR: WPO-Minify couldn't catch the CSS file below. Please report this on https://wordpress.org/support/plugin/wp-optimize/ -->\n";
@@ -335,15 +366,15 @@
335 366 return $html;
336 367 }
337 368
338 369 /**
339 - * Enable defer for JavaScript (WP 4.1 and above) and remove query strings for ignored files
370 + * Enable defer for JavaScript and remove query strings for ignored and all non-minified files
340 371 *
341 - * @param String $tag
342 - * @param String $handle
343 - * @param String $src
372 + * @param string $tag
373 + * @param string $handle
374 + * @param string $src
344 375 *
345 - * @return String
376 + * @return string
346 377 */
347 378 public function defer_js($tag, $handle, $src) {
348 379 $wp_domain = trim(str_ireplace(array('http://', 'https://'), '', trim(site_url(), '/')));
349 380 $exclude_js = $this->get_excluded_js_list();
@@ -349,10 +380,11 @@
349 380 $exclude_js = $this->get_excluded_js_list();
350 381 $ignore_list = WP_Optimize_Minify_Functions::compile_ignore_list($exclude_js);
351 382 // Should this defer the Poly fills for IE?
352 383 $blacklist = WP_Optimize_Minify_Functions::get_ie_blacklist();
384 +
353 385 // no query strings
354 - if (false !== stripos($src, '?ver')) {
386 + if (false !== stripos($src, '?ver') && WP_Optimize_Minify_Functions::is_already_minified($src)) {
355 387 $srcf = stristr($src, '?ver', true);
356 388 $tag = str_ireplace($src, $srcf, $tag);
357 389 $src = $srcf;
358 390 }
@@ -387,9 +419,9 @@
387 419 }
388 420
389 421 // should we exclude defer on the login page?
390 422 if ($this->options['exclude_defer_login']
391 - && false !== stripos($_SERVER["SCRIPT_NAME"], strrchr(wp_login_url(), '/'))
423 + && isset($_SERVER['SCRIPT_NAME']) && false !== stripos(sanitize_text_field(wp_unslash($_SERVER["SCRIPT_NAME"])), strrchr(wp_login_url(), '/'))
392 424 ) {
393 425 return $tag;
394 426 }
395 427
@@ -439,11 +471,15 @@
439 471 * @return void
440 472 */
441 473 public function add_critical_path() {
442 474 if (is_front_page() && !empty($this->options['critical_path_css_is_front_page'])) {
443 - echo '<style id="critical-path-is-front-page" type="text/css" media="all">' . "\n" . $this->options['critical_path_css_is_front_page'] . "\n" . '</style>' . "\n";
475 + echo '<style id="critical-path-is-front-page" type="text/css" media="all">' . "\n";
476 + echo $this->options['critical_path_css_is_front_page'] . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is already escaped
477 + echo '</style>' . "\n";
444 478 } elseif (!empty($this->options['critical_path_css'])) {
445 - echo '<style id="critical-path-global" type="text/css" media="all">' . "\n" . $this->options['critical_path_css'] . "\n" . '</style>' . "\n";
479 + echo '<style id="critical-path-global" type="text/css" media="all">' . "\n";
480 + echo $this->options['critical_path_css'] . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is already escaped
481 + echo '</style>' . "\n";
446 482 }
447 483 }
448 484
449 485 /**
@@ -482,8 +518,9 @@
482 518 $minify_css = $this->options['enable_css_minification'];
483 519 $merge_css = $this->options['enable_merging_of_css'];
484 520 $merge_inline_extra_css_js = $this->options['merge_inline_extra_css_js'];
485 521 $process_css = $minify_css || $merge_css;
522 + $disable_google_fonts_processing = $this->options['disable_google_fonts_processing'];
486 523 $styles = clone $wp_styles;
487 524 $styles->all_deps($styles->queue);
488 525 $done = $styles->done;
489 526 $header = array();
@@ -512,9 +549,9 @@
512 549 }
513 550
514 551 // mediatype
515 552 $mt = isset($wp_styles->registered[$handle]->args) ? $wp_styles->registered[$handle]->args : 'all';
516 - if ('screen' == $mt || 'screen, print' == $mt || empty($mt) || is_null($mt) || false == $mt) {
553 + if ('screen' === $mt || 'screen, print' === $mt || empty($mt) || is_null($mt) || false === $mt) {
517 554 $mt = 'all';
518 555 }
519 556 $mediatype = $mt;
520 557
@@ -536,11 +573,15 @@
536 573 } else {
537 574 $uniq[$key] = $handle;
538 575 }
539 576 }
577 +
578 + $version = '?ver=' . (!empty($version) ? $version : $wp_styles->default_version);
579 + $href_versioned = $href . $version;
580 +
540 581 // Exclude specific CSS files from PageSpeedIndex?
541 582 if (WP_Optimize_Minify_Functions::in_arrayi($href, $async_css)) {
542 - WP_Optimize_Minify_Print::exclude_style($href);
583 + WP_Optimize_Minify_Print::exclude_style($href_versioned);
543 584 $done = array_merge($done, array($handle));
544 585 continue;
545 586 }
546 587 // Fonts Awesome Processing
@@ -545,17 +586,17 @@
545 586 }
546 587 // Fonts Awesome Processing
547 588 if (WP_Optimize_Minify_Functions::is_font_awesome($href)) {
548 589 if ('inline' === $this->options['fawesome_method']) {
549 - WP_Optimize_Minify_Print::inline_style($handle, $href);
590 + WP_Optimize_Minify_Print::inline_style($handle, $href_versioned);
550 591 $done = array_merge($done, array($handle));
551 592 continue;
552 593 } elseif ('async' === $this->options['fawesome_method']) {
553 - WP_Optimize_Minify_Print::async_style($href, $mediatype);
594 + WP_Optimize_Minify_Print::async_style($href_versioned, $mediatype);
554 595 $done = array_merge($done, array($handle));
555 596 continue;
556 597 } elseif ('exclude' === $this->options['fawesome_method']) {
557 - WP_Optimize_Minify_Print::exclude_style($href);
598 + WP_Optimize_Minify_Print::exclude_style($href_versioned);
558 599 $done = array_merge($done, array($handle));
559 600 continue;
560 601 }
561 602 }
@@ -574,9 +615,9 @@
574 615 'mediatype' => $mediatype
575 616 );
576 617
577 618 // google fonts to the top (collect and skip process array)
578 - if (WP_Optimize_Minify_Functions::is_google_font($href)) {
619 + if (!$disable_google_fonts_processing && WP_Optimize_Minify_Functions::is_google_font($href)) {
579 620 if ($this->options['remove_googlefonts']) {
580 621 $done = array_merge($done, array($handle));
581 622 continue;
582 623 }
@@ -595,9 +636,9 @@
595 636 // merge google fonts if force inlining is enabled?
596 637 $nfonts = array();
597 638 if ($this->options['merge_google_fonts']) {
598 639 $nfonts[] = WP_Optimize_Minify_Fonts::concatenate_google_fonts($google_fonts);
599 - // mark the google fonts as done so they don't get processed
640 + // mark the Google fonts as done so they don't get processed
600 641 if ('inherit' !== $this->options['gfonts_method']) {
601 642 $done = array_merge($done, array_keys($google_fonts));
602 643 }
603 644 } else {
@@ -619,9 +660,9 @@
619 660 // check if the cache is empty or has no code
620 661 if (null === $json || false === $json || empty($json['code'])) {
621 662 $res = WP_Optimize_Minify_Functions::download_and_minify($href, null, $minify_css, 'css', null);
622 663 if ($this->options['debug']) {
623 - echo "<!-- wpo_min DEBUG: Uncached file processing now for $href -->\n";
664 + echo "<!-- wpo_min DEBUG: Uncached file processing now for " . esc_html($href) . " -->\n";
624 665 }
625 666 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $res);
626 667 // decode
627 668 $json = json_decode($res, true);
@@ -631,14 +672,16 @@
631 672 if (null !== $json && !empty($json['code'])) {
632 673 // add font-display
633 674 // https://developers.google.com/web/updates/2016/02/font-display
634 675 $json['code'] = str_ireplace('font-style:normal;', 'font-display:block;font-style:normal;', $json['code']);
635 - echo '<style type="text/css" media="all">'.$json['code'].'</style>' . "\n";
676 + echo '<style type="text/css" media="all">';
677 + echo $json['code']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is already escaped
678 + echo '</style>' . "\n";
636 679 $done = array_merge($done, array($handle));
637 680 } else {
638 - echo "<!-- GOOGLE FONTS REQUEST FAILED for $href -->" . "\n";
681 + echo "<!-- GOOGLE FONTS REQUEST FAILED for " . esc_html($href) . " -->" . "\n";
639 682 // inlining failed, so enqueue again
640 - wp_enqueue_style($handle, $href, array(), null);
683 + wp_enqueue_style($handle, $href, array(), null); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Not needed as this is a google font and from cache
641 684 }
642 685 } elseif ('async' === $this->options['gfonts_method']) {
643 686 WP_Optimize_Minify_Print::async_style($href);
644 687 $done = array_merge($done, array($handle));
@@ -680,16 +723,19 @@
680 723 $file_size = WP_Optimize_Minify_Functions::get_file_size($href);
681 724
682 725 // If we can't determine file size, then we still need to proceed with normal minify process
683 726 if (!apply_filters('wp_optimize_skip_inlining', false === $file_size || $file_size > 20480 || !$this->options['inline_css'], $file_size, $href)) continue;
684 -
685 - // skip ignore list, conditional css, external css, font-awesome merge
686 - if (($process_css && !WP_Optimize_Minify_Functions::in_arrayi($href, $ignore_list) && !isset($conditional) && WP_Optimize_Minify_Functions::internal_url($href, site_url()))
727 +
728 + // check if the current URL points to a minified file.
729 + $exclude_minified_css = WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
730 + $normal_processing = $exclude_minified_css && !$merge_css;
731 + // skip ignore list, conditional css, external css, font-awesome merge and already minified js
732 + if (($process_css && !$normal_processing && !WP_Optimize_Minify_Functions::in_arrayi($href, $ignore_list) && !isset($conditional) && WP_Optimize_Minify_Functions::internal_url($href, site_url()))
687 733 || empty($href)
688 - || ($process_css && 'inherit' == $this->options['fawesome_method'] && WP_Optimize_Minify_Functions::is_font_awesome($href))
689 - || ($process_css && 'inherit' == $this->options['gfonts_method'] && WP_Optimize_Minify_Functions::is_google_font($href))
734 + || ($process_css && 'inherit' === $this->options['fawesome_method'] && WP_Optimize_Minify_Functions::is_font_awesome($href))
735 + || ($process_css && !$disable_google_fonts_processing && 'inherit' === $this->options['gfonts_method'] && WP_Optimize_Minify_Functions::is_google_font($href))
690 736 ) {
691 - // colect inline css for this handle
737 + // collect inline css for this handle
692 738 if (isset($wp_styles->registered[$handle]->extra['after']) && is_array($wp_styles->registered[$handle]->extra['after'])) {
693 739 $inline_css[$handle] = WP_Optimize_Minify_Functions::minify_css_string(implode('', $wp_styles->registered[$handle]->extra['after'])); // save
694 740 $wp_styles->registered[$handle]->extra['after'] = null; // dequeue
695 741 }
@@ -694,9 +740,9 @@
694 740 $wp_styles->registered[$handle]->extra['after'] = null; // dequeue
695 741 }
696 742
697 743 // process
698 - if (isset($header[count($header)-1]['handle']) || count($header) == 0 || $header[count($header)-1]['media'] != $mediatype || !$merge_css) {
744 + if (isset($header[count($header)-1]['handle']) || count($header) === 0 || $header[count($header)-1]['media'] !== $mediatype || !$merge_css) {
699 745 array_push($header, array('handles' => array(), 'media' => $mediatype, 'versions' => array()));
700 746 }
701 747
702 748 // push it to the array
@@ -706,11 +752,12 @@
706 752 // https://plugins.trac.wordpress.org/browser/mailin/tags/3.1.54/sendinblue.php#L456
707 753 $version_str = is_array($wp_styles->registered[$handle]->ver) ? $this->array_to_string_conversion($wp_styles->registered[$handle]->ver) : $wp_styles->registered[$handle]->ver;
708 754 array_push($header[count($header)-1]['versions'], $version_str);
709 755
756 + $header[count($header) - 1]['last_modified'][] = WP_Optimize_Minify_Functions::get_modification_time($wp_styles->registered[$handle]->src);
757 +
710 758 // external and ignored css
711 759 } else {
712 -
713 760 // normal enqueuing
714 761 array_push($header, array('handle' => $handle));
715 762 }
716 763 }
@@ -725,25 +772,29 @@
725 772 $header = apply_filters('wpo_minify_stylesheets', $header, 'header');
726 773
727 774 // loop through header css and merge
728 775 for ($i=0,$l=count($header); $i<$l; $i++) {
776 +
729 777 if (!isset($header[$i]['handle'])) {
778 +
779 + $handle_str = is_array($header[$i]['handles']) ? $this->array_to_string_conversion($header[$i]['handles']) : strval($header[$i]['handles']);
780 + $last_modified_str = empty($header[$i]['last_modified']) ? '' : (is_array($header[$i]['last_modified']) ? $this->array_to_string_conversion($header[$i]['last_modified']) : strval($header[$i]['last_modified']));
781 +
730 782 if ($merge_css) {
731 783 // get hash for the inline css in this group
732 784 $inline_css_group = array();
733 - foreach ($header[$i]['handles'] as $h) {
734 - if (!empty($inline_css) && isset($inline_css[$h]) && !empty($inline_css[$h])) {
735 - $inline_css_group[] = $inline_css[$h];
785 +
786 + if (is_array($header[$i]['handles'])) {
787 + foreach ($header[$i]['handles'] as $h) {
788 + if (!empty($inline_css) && isset($inline_css[$h]) && !empty($inline_css[$h])) {
789 + $inline_css_group[] = $inline_css[$h];
790 + }
736 791 }
737 792 }
738 793 $inline_css_hash = md5(implode('', $inline_css_group));
739 - // We need this because some plugins/theme use empty array as version
740 - // https://plugins.trac.wordpress.org/browser/mailin/tags/3.1.54/sendinblue.php#L456
741 - $version_str = $this->array_to_string_conversion($header[$i]['versions']);
742 - $handle_str = $this->array_to_string_conversion($header[$i]['handles']);
743 - $hash = hash('adler32', $handle_str . $inline_css_hash . $version_str);
794 + $hash = hash('adler32', $handle_str . $inline_css_hash . $last_modified_str);
744 795 } else {
745 - $hash = implode('', $header[$i]['handles']) . implode('', $header[$i]['versions']);
796 + $hash = sanitize_file_name($handle_str . $last_modified_str);
746 797 }
747 798
748 799 // static cache file info
749 800 $file_name = 'wpo-minify-header-'.$hash.($minify_css ? '.min' : '');
@@ -757,9 +808,9 @@
757 808 clearstatcache();
758 809 if (!file_exists($file)) {
759 810
760 811 // code and log initialization
761 - $log_header = "PROCESSED on ".date('r')." from ".home_url(add_query_arg(null, null));
812 + $log_header = $this->get_log_header();
762 813 $log = array(
763 814 'header' => $log_header,
764 815 'files' => array()
765 816 );
@@ -770,10 +821,12 @@
770 821 foreach ($header[$i]['handles'] as $handle) {
771 822 if (!empty($wp_styles->registered[$handle]->src)) {
772 823
773 824 // get href per handle
774 - $href = WP_Optimize_Minify_Functions::get_hurl($wp_styles->registered[$handle]->src);
825 + $handle_src = $wp_styles->registered[$handle]->src;
826 + $href = WP_Optimize_Minify_Functions::get_hurl($handle_src);
775 827 $version = $wp_styles->registered[$handle]->ver;
828 + $last_modified = WP_Optimize_Minify_Functions::get_modification_time($handle_src);
776 829
777 830 // inlined scripts without file
778 831 if (empty($href)) continue;
779 832
@@ -781,11 +834,12 @@
781 834 $tkey = 'css-'.hash('adler32', $handle . $href).'.css';
782 835 $json = false;
783 836 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
784 837 if (false === $json) {
785 - $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $this->options['enable_css_minification'], 'css', $handle, $version);
838 + $enable_minification = $this->options['enable_css_minification'] && !WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
839 + $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $enable_minification, 'css', $handle, $version);
786 840 if ($this->options['debug']) {
787 - echo "<!-- wpo_min DEBUG: Uncached file processing now for $handle / $href / $version -->" . "\n";
841 + echo "<!-- wpo_min DEBUG: Uncached file processing now for " . esc_html($handle) . " / " . esc_html($href) . " / " . esc_html($version) . " -->" . "\n";
788 842 }
789 843 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
790 844 }
791 845
@@ -801,10 +855,12 @@
801 855 $meta_log['files_that_changed'][$handle] = $res['log'];
802 856 }
803 857
804 858 // response has failed
805 - if (true != $res['status']) {
859 + if (true !== $res['status']) {
806 860 $log['files'][$handle] = $res['log'];
861 + $log['files'][$handle]['version'] = $version;
862 + $log['files'][$handle]['last_modified'] = $last_modified;
807 863 continue;
808 864 }
809 865
810 866 // Only add the $handle to $done if it was successfully downloaded
@@ -809,10 +865,12 @@
809 865
810 866 // Only add the $handle to $done if it was successfully downloaded
811 867 $done[] = $handle;
812 868 // append code to merged file
813 - $code .= isset($res['code']) ? $res['code'] : '';
869 + $code .= $res['code'] ?? '';
814 870 $log['files'][$handle] = $res['log'];
871 + $log['files'][$handle]['version'] = $version;
872 + $log['files'][$handle]['last_modified'] = $last_modified;
815 873
816 874 // append inlined styles
817 875 if ($merge_inline_extra_css_js && isset($inline_css[$handle]) && !empty($inline_css[$handle])) {
818 876 $code.= $inline_css[$handle];
@@ -828,9 +886,9 @@
828 886 // generate cache, write log
829 887 if (!empty($code)) {
830 888 // Only generate meta.json file if cache is reset
831 889 if (!empty($meta_log['invalidation_reason'])) {
832 - file_put_contents($meta_json_file, json_encode($meta_log));
890 + file_put_contents($meta_json_file, wp_json_encode($meta_log));
833 891 }
834 892 WP_Optimize_Minify_Print::write_combined_asset($file, $code, $log);
835 893 }
836 894 } else {
@@ -871,9 +929,9 @@
871 929 }
872 930 }
873 931 } else {
874 932 // file could not be generated, output something meaningful
875 - echo "<!-- ERROR: WP-Optimize Minify was not allowed to save its cache on - ".str_replace(ABSPATH, '', $file)." -->";
933 + echo "<!-- ERROR: WP-Optimize Minify was not allowed to save its cache on - ".esc_html(str_replace(ABSPATH, '', $file))." -->";
876 934 echo "<!-- Please check if the path above is correct and ensure your server has write permission there! -->";
877 935 }
878 936 }
879 937 // other css need to be requeued for the order of files to be kept
@@ -917,8 +975,10 @@
917 975
918 976 // mark as done (as we go)
919 977 $done = $scripts->done;
920 978
979 + $previous_load_strategy = null;
980 +
921 981 // get groups of handles
922 982 foreach ($scripts->to_do as $handle) :
923 983
924 984 // get full url
@@ -929,9 +989,9 @@
929 989 continue;
930 990 }
931 991
932 992 // Exclude JS files from PageSpeedIndex (Async) takes priority over the ignore list
933 - if (false != $async_js || is_array($async_js)) {
993 + if (!empty($async_js)) {
934 994
935 995 // check for string match
936 996 $skipjs = false;
937 997 foreach ($async_js as $l) {
@@ -936,15 +996,16 @@
936 996 $skipjs = false;
937 997 foreach ($async_js as $l) {
938 998 if (stripos($href, $l) !== false) {
939 999 // print code if there are no linebreaks, or return
940 - WP_Optimize_Minify_Print::async_script($href);
1000 + $href_versioned = $href . (!empty($wp_scripts->registered[$handle]->ver) ? '?ver=' . $wp_scripts->registered[$handle]->ver : '');
1001 + WP_Optimize_Minify_Print::async_script($href_versioned);
941 1002 $skipjs = true;
942 1003 $done = array_merge($done, array($handle));
943 1004 break;
944 1005 }
945 1006 }
946 - if (false != $skipjs) {
1007 + if (false !== $skipjs) {
947 1008 continue;
948 1009 }
949 1010 }
950 1011
@@ -953,15 +1014,24 @@
953 1014 if ($ieonly) {
954 1015 continue;
955 1016 }
956 1017
1018 + // check if the current URL points to a minified file.
1019 + $exclude_minified_js = WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
1020 + $normal_processing = $exclude_minified_js && !$merge_js;
1021 +
957 1022 // skip ignore list, scripts with conditionals, external scripts
958 - if (($process_js && !WP_Optimize_Minify_Functions::in_arrayi($href, $ignore_list) && !isset($wp_scripts->registered[$handle]->extra["conditional"]) && WP_Optimize_Minify_Functions::internal_url($href, site_url()))
1023 + if (($process_js && !$normal_processing && !WP_Optimize_Minify_Functions::in_arrayi($href, $ignore_list) && !isset($wp_scripts->registered[$handle]->extra["conditional"]) && WP_Optimize_Minify_Functions::internal_url($href, site_url()))
959 1024 || empty($href)
960 1025 ) {
961 1026
962 1027 // process
963 - if (isset($footer[count($footer)-1]['handle']) || !count($footer) || !$merge_js) {
1028 + if (isset($footer[count($footer)-1]['handle'])
1029 + || !count($footer)
1030 + || !$merge_js
1031 + || (isset($scripts->registered[$handle]->extra['strategy']) && $previous_load_strategy !== $scripts->registered[$handle]->extra['strategy'])
1032 + || (!isset($scripts->registered[$handle]->extra['strategy']) && null !== $previous_load_strategy)
1033 + ) {
964 1034 array_push($footer, array('handles' => array(), 'versions' => array()));
965 1035 }
966 1036
967 1037 if (isset($wp_scripts->registered[$handle]->extra['before'])) {
@@ -972,9 +1042,17 @@
972 1042
973 1043 // push it to the array
974 1044 array_push($footer[count($footer)-1]['handles'], $handle);
975 1045 array_push($footer[count($footer)-1]['versions'], $wp_scripts->registered[$handle]->ver);
1046 +
1047 + // Register strategy if it is used
1048 + if (isset($scripts->registered[$handle]->extra['strategy'])) $footer[count($footer)-1]['strategy'] = $scripts->registered[$handle]->extra['strategy'];
1049 +
1050 + $footer[count($footer) - 1]['last_modified'][] = WP_Optimize_Minify_Functions::get_modification_time($wp_scripts->registered[$handle]->src);
976 1051 // external and ignored scripts
1052 +
1053 + $previous_load_strategy = $scripts->registered[$handle]->extra['strategy'] ?? null;
1054 +
977 1055 } else {
978 1056 array_push($footer, array('handle' => $handle));
979 1057 }
980 1058 endforeach;
@@ -980,15 +1058,19 @@
980 1058 endforeach;
981 1059
982 1060 // loop through footer scripts and merge
983 1061 for ($i=0,$l=count($footer); $i<$l; $i++) {
1062 +
984 1063 if (!isset($footer[$i]['handle'])) {
985 1064
1065 + $handles_str = is_array($footer[$i]['handles']) ? $this->array_to_string_conversion($footer[$i]['handles']) : strval($footer[$i]['handles']);
1066 + $last_modified_str = empty($footer[$i]['last_modified']) ? '' : (is_array($footer[$i]['last_modified']) ? $this->array_to_string_conversion($footer[$i]['last_modified']) : strval($footer[$i]['last_modified']));
1067 +
986 1068 if ($merge_js) {
987 - // Change the hash based on version numbers
988 - $hash = hash('adler32', implode('', $footer[$i]['handles']) . implode('', $footer[$i]['versions']));
1069 + // Change the hash based on last modified timestamp
1070 + $hash = hash('adler32', $handles_str . $last_modified_str);
989 1071 } else {
990 - $hash = implode('', $footer[$i]['handles']) . implode('', $footer[$i]['versions']);
1072 + $hash = sanitize_file_name($handles_str . $last_modified_str);
991 1073 }
992 1074
993 1075 // static cache file info
994 1076 $file_name = 'wpo-minify-footer-'.$hash.($minify_js ? '.min' : '');
@@ -1002,9 +1084,9 @@
1002 1084 clearstatcache();
1003 1085 if (!file_exists($file)) {
1004 1086
1005 1087 // code and log initialization
1006 - $log_header = "PROCESSED on ".date('r')." from ".home_url(add_query_arg(null, null));
1088 + $log_header = $this->get_log_header();
1007 1089 $log = array(
1008 1090 'header' => $log_header,
1009 1091 'files' => array()
1010 1092 );
@@ -1019,10 +1101,12 @@
1019 1101 // only add minified scripts once to the bundle
1020 1102 if (in_array($handle, $done)) continue;
1021 1103
1022 1104 // get href per handle
1023 - $href = WP_Optimize_Minify_Functions::get_hurl($wp_scripts->registered[$handle]->src);
1105 + $handle_src = $wp_scripts->registered[$handle]->src;
1106 + $href = WP_Optimize_Minify_Functions::get_hurl($handle_src);
1024 1107 $version = $wp_scripts->registered[$handle]->ver;
1108 + $last_modified = WP_Optimize_Minify_Functions::get_modification_time($handle_src);
1025 1109 // inlined scripts without file
1026 1110 if (empty($href)) {
1027 1111 continue;
1028 1112 }
@@ -1030,11 +1114,12 @@
1030 1114 $tkey = 'js-'.hash('adler32', $handle . $href).'.js';
1031 1115 $json = false;
1032 1116 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
1033 1117 if (false === $json) {
1034 - $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $minify_js, 'js', $handle, $version);
1118 + $enable_minification = $minify_js && !WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
1119 + $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $enable_minification, 'js', $handle, $version);
1035 1120 if ($this->options['debug']) {
1036 - echo "<!-- wpo_min DEBUG: Uncached file processing now for $handle / $href / $version -->\n";
1121 + echo "<!-- wpo_min DEBUG: Uncached file processing now for " . esc_html($handle) . " / " . esc_html($href) . " / " . esc_html($version) . " -->\n";
1037 1122 }
1038 1123 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
1039 1124 }
1040 1125
@@ -1050,10 +1135,13 @@
1050 1135 $meta_log['files_that_changed'][$handle] = $res['log'];
1051 1136 }
1052 1137
1053 1138 // response has failed
1054 - if (true != $res['status']) {
1139 + if (true !== $res['status']) {
1055 1140 $log['files'][$handle] = $res['log'];
1141 + $log['files'][$handle]['uses_loading_strategy'] = isset($footer[$i]['strategy']);
1142 + $log['files'][$handle]['version'] = $version;
1143 + $log['files'][$handle]['last_modified'] = $last_modified;
1056 1144 continue;
1057 1145 }
1058 1146
1059 1147 $done[] = $handle;
@@ -1081,12 +1169,15 @@
1081 1169 }
1082 1170
1083 1171 // append code to merged file
1084 1172 $code .= $before_code . "\n";
1085 - $code .= isset($res['code']) ? $res['code'] : '';
1173 + $code .= $res['code'] ?? '';
1086 1174 $code .= "\n" . $after_code . "\n";
1087 1175 $code = WP_Optimize_Minify_Functions::prepare_merged_js($code, $href);
1088 1176 $log['files'][$handle] = $res['log'];
1177 + $log['files'][$handle]['uses_loading_strategy'] = isset($footer[$i]['strategy']);
1178 + $log['files'][$handle]['version'] = $version;
1179 + $log['files'][$handle]['last_modified'] = $last_modified;
1089 1180
1090 1181 // consider dependencies on handles with an empty src
1091 1182 } else {
1092 1183 wp_dequeue_script($handle);
@@ -1097,9 +1188,9 @@
1097 1188 // generate cache, write log
1098 1189 if (!empty($code)) {
1099 1190 // Only generate meta.json file if cache is reset
1100 1191 if (!empty($meta_log['invalidation_reason'])) {
1101 - file_put_contents($meta_json_file, json_encode($meta_log));
1192 + file_put_contents($meta_json_file, wp_json_encode($meta_log));
1102 1193 }
1103 1194 WP_Optimize_Minify_Print::write_combined_asset($file, $code, $log);
1104 1195 }
1105 1196 } else {
@@ -1123,9 +1214,9 @@
1123 1214 }
1124 1215 }
1125 1216
1126 1217 // register minified file
1127 - wp_register_script("wpo_min-footer-$i", $file_url, array(), null, false);
1218 + wp_register_script("wpo_min-footer-$i", $file_url, array(), null, false); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Not needed as this is a timestamp based cache
1128 1219
1129 1220 // add all extra data from wp_localize_script
1130 1221 $before_code = '';
1131 1222 $data = array();
@@ -1161,11 +1252,16 @@
1161 1252 wp_enqueue_script("wpo_min-footer-$i");
1162 1253 if (!empty($after_code)) {
1163 1254 wp_add_inline_script("wpo_min-footer-$i", $after_code, 'after');
1164 1255 }
1256 +
1257 + if (isset($footer[$i]['strategy'])) {
1258 + // Backward compatible way of doing this
1259 + wp_script_add_data( "wpo_min-footer-$i", 'strategy', $footer[$i]['strategy']);
1260 + }
1165 1261 } else {
1166 1262 // file could not be generated, output something meaningful
1167 - echo "<!-- ERROR: WP-Optimize Minify was not allowed to save its cache on - ".str_replace(ABSPATH, '', $file)." -->";
1263 + echo "<!-- ERROR: WP-Optimize Minify was not allowed to save its cache on - ".esc_html(str_replace(ABSPATH, '', $file))." -->";
1168 1264 echo "<!-- Please check if the path above is correct and ensure your server has write permission there! -->";
1169 1265 }
1170 1266
1171 1267 // other scripts need to be requeued for the order of files to be kept
@@ -1180,9 +1276,9 @@
1180 1276 }
1181 1277
1182 1278 /**
1183 1279 * Process header JavaScript
1184 - * Dependant on 'enable_js' option
1280 + * Dependent on 'enable_js' option
1185 1281 *
1186 1282 * @return void
1187 1283 */
1188 1284 public function process_header_scripts() {
@@ -1205,8 +1301,10 @@
1205 1301 // mark as done (as we go)
1206 1302 $done = $scripts->done;
1207 1303 $excluded_dependencies = array();
1208 1304
1305 + $previous_load_strategy = null;
1306 +
1209 1307 // Prepare and separate assets (get groups of handles)
1210 1308 foreach ($scripts->to_do as $handle) {
1211 1309 // get full url
1212 1310 $href = WP_Optimize_Minify_Functions::get_hurl($wp_scripts->registered[$handle]->src);
@@ -1211,9 +1309,9 @@
1211 1309 // get full url
1212 1310 $href = WP_Optimize_Minify_Functions::get_hurl($wp_scripts->registered[$handle]->src);
1213 1311 // inlined scripts without file
1214 1312 if (empty($href)) {
1215 - wp_enqueue_script($handle, false);
1313 + wp_enqueue_script($handle, false); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Not needed
1216 1314 continue;
1217 1315 }
1218 1316
1219 1317 // Only go through items without a group
@@ -1222,9 +1320,10 @@
1222 1320 // check for string match
1223 1321 $skipjs = false;
1224 1322 foreach ($async_js as $l) {
1225 1323 if (stripos($href, $l) !== false) {
1226 - WP_Optimize_Minify_Print::async_script($href);
1324 + $href_versioned = $href . (!empty($wp_scripts->registered[$handle]->ver) ? '?ver=' . $wp_scripts->registered[$handle]->ver : '');
1325 + WP_Optimize_Minify_Print::async_script($href_versioned);
1227 1326 $skipjs = true;
1228 1327 $done = array_merge($done, array($handle));
1229 1328 break;
1230 1329 }
@@ -1245,14 +1344,23 @@
1245 1344 ) {
1246 1345 continue;
1247 1346 }
1248 1347
1348 + // check if the current URL points to a minified file.
1349 + $exclude_minified_js = WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
1350 + $normal_processing = $exclude_minified_js && !$merge_js;
1351 +
1249 1352 // Group handles - skip ignore list, scripts with conditionals, external scripts
1250 - if (($process_js && !WP_Optimize_Minify_Functions::in_arrayi($href, $ignore_list) && !isset($wp_scripts->registered[$handle]->extra["conditional"]) && WP_Optimize_Minify_Functions::internal_url($href, site_url()))
1353 + if (($process_js && !$normal_processing && !WP_Optimize_Minify_Functions::in_arrayi($href, $ignore_list) && !isset($wp_scripts->registered[$handle]->extra["conditional"]) && WP_Optimize_Minify_Functions::internal_url($href, site_url()))
1251 1354 || empty($href)
1252 1355 ) {
1253 1356 // process
1254 - if (isset($header[count($header)-1]['handle']) || !count($header) || !$merge_js) {
1357 + if (isset($header[count($header)-1]['handle'])
1358 + || !count($header)
1359 + || !$merge_js
1360 + || (isset($scripts->registered[$handle]->extra['strategy']) && $previous_load_strategy !== $scripts->registered[$handle]->extra['strategy'])
1361 + || (!isset($scripts->registered[$handle]->extra['strategy']) && null !== $previous_load_strategy)
1362 + ) {
1255 1363 array_push($header, array('handles' => array(), 'versions' => array()));
1256 1364 }
1257 1365
1258 1366 // Force loading of dependencies
@@ -1285,9 +1393,16 @@
1285 1393
1286 1394 // push it to the array
1287 1395 array_push($header[count($header)-1]['handles'], $handle);
1288 1396 array_push($header[count($header)-1]['versions'], $scripts->registered[$handle]->ver);
1397 + $header[count($header) - 1]['last_modified'][] = WP_Optimize_Minify_Functions::get_modification_time($wp_scripts->registered[$handle]->src);
1289 1398
1399 + // Register strategy if it is used
1400 + if (isset($scripts->registered[$handle]->extra['strategy'])) $header[count($header)-1]['strategy'] = $scripts->registered[$handle]->extra['strategy'];
1401 +
1402 + $previous_load_strategy = $scripts->registered[$handle]->extra['strategy'] ?? null;
1403 +
1404 +
1290 1405 // external and ignored scripts
1291 1406 } else {
1292 1407 // add the ignored assets
1293 1408 array_push($header, array('handle' => $handle));
@@ -1294,20 +1409,24 @@
1294 1409 }
1295 1410
1296 1411 // make sure that the scripts skipped here, show up in the footer
1297 1412 } else {
1298 - wp_enqueue_script($handle, $href, array(), null, true);
1413 + wp_enqueue_script($handle, $href, array(), null, true); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Not needed as this is a timestamp based cache
1299 1414 }
1300 1415 }
1301 1416
1302 1417 // loop through header scripts and merge
1303 1418 for ($i=0,$l=count($header); $i < $l; $i++) {
1419 +
1304 1420 if (!isset($header[$i]['handle'])) {
1305 -
1421 +
1422 + $handles_str = is_array($header[$i]['handles']) ? $this->array_to_string_conversion($header[$i]['handles']) : strval($header[$i]['handles']);
1423 + $last_modified_str = empty($header[$i]['last_modified']) ? '' : (is_array($header[$i]['last_modified']) ? $this->array_to_string_conversion($header[$i]['last_modified']) : strval($header[$i]['last_modified']));
1424 +
1306 1425 if ($merge_js) {
1307 - $hash = hash('adler32', implode('', $header[$i]['handles']) . implode('', $header[$i]['versions']));
1426 + $hash = hash('adler32', $handles_str . $last_modified_str);
1308 1427 } else {
1309 - $hash = implode('', $header[$i]['handles']) . implode('', $header[$i]['versions']);
1428 + $hash = sanitize_file_name($handles_str . $last_modified_str);
1310 1429 }
1311 1430
1312 1431 // static cache file info
1313 1432 $file_name = 'wpo-minify-header-'.$hash.($minify_js ? '.min' : '');
@@ -1320,9 +1439,9 @@
1320 1439 clearstatcache();
1321 1440 if (!file_exists($file)) {
1322 1441
1323 1442 // code and log initialization
1324 - $log_header = "PROCESSED on ".date('r')." from ".home_url(add_query_arg(null, null));
1443 + $log_header = $this->get_log_header();
1325 1444 $log = array(
1326 1445 'header' => $log_header,
1327 1446 'files' => array()
1328 1447 );
@@ -1337,10 +1456,12 @@
1337 1456 // only add minified scripts once to the bundle
1338 1457 if (in_array($handle, $done)) continue;
1339 1458
1340 1459 // get href per handle
1341 - $href = WP_Optimize_Minify_Functions::get_hurl($wp_scripts->registered[$handle]->src);
1460 + $handle_src = $wp_scripts->registered[$handle]->src;
1461 + $href = WP_Optimize_Minify_Functions::get_hurl($handle_src);
1342 1462 $version = $wp_scripts->registered[$handle]->ver;
1463 + $last_modified = WP_Optimize_Minify_Functions::get_modification_time($handle_src);
1343 1464 if (empty($href)) continue;
1344 1465 // download, minify, cache
1345 1466 $tkey = 'js-'.hash('adler32', $handle . $href).'.js';
1346 1467 $json = false;
@@ -1345,11 +1466,12 @@
1345 1466 $tkey = 'js-'.hash('adler32', $handle . $href).'.js';
1346 1467 $json = false;
1347 1468 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
1348 1469 if (false === $json) {
1349 - $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $minify_js, 'js', $handle, $version);
1470 + $enable_minification = $minify_js && !WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
1471 + $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $enable_minification, 'js', $handle, $version);
1350 1472 if ($this->options['debug']) {
1351 - echo "<!-- wpo_min DEBUG: Uncached file processing now for $handle / $href / $version -->" . "\n";
1473 + echo "<!-- wpo_min DEBUG: Uncached file processing now for " . esc_html($handle) . " / " . esc_html($href) . " / " . esc_html($version) . " -->" . "\n";
1352 1474 }
1353 1475 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
1354 1476 }
1355 1477
@@ -1365,10 +1487,13 @@
1365 1487 $meta_log['files_that_changed'][$handle] = $res['log'];
1366 1488 }
1367 1489
1368 1490 // response has failed
1369 - if (true != $res['status']) {
1491 + if (true !== $res['status']) {
1370 1492 $log['files'][$handle] = $res['log'];
1493 + $log['files'][$handle]['uses_loading_strategy'] = isset($header[$i]['strategy']);
1494 + $log['files'][$handle]['version'] = $version;
1495 + $log['files'][$handle]['last_modified'] = $last_modified;
1371 1496 continue;
1372 1497 }
1373 1498
1374 1499 // Add extra data from wp_add_inline_script before
@@ -1402,8 +1527,11 @@
1402 1527 $code .= isset($res['code']) ? $res['code'] : '';
1403 1528 $code .= "\n" . $after_code . "\n";
1404 1529 $code = WP_Optimize_Minify_Functions::prepare_merged_js($code, $href);
1405 1530 $log['files'][$handle] = $res['log'];
1531 + $log['files'][$handle]['uses_loading_strategy'] = isset($header[$i]['strategy']);
1532 + $log['files'][$handle]['version'] = $version;
1533 + $log['files'][$handle]['last_modified'] = $last_modified;
1406 1534
1407 1535 // consider dependencies on handles with an empty src
1408 1536 } else {
1409 1537 wp_dequeue_script($handle);
@@ -1414,9 +1542,9 @@
1414 1542 // generate cache, write log
1415 1543 if (!empty($code)) {
1416 1544 // Only generate meta.json file if cache is reset
1417 1545 if (!empty($meta_log['invalidation_reason'])) {
1418 - file_put_contents($meta_json_file, json_encode($meta_log));
1546 + file_put_contents($meta_json_file, wp_json_encode($meta_log));
1419 1547 }
1420 1548 WP_Optimize_Minify_Print::write_combined_asset($file, $code, $log);
1421 1549 }
1422 1550 } else {
@@ -1442,9 +1570,9 @@
1442 1570 }
1443 1571
1444 1572 // register minified file
1445 1573 $dependencies = isset($excluded_dependencies[$i]) ? $excluded_dependencies[$i] : array();
1446 - wp_register_script("wpo_min-header-$i", $file_url, $dependencies, null, false);
1574 + wp_register_script("wpo_min-header-$i", $file_url, $dependencies, null, false); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Not needed as this is a timestamp based cache
1447 1575
1448 1576 // add all extra data from wp_localize_script
1449 1577 $before_code = '';
1450 1578 $data = array();
@@ -1481,11 +1609,16 @@
1481 1609 wp_enqueue_script("wpo_min-header-$i");
1482 1610 if (!empty($after_code)) {
1483 1611 wp_add_inline_script("wpo_min-header-$i", $after_code, 'after');
1484 1612 }
1613 +
1614 + if (isset($header[$i]['strategy'])) {
1615 + // Backward compatible way of doing this
1616 + wp_script_add_data( "wpo_min-header-$i", 'strategy', $header[$i]['strategy']);
1617 + }
1485 1618 } else {
1486 1619 // file could not be generated, output something meaningful
1487 - echo "<!-- ERROR: WP-Optimize minify was not allowed to save its cache on - ".str_replace(ABSPATH, '', $file)." -->";
1620 + echo "<!-- ERROR: WP-Optimize minify was not allowed to save its cache on - ".esc_html(str_replace(ABSPATH, '', $file))." -->";
1488 1621 echo "<!-- Please check if the path above is correct and ensure your server has write permission there! -->";
1489 1622 echo "<!-- If you found a bug, please report this on https://wordpress.org/support/plugin/wp-optimize/ -->";
1490 1623 }
1491 1624
@@ -1517,8 +1650,9 @@
1517 1650 $async_css = $this->get_async_css_list();
1518 1651 $minify_css = $this->options['enable_css_minification'];
1519 1652 $merge_css = $this->options['enable_merging_of_css'];
1520 1653 $process_css = $minify_css || $merge_css;
1654 + $disable_google_fonts_processing = $this->options['disable_google_fonts_processing'];
1521 1655 $log = "";
1522 1656 $code = "";
1523 1657 $styles = clone $wp_styles;
1524 1658 $styles->all_deps($styles->queue);
@@ -1537,15 +1671,15 @@
1537 1671 $wp_styles->done = $done;
1538 1672 return;
1539 1673 }
1540 1674
1541 - // dequeue and get a list of google fonts, or requeue external
1675 + // dequeue and get a list of Google fonts, or requeue external
1542 1676 foreach ($styles->to_do as $handle) {
1543 1677 $href = WP_Optimize_Minify_Functions::get_hurl($wp_styles->registered[$handle]->src);
1544 1678 // inlined scripts without file
1545 1679 if (empty($href)) continue;
1546 1680
1547 - if (WP_Optimize_Minify_Functions::is_google_font($href)) {
1681 + if (!$disable_google_fonts_processing && WP_Optimize_Minify_Functions::is_google_font($href)) {
1548 1682 wp_dequeue_style($handle);
1549 1683 if ($this->options['remove_googlefonts']) {
1550 1684 $done = array_merge($done, array($handle));
1551 1685 continue;
@@ -1606,15 +1740,14 @@
1606 1740 WP_Optimize_Minify_Print::inline_style($handle, $href);
1607 1741 $done = array_merge($done, array($handle));
1608 1742 } else {
1609 1743 // fallback, enqueue google fonts
1610 - wp_enqueue_style($handle, $href, array(), null, 'all');
1744 + wp_enqueue_style($handle, $href, array(), null, 'all'); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Not needed as this google font and from cache
1611 1745 }
1612 1746 }
1613 1747 }
1614 1748 }
1615 1749
1616 -
1617 1750 // get groups of handles
1618 1751 $uniq = array();
1619 1752 foreach ($styles->to_do as $handle) {
1620 1753
@@ -1627,11 +1760,11 @@
1627 1760 $conditional = null; if (isset($wp_styles->registered[$handle]->extra["conditional"])) {
1628 1761 $conditional = $wp_styles->registered[$handle]->extra["conditional"]; // such as ie7, ie8, ie9, etc
1629 1762 }
1630 1763
1631 - // mediatype
1764 + // media type
1632 1765 $mt = isset($wp_styles->registered[$handle]->args) ? $wp_styles->registered[$handle]->args : 'all';
1633 - if ('screen' == $mt || 'screen, print' == $mt || empty($mt) || is_null($mt) || false == $mt) {
1766 + if ('screen' === $mt || 'screen, print' === $mt || empty($mt)) {
1634 1767 $mt = 'all';
1635 1768 }
1636 1769 $mediatype = $mt;
1637 1770
@@ -1661,11 +1794,14 @@
1661 1794 if ($ieonly) {
1662 1795 continue;
1663 1796 }
1664 1797
1798 + $version = '?ver=' . (!empty($version) ? $version : $wp_styles->default_version);
1799 + $href_versioned = $href . $version;
1800 +
1665 1801 // Exclude specific CSS files from PageSpeedIndex?
1666 - if (false != $async_css && is_array($async_css) && WP_Optimize_Minify_Functions::in_arrayi($href, $async_css)) {
1667 - WP_Optimize_Minify_Print::exclude_style($href);
1802 + if (is_array($async_css) && WP_Optimize_Minify_Functions::in_arrayi($href, $async_css)) {
1803 + WP_Optimize_Minify_Print::exclude_style($href_versioned);
1668 1804 $done = array_merge($done, array($handle));
1669 1805 continue;
1670 1806 }
1671 1807
@@ -1670,17 +1806,17 @@
1670 1806 }
1671 1807
1672 1808 if (WP_Optimize_Minify_Functions::is_font_awesome($href)) {
1673 1809 if ('inline' === $this->options['fawesome_method']) {
1674 - WP_Optimize_Minify_Print::inline_style($handle, $href);
1810 + WP_Optimize_Minify_Print::inline_style($handle, $href_versioned);
1675 1811 $done = array_merge($done, array($handle));
1676 1812 continue;
1677 1813 } elseif ('async' === $this->options['fawesome_method']) {
1678 - WP_Optimize_Minify_Print::async_style($href, $mediatype);
1814 + WP_Optimize_Minify_Print::async_style($href_versioned, $mediatype);
1679 1815 $done = array_merge($done, array($handle));
1680 1816 continue;
1681 1817 } elseif ('exclude' === $this->options['fawesome_method']) {
1682 - WP_Optimize_Minify_Print::exclude_style($href);
1818 + WP_Optimize_Minify_Print::exclude_style($href_versioned);
1683 1819 $done = array_merge($done, array($handle));
1684 1820 continue;
1685 1821 }
1686 1822 }
@@ -1690,14 +1826,17 @@
1690 1826 $done = array_merge($done, array($handle));
1691 1827 continue;
1692 1828 }
1693 1829
1694 - // skip ignore list, conditional css, external css, font-awesome merge
1695 - if (($process_css && !WP_Optimize_Minify_Functions::in_arrayi($href, $ignore_list) && !isset($conditional) && WP_Optimize_Minify_Functions::internal_url($href, site_url()))
1830 + // check if the current URL points to a minified file.
1831 + $exclude_minified_css = WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
1832 + $normal_processing = $exclude_minified_css && !$merge_css;
1833 + // skip ignore list, conditional css, external css, font-awesome merge and already minified css
1834 + if (($process_css && !$normal_processing && !WP_Optimize_Minify_Functions::in_arrayi($href, $ignore_list) && !isset($conditional) && WP_Optimize_Minify_Functions::internal_url($href, site_url()))
1696 1835 || empty($href)
1697 1836 ) {
1698 1837
1699 - // colect inline css for this handle
1838 + // collect inline css for this handle
1700 1839 if (isset($wp_styles->registered[$handle]->extra['after']) && is_array($wp_styles->registered[$handle]->extra['after'])) {
1701 1840 $inline_css[$handle] = WP_Optimize_Minify_Functions::minify_css_string(implode('', $wp_styles->registered[$handle]->extra['after'])); // save
1702 1841 $wp_styles->registered[$handle]->extra['after'] = null; // dequeue
1703 1842 }
@@ -1702,9 +1841,9 @@
1702 1841 $wp_styles->registered[$handle]->extra['after'] = null; // dequeue
1703 1842 }
1704 1843
1705 1844 // process
1706 - if (isset($footer[count($footer)-1]['handle']) || !count($footer) || $footer[count($footer)-1]['media'] != $wp_styles->registered[$handle]->args || !$merge_css) {
1845 + if (isset($footer[count($footer)-1]['handle']) || !count($footer) || $footer[count($footer)-1]['media'] !== $wp_styles->registered[$handle]->args || !$merge_css) {
1707 1846 array_push($footer, array('handles' => array(), 'media' => $mediatype, 'versions' => array()));
1708 1847 }
1709 1848
1710 1849 // push it to the array get latest modified time
@@ -1709,8 +1848,9 @@
1709 1848
1710 1849 // push it to the array get latest modified time
1711 1850 array_push($footer[count($footer)-1]['handles'], $handle);
1712 1851 array_push($footer[count($footer)-1]['versions'], $version);
1852 + $footer[count($footer) - 1]['last_modified'][] = WP_Optimize_Minify_Functions::get_modification_time($wp_styles->registered[$handle]->src);
1713 1853
1714 1854 // external and ignored css
1715 1855 } else {
1716 1856
@@ -1729,21 +1869,28 @@
1729 1869 $footer = apply_filters('wpo_minify_stylesheets', $footer, 'footer');
1730 1870
1731 1871 // loop through footer css and merge
1732 1872 for ($i=0,$l=count($footer); $i<$l; $i++) {
1873 +
1733 1874 if (!isset($footer[$i]['handle'])) {
1875 +
1876 + $handles_str = is_array($footer[$i]['handles']) ? $this->array_to_string_conversion($footer[$i]['handles']) : strval($footer[$i]['handles']);
1877 + $last_modified_str = empty($footer[$i]['last_modified']) ? '' : (is_array($footer[$i]['last_modified']) ? $this->array_to_string_conversion($footer[$i]['last_modified']) : strval($footer[$i]['last_modified']));
1878 +
1734 1879 if ($merge_css) {
1735 1880 // get hash for the inline css in this group
1736 1881 $inline_css_group = array();
1737 - foreach ($footer[$i]['handles'] as $h) {
1738 - if (isset($inline_css[$h]) && !empty($inline_css[$h])) {
1739 - $inline_css_group[] = $inline_css[$h];
1882 + if (is_array($footer[$i]['handles'])) {
1883 + foreach ($footer[$i]['handles'] as $h) {
1884 + if (isset($inline_css[$h]) && !empty($inline_css[$h])) {
1885 + $inline_css_group[] = $inline_css[$h];
1886 + }
1740 1887 }
1741 1888 }
1742 1889 $inline_css_hash = md5(implode('', $inline_css_group));
1743 - $hash = hash('adler32', implode('', $footer[$i]['handles']) . $inline_css_hash . implode('', $footer[$i]['versions']));
1890 + $hash = hash('adler32', $handles_str . $inline_css_hash . $last_modified_str);
1744 1891 } else {
1745 - $hash = implode('', $footer[$i]['handles']) . implode('', $footer[$i]['versions']);
1892 + $hash = sanitize_file_name($handles_str . $last_modified_str);
1746 1893 }
1747 1894
1748 1895 // static cache file info
1749 1896 $file_name = 'wpo-minify-footer-'.$hash.($minify_css ? '.min' : '');
@@ -1757,9 +1904,9 @@
1757 1904 clearstatcache();
1758 1905 if (!file_exists($file)) {
1759 1906
1760 1907 // code and log initialization
1761 - $log_header = "PROCESSED on ".date('r')." from ".home_url(add_query_arg(null, null));
1908 + $log_header = $this->get_log_header();
1762 1909 $log = array(
1763 1910 'header' => $log_header,
1764 1911 'files' => array()
1765 1912 );
@@ -1770,11 +1917,13 @@
1770 1917 foreach ($footer[$i]['handles'] as $handle) {
1771 1918 if (!empty($wp_styles->registered[$handle]->src)) {
1772 1919
1773 1920 // get href per handle
1774 - $href = WP_Optimize_Minify_Functions::get_hurl($wp_styles->registered[$handle]->src);
1921 + $handle_src = $wp_styles->registered[$handle]->src;
1922 + $href = WP_Optimize_Minify_Functions::get_hurl($handle_src);
1775 1923 $version = $wp_styles->registered[$handle]->ver;
1776 - // inlined scripts without hreffile
1924 + $last_modified = WP_Optimize_Minify_Functions::get_modification_time($handle_src);
1925 + // inlined scripts without href file
1777 1926 if (empty($href)) continue;
1778 1927
1779 1928 // download, minify, cache
1780 1929 $tkey = 'css-'.hash('adler32', $handle . $href).'.css';
@@ -1780,11 +1929,12 @@
1780 1929 $tkey = 'css-'.hash('adler32', $handle . $href).'.css';
1781 1930 $json = false;
1782 1931 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
1783 1932 if (false === $json) {
1784 - $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $minify_css, 'css', $handle, $version);
1933 + $enable_minification = $minify_css && !WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
1934 + $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $enable_minification, 'css', $handle, $version);
1785 1935 if ($this->options['debug']) {
1786 - echo "<!-- wpo_min DEBUG: Uncached file processing now for $handle / $href / $version -->" . "\n";
1936 + echo "<!-- wpo_min DEBUG: Uncached file processing now for " . esc_html($handle) . " / " . esc_html($href) . " / " . esc_html($version) . " -->" . "\n";
1787 1937 }
1788 1938 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
1789 1939 }
1790 1940
@@ -1800,10 +1950,12 @@
1800 1950 $meta_log['files_that_changed'][$handle] = $res['log'];
1801 1951 }
1802 1952
1803 1953 // response has failed
1804 - if (true != $res['status']) {
1954 + if (true !== $res['status']) {
1805 1955 $log['files'][$handle] = $res['log'];
1956 + $log['files'][$handle]['version'] = $version;
1957 + $log['files'][$handle]['last_modified'] = $last_modified;
1806 1958 continue;
1807 1959 }
1808 1960
1809 1961 $done[] = $handle;
@@ -1808,10 +1960,12 @@
1808 1960
1809 1961 $done[] = $handle;
1810 1962
1811 1963 // append code to merged file
1812 - $code .= isset($res['code']) ? $res['code'] : '';
1964 + $code .= $res['code'] ?? '';
1813 1965 $log['files'][$handle] = $res['log'];
1966 + $log['files'][$handle]['version'] = $version;
1967 + $log['files'][$handle]['last_modified'] = $last_modified;
1814 1968
1815 1969 // append inlined styles
1816 1970 if (isset($inline_css[$handle]) && !empty($inline_css[$handle])) {
1817 1971 $code.= $inline_css[$handle];
@@ -1821,15 +1975,15 @@
1821 1975 } else {
1822 1976 wp_dequeue_script($handle);
1823 1977 wp_enqueue_script($handle);
1824 1978 }
1825 - };
1979 + }
1826 1980
1827 1981 // generate cache, add inline css, write log
1828 1982 if (!empty($code)) {
1829 1983 // Only generate meta.json file if cache is reset
1830 1984 if (!empty($meta_log['invalidation_reason'])) {
1831 - file_put_contents($meta_json_file, json_encode($meta_log));
1985 + file_put_contents($meta_json_file, wp_json_encode($meta_log));
1832 1986 }
1833 1987 WP_Optimize_Minify_Print::write_combined_asset($file, $code, $log);
1834 1988 }
1835 1989 } else {
@@ -1865,13 +2019,13 @@
1865 2019 if (filesize($file) < 20000 && $this->options['inline_css']) {
1866 2020 $this->inline_css(file_get_contents($file), $handle, $file_url, $footer[$i]['media']);
1867 2021 } else {
1868 2022 // enqueue it
1869 - wp_enqueue_style("wpo_min-footer-$i", $file_url, array(), null, $footer[$i]['media']);
2023 + wp_enqueue_style("wpo_min-footer-$i", $file_url, array(), null, $footer[$i]['media']); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Not needed as this is a timestamp based cache
1870 2024 }
1871 2025 } else {
1872 2026 // file could not be generated, output something meaningful
1873 - echo "<!-- ERROR: WP-Optimize Minify was not allowed to save its cache on - ".str_replace(ABSPATH, '', $file)." -->";
2027 + echo "<!-- ERROR: WP-Optimize Minify was not allowed to save its cache on - ".esc_html(str_replace(ABSPATH, '', $file))." -->";
1874 2028 echo "<!-- Please check if the path above is correct and ensure your server has write permission there! -->";
1875 2029 }
1876 2030 }
1877 2031
@@ -1886,8 +2040,129 @@
1886 2040 $wp_styles->done = $done;
1887 2041 }
1888 2042
1889 2043 /**
2044 + * Process JS Scripts of type module
2045 + *
2046 + * @param string $buffer Page HTML.
2047 + *
2048 + * @return string
2049 + */
2050 + public function process_script_modules($buffer) {
2051 +
2052 + if ('' === $buffer) return '';
2053 +
2054 + if (!WP_Optimize_Utils::is_valid_html($buffer)) return $buffer;
2055 +
2056 + $minify_js = $this->options['enable_js_minification'];
2057 + $cache_path = WP_Optimize_Minify_Cache_Functions::cache_path();
2058 + $cache_dir = $cache_path['cachedir'];
2059 + $cache_dir_url = $cache_path['cachedirurl'];
2060 + $cache_base_dir = $cache_path['cachebasedir'];
2061 +
2062 + $scripts = $this->get_scripts($buffer);
2063 + if (empty($scripts)) return $buffer;
2064 +
2065 + foreach ($scripts as $script) {
2066 + if ("module" !== $script['type']) continue;
2067 +
2068 + $href = WP_Optimize_Minify_Functions::get_hurl($script['url']);
2069 + if (WP_Optimize_Minify_Functions::is_minified_css_js_filename($href)) continue;
2070 +
2071 + $asset_content = WP_Optimize_Minify_Functions::get_asset_content($href);
2072 + $code = $asset_content['content'];
2073 +
2074 +
2075 + if (WP_Optimize_Minify_Functions::has_js_import_statements($code)) {
2076 + // If the module script contains import statements, we cannot safely minify or cache it, so skip it.
2077 + continue;
2078 + }
2079 +
2080 + $last_modified = WP_Optimize_Minify_Functions::get_modification_time($script['url']);
2081 + $handle = $script['handle'];
2082 + $version = $script['version'];
2083 +
2084 + // Module script handles use slashes and @ symbols,
2085 + // replace them with '-' and empty string, break if handle is still ''
2086 + if (!empty($handle)) {
2087 + $handle_no_slash = str_replace(array('/', '@'), array('-', ''), $handle);
2088 + } else {
2089 + continue;
2090 + }
2091 +
2092 + // code and log initialization
2093 + $log_header = $this->get_log_header();
2094 + $log = array(
2095 + 'header' => $log_header,
2096 + 'files' => array()
2097 + );
2098 + $meta_log = $this->meta_log_initialization($log_header);
2099 + $code = '';
2100 +
2101 + // create cache files and urls
2102 + $file_name = 'wpo-minify-'.$handle_no_slash.($minify_js ? '.min' : '');
2103 + $file = $cache_dir.'/'.$file_name.'.js';
2104 + $meta_json_file = $cache_base_dir.'/'.'meta.json';
2105 + $file_url = WP_Optimize_Minify_Functions::get_protocol($cache_dir_url.'/'.$file_name.'.js');
2106 +
2107 + // download, minify, cache
2108 + $tkey = 'js-'.hash('adler32', $handle_no_slash . $href).'.js';
2109 + $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
2110 + if (false === $json) {
2111 + $enable_minification = $minify_js && !WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
2112 + $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $enable_minification, 'js', $handle_no_slash, $version);
2113 + if ($this->options['debug']) {
2114 + $buffer .= "<!-- wpo_min DEBUG: Uncached file processing now for " . esc_html($handle) . " / " . esc_html($href) . " / " . esc_html($version) . " -->\n";
2115 + }
2116 + WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
2117 + }
2118 +
2119 + // decode
2120 + $res = json_decode($json, true);
2121 +
2122 + if (null === $res) continue;
2123 +
2124 + // Reset minified script module
2125 + if ($this->should_reset_minify_assets($res, $href, 'js', $handle, $version)) {
2126 + WP_Optimize_Minify_Cache_Functions::reset();
2127 + $this->minify_cache_incremented = true;
2128 + $meta_log['invalidation_reason'] = 'Checksum Mismatch and version changed from ' . $res['request']['version'] . ' to ' . $version;
2129 + $meta_log['files_that_changed'][$handle] = $res['log'];
2130 + }
2131 +
2132 + if (!$res['status']) continue;
2133 +
2134 + $code .= $res['code'] ?? '';
2135 + $code = WP_Optimize_Minify_Functions::prepare_merged_js($code, $href);
2136 + $log['files'][$handle] = $res['log'];
2137 + $log['files'][$handle]['version'] = $version;
2138 + $log['files'][$handle]['last_modified'] = $last_modified;
2139 +
2140 + // If code is empty (nothing to minify) break loop
2141 + if (empty($code)) continue;
2142 +
2143 + // Only generate meta.json file if cache is reset
2144 + if (!empty($meta_log['invalidation_reason'])) {
2145 + file_put_contents($meta_json_file, wp_json_encode($meta_log));
2146 + }
2147 + WP_Optimize_Minify_Print::write_combined_asset($file, $code, $log);
2148 +
2149 + // Extract importmap script tag
2150 + $json_map = $this->get_script_module_importmap($buffer);
2151 + $json_map_update = $json_map;
2152 +
2153 + // Update module source file and importmap with new file url (if necessary)
2154 + $buffer = str_replace($script['url'], $file_url, $buffer);
2155 + if (!empty($json_map) && isset($json_map['imports'][$handle])) {
2156 + $json_map_update['imports'][$handle] = $file_url;
2157 + $buffer = str_replace(wp_json_encode($json_map), wp_json_encode($json_map_update), $buffer);
2158 + }
2159 + }
2160 +
2161 + return $buffer;
2162 + }
2163 +
2164 + /**
1890 2165 * Orders the CSS per media type
1891 2166 *
1892 2167 * @param array $list - The list of assets
1893 2168 * @return array
@@ -1931,9 +2206,9 @@
1931 2206 * @return void;
1932 2207 */
1933 2208 public function add_google_fonts_merged() {
1934 2209 // must have something to do
1935 - if (count($this->collect_google_fonts) == 0) return;
2210 + if (count($this->collect_google_fonts) === 0) return;
1936 2211
1937 2212 // merge google fonts
1938 2213 $href = WP_Optimize_Minify_Fonts::concatenate_google_fonts($this->collect_google_fonts);
1939 2214 if (empty($href)) {
@@ -1979,14 +2254,19 @@
1979 2254 // always false for admin pages
1980 2255 if (is_admin()) return false;
1981 2256
1982 2257 // get host with multisite support and query strings
1983 - $host = htmlentities($_SERVER['SERVER_NAME']);
2258 + $host = isset($_SERVER['SERVER_NAME']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_NAME'])) : '';
1984 2259 if (empty($host)) {
1985 - $host = htmlentities($_SERVER['HTTP_HOST']);
2260 + $host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '';
1986 2261 }
1987 - $request_query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
1988 - $request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
2262 +
2263 + $request_query = '';
2264 + $request_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : '';
2265 + if (!empty($request_uri)) {
2266 + $request_query = wp_parse_url($request_uri, PHP_URL_QUERY);
2267 + $request_uri = wp_parse_url($request_uri, PHP_URL_PATH);
2268 + }
1989 2269
1990 2270 // initialize headers
1991 2271 $headers = array();
1992 2272
@@ -1994,9 +2274,9 @@
1994 2274 if ($this->options['enabled_css_preload']
1995 2275 && count($this->collect_preload_css) > 0
1996 2276 ) {
1997 2277 foreach ($this->collect_preload_css as $u) {
1998 - // filter out footer footer files, because they are not in the critical path
2278 + // filter out footer files, because they are not in the critical path
1999 2279 if (strpos($u, '/assets/wpo-minify-footer-') !== false) {
2000 2280 continue;
2001 2281 }
2002 2282
@@ -2010,9 +2290,9 @@
2010 2290 && count($this->collect_preload_js) > 0
2011 2291 ) {
2012 2292 foreach ($this->collect_preload_js as $u) {
2013 2293
2014 - // filter out footer footer files, because they are not in the critical path
2294 + // filter out footer files, because they are not in the critical path
2015 2295 if (false !== strpos($u, '/assets/wpo-minify-footer-')) {
2016 2296 continue;
2017 2297 }
2018 2298
@@ -2021,9 +2301,9 @@
2021 2301 }
2022 2302 }
2023 2303
2024 2304 // must have something
2025 - if (count($headers) == 0) {
2305 + if (count($headers) === 0) {
2026 2306 return false;
2027 2307 } else {
2028 2308 $headers = implode("\n", $headers);
2029 2309 }
@@ -2039,9 +2319,9 @@
2039 2319 // reset file cache
2040 2320 clearstatcache();
2041 2321
2042 2322 // if there are no query strings
2043 - if ($b == $a) {
2323 + if ($b === $a) {
2044 2324 if (!file_exists($a)) {
2045 2325 WP_Optimize_Minify_Print::write_header($a, $headers);
2046 2326 }
2047 2327 return false;
@@ -2054,13 +2334,13 @@
2054 2334
2055 2335 /**
2056 2336 * Collect all wpo_min JS files and save them to a headers file
2057 2337 *
2058 - * @param String $html
2059 - * @param String $handle
2060 - * @param String $src
2338 + * @param string $html
2339 + * @param string $handle
2340 + * @param string $src
2061 2341 *
2062 - * @return String
2342 + * @return string
2063 2343 */
2064 2344 public function collect_js_preload_headers($html, $handle, $src) {
2065 2345 if (false !== strpos($src, 'assets/wpo-minify')) {
2066 2346 if (!in_array($src, $this->collect_preload_js)) {
@@ -2107,14 +2387,18 @@
2107 2387 return false;
2108 2388 }
2109 2389
2110 2390 // get host with multisite support and query strings
2111 - $host = htmlentities($_SERVER['SERVER_NAME']);
2391 + $host = isset($_SERVER['SERVER_NAME']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_NAME'])) : '';
2112 2392 if (empty($host)) {
2113 - $host = htmlentities($_SERVER['HTTP_HOST']);
2393 + $host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '';
2114 2394 }
2115 - $request_query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
2116 - $request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
2395 + $request_query = '';
2396 + $request_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : '';
2397 + if (!empty($request_uri)) {
2398 + $request_query = wp_parse_url($request_uri, PHP_URL_QUERY);
2399 + $request_uri = wp_parse_url($request_uri, PHP_URL_PATH);
2400 + }
2117 2401
2118 2402 // get cache path
2119 2403 $cache_path = WP_Optimize_Minify_Cache_Functions::cache_path();
2120 2404 $header_dir = $cache_path['headerdir'];
@@ -2127,12 +2411,12 @@
2127 2411 // reset file cache
2128 2412 clearstatcache();
2129 2413
2130 2414 // return header files or fallback
2131 - if ($b == $a && file_exists($a)) {
2415 + if ($b === $a && file_exists($a)) {
2132 2416 return file_get_contents($a);
2133 2417 }
2134 - if ($b != $a && file_exists($b)) {
2418 + if ($b !== $a && file_exists($b)) {
2135 2419 return file_get_contents($b);
2136 2420 }
2137 2421
2138 2422 return false;
@@ -2138,9 +2422,9 @@
2138 2422 return false;
2139 2423 }
2140 2424
2141 2425 /**
2142 - * Add pre-connect and pre-load headers
2426 + * Add pre-connect and preload headers
2143 2427 *
2144 2428 * @return void
2145 2429 */
2146 2430 public function extra_preload_headers() {
@@ -2149,9 +2433,9 @@
2149 2433 // fetch headers
2150 2434 $pre_connect = $this->get_pre_connect_list();
2151 2435
2152 2436 // preload
2153 - if (is_array($pre_connect) && count($pre_connect) > 0) {
2437 + if (count($pre_connect) > 0) {
2154 2438 foreach ($pre_connect as $url) {
2155 2439 if (!empty($url) && filter_var($url, FILTER_VALIDATE_URL)) {
2156 2440 header("Link: <$url>; rel=preconnect", false);
2157 2441 }
@@ -2158,9 +2442,9 @@
2158 2442 }
2159 2443 }
2160 2444
2161 2445 $headers = $this->get_preload_headers();
2162 - if (false != $headers) {
2446 + if ($headers) {
2163 2447 $nh = array_map('trim', explode("\n", $headers));
2164 2448 foreach ($nh as $h) {
2165 2449 if (!empty($h)) {
2166 2450 header($h, false);
@@ -2219,15 +2503,15 @@
2219 2503 /**
2220 2504 * Handles header meta information removal
2221 2505 */
2222 2506 private function remove_header_meta_info() {
2223 - // no resource hints, generator tag, shortlinks, manifest link, etc
2507 + // no resource hints, generator tag, shortlink, manifest link, etc
2224 2508 remove_action('wp_head', 'wp_resource_hints', 2);
2225 2509 remove_action('wp_head', 'wp_generator');
2226 2510 remove_action('template_redirect', 'wp_shortlink_header', 11);
2227 2511 remove_action('wp_head', 'wlwmanifest_link');
2228 2512 remove_action('wp_head', 'rsd_link');
2229 - remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
2513 + remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
2230 2514 remove_action('wp_head', 'feed_links', 2);
2231 2515 remove_action('wp_head', 'feed_links_extra', 3);
2232 2516 WP_Optimize_Minify_Functions::remove_redundant_shortlink();
2233 2517 }
@@ -2253,11 +2537,65 @@
2253 2537 || ( 'all' === $this->options['enable_defer_js'] && 'async_using_js' === $this->options['defer_js_type'] )
2254 2538 ) {
2255 2539 add_action('wp_head', array('WP_Optimize_Minify_Print', 'add_load_async'), 0);
2256 2540 }
2541 +
2542 + // Process script module from generated html
2543 + ob_start(array($this, "process_script_modules"));
2257 2544 }
2258 2545
2259 2546 /**
2547 + * Extract scripts tags from html buffer using regex
2548 + *
2549 + * @param string $html - HTML document as string
2550 + * @return array
2551 + */
2552 + private function get_scripts($html) {
2553 +
2554 + preg_match_all('/<script([^>]*)>/Umi', $html, $script_matches, PREG_SET_ORDER);
2555 +
2556 + $modified_script_matches = array();
2557 + foreach ($script_matches as $script) {
2558 + $script['url'] = '';
2559 + $script['handle'] = '';
2560 + $script['version'] = '';
2561 + $script['type'] = '';
2562 + $attributes = WP_Optimize_Utils::parse_attributes($script[1]);
2563 +
2564 + if (isset($attributes['src'])) {
2565 + $script['url'] = $attributes['src'];
2566 + $url_query = wp_parse_url($script['url'], PHP_URL_QUERY);
2567 + $output = array();
2568 + wp_parse_str($url_query, $output);
2569 + if (isset($output['ver'])) $script['version'] = $output['ver'];
2570 + }
2571 +
2572 + // Extract the id/handle from attribute's array if present
2573 + if (isset($attributes['id'])) $script['handle'] = $attributes['id'];
2574 +
2575 + // Extract the type from attribute's array if present
2576 + if (isset($attributes['type'])) $script['type'] = $attributes['type'];
2577 +
2578 + $modified_script_matches[] = $script;
2579 + }
2580 +
2581 + return $modified_script_matches;
2582 + }
2583 +
2584 + /**
2585 + * Extract `importmap` json object from html buffer using regex
2586 + *
2587 + * @param string $html - HTML document as string
2588 + * @return array
2589 + */
2590 + private function get_script_module_importmap($html) {
2591 + preg_match('/<script\s+type\s*=\s*[\'"]importmap.*>(?<importmap>.*)<\/script>/Umsi', $html, $match);
2592 + if (!empty($match) && isset($match['importmap'])) return json_decode($match['importmap'], true);
2593 +
2594 + return array();
2595 + }
2596 +
2597 + /**
2260 2598 * Handles css processing
2261 2599 */
2262 2600 private function process_css() {
2263 2601 add_action('wp_head', array($this, 'add_critical_path'), 2);
@@ -2263,11 +2601,11 @@
2263 2601 add_action('wp_head', array($this, 'add_critical_path'), 2);
2264 2602
2265 2603 // merge, if inline is selected but prevent optimization for these locations
2266 2604 if ($this->options['inline_css']) {
2267 - // this prints the styles (not fonts) and checks the 'colllect google fonts'
2605 + // this prints the styles (not fonts) and checks the 'collect google fonts'
2268 2606 add_filter('style_loader_tag', array($this, 'inline_css'), PHP_INT_MAX, 4);
2269 - // this prints the google fonts
2607 + // this prints the Google fonts
2270 2608 add_action('wp_print_styles', array($this, 'add_google_fonts_merged'), PHP_INT_MAX);
2271 2609 add_action('wp_print_footer_scripts', array($this, 'add_google_fonts_merged'), PHP_INT_MAX);
2272 2610 }
2273 2611 // Preloading
@@ -2273,14 +2611,14 @@
2273 2611 // Preloading
2274 2612 if ($this->options['enabled_css_preload']) {
2275 2613 add_filter('style_loader_tag', array($this, 'collect_css_preload_headers'), PHP_INT_MAX, 3);
2276 2614 }
2277 - // Optimize the css and collect the google fonts for merging
2615 + // Optimize the css and collect the Google fonts for merging
2278 2616 add_action('wp_print_styles', array($this, 'process_header_css'), PHP_INT_MAX);
2279 2617 add_action('wp_print_footer_scripts', array($this, 'process_footer_css'), 9);
2280 2618
2281 2619 /**
2282 - * Filters whether or not to ignore the order of the CSS files, and group them by media type
2620 + * Filters whether to ignore the order of the CSS files, and group them by media type
2283 2621 *
2284 2622 * @param boolean $maintain_css_order
2285 2623 * @return boolean
2286 2624 * @default true
@@ -2286,14 +2624,16 @@
2286 2624 * @default true
2287 2625 */
2288 2626 if (!apply_filters('wpo_minify_maintain_css_order', true)) {
2289 2627 // Reorder stylesheets
2290 - add_filter('wpo_minify_stylesheets', array($this, 'order_stylesheets_per_media_type'), 10);
2628 + add_filter('wpo_minify_stylesheets', array($this, 'order_stylesheets_per_media_type'));
2291 2629 }
2292 2630 }
2293 2631
2294 2632 /**
2295 2633 * Determines whether we should minify html or not
2634 + *
2635 + * @return bool
2296 2636 */
2297 2637 private function should_process_html() {
2298 2638 return $this->options['html_minification'] && !is_admin() && $this->is_cache_preload();
2299 2639 }
@@ -2299,8 +2639,10 @@
2299 2639 }
2300 2640
2301 2641 /**
2302 2642 * Determines whether to use loadCSS polyfill or not
2643 + *
2644 + * @return bool
2303 2645 */
2304 2646 private function should_use_loadCSS() {
2305 2647 return $this->options['loadcss']
2306 2648 || 'async' === $this->options['fawesome_method']
@@ -2392,19 +2734,20 @@
2392 2734
2393 2735 /**
2394 2736 * Decides whether minify cache should be incremented or not
2395 2737 *
2396 - * @param string $res
2738 + * @param array $res
2397 2739 * @param string $href
2398 2740 * @param string $type
2399 2741 * @param string $handle
2400 - * @param string $version
2742 + * @param mixed $version
2401 2743 *
2402 2744 * @return bool true when cache is invalid, false otherwise
2403 2745 */
2404 2746 private function should_reset_minify_assets($res, $href, $type, $handle, $version) {
2405 2747 if (isset($res['request']['version']) && $res['request']['version'] != $version && !$this->minify_cache_incremented) {
2406 - $new_json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $this->options['enable_css_minification'], $type, $handle, $version);
2748 + $enable_minification = $this->options['enable_'.$type.'_minification'] && !WP_Optimize_Minify_Functions::is_minified_css_js_filename($href);
2749 + $new_json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $enable_minification, $type, $handle, $version);
2407 2750 $new_res = json_decode($new_json, true);
2408 2751
2409 2752 /**
2410 2753 * In case `download_and_minify` fails because of
@@ -2417,6 +2760,18 @@
2417 2760 $hash = hash('sha256', $res['code']);
2418 2761 $new_hash = hash('sha256', $new_res['code']);
2419 2762 return strcmp($hash, $new_hash);
2420 2763 }
2764 + return false;
2765 + }
2766 +
2767 + /**
2768 + * Returns the log header with the current date and url
2769 + *
2770 + * @return string
2771 + */
2772 + private function get_log_header() {
2773 + $request_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : '';
2774 + $log_header = "PROCESSED on ".gmdate('r')." from ".home_url($request_uri);
2775 + return $log_header;
2421 2776 }
2422 2777 }