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 +709 -206 3.2.7 → 4.7.0 View file →
@@ -30,8 +30,12 @@
30 30 add_action('fl_builder_after_save_layout', array('WP_Optimize_Minify_Cache_Functions', 'reset'));
31 31
32 32 // extra_preload_headers is currently not available to users
33 33 // add_action('send_headers', array($this, 'extra_preload_headers'));
34 +
35 + if (!is_admin()) {
36 + add_action('wp_headers', array($this, 'add_caching_headers'));
37 + }
34 38 }
35 39
36 40 /**
37 41 * Fired on wp init
@@ -60,8 +64,14 @@
60 64 if ($this->options['enable_js']) {
61 65 $this->process_js();
62 66 }
63 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 +
64 74 if ($this->options['enable_css']) {
65 75 $this->process_css();
66 76 }
67 77
@@ -70,9 +80,9 @@
70 80 add_action('wp_head', array($this, 'add_assets_preload'), 2);
71 81 }
72 82
73 83 if ($this->should_process_html()) {
74 - add_action('template_redirect', array('WP_Optimize_Minify_Functions', 'html_compression_start'), PHP_INT_MAX);
84 + add_action('template_redirect', array('WP_Optimize_Minify_Functions', 'html_compression_start'));
75 85 }
76 86
77 87 if ($this->should_use_loadCSS()) {
78 88 add_action('wp_footer', array('WP_Optimize_Minify_Print', 'add_load_css'), PHP_INT_MAX);
@@ -81,30 +91,54 @@
81 91 $this->remove_query_string_from_static_assets();
82 92 }
83 93
84 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 + /**
85 105 * Detects whether cache preloading is running or not
86 106 *
87 107 * @return bool
88 108 */
89 109 private function is_cache_preload() {
90 - 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');
91 111 }
92 112
93 113 /**
94 - * Wether to run the feature on a page or not
114 + * Set initial values for the meta log object
95 115 *
116 + * @param string $header - Info on time the log was processed
117 + * @return array
118 + */
119 + private function meta_log_initialization($header) {
120 + return array(
121 + 'header' => $header,
122 + 'invalidation_reason' => "",
123 + 'files_that_changed' => array()
124 + );
125 + }
126 +
127 + /**
128 + * Whether to run the feature on a page or not
129 + *
96 130 * @param string $context - Optional, The context where the check is done
97 131 * @return boolean
98 132 */
99 133 public function run_on_page($context = 'default') {
100 134 /**
101 - * Filters wether the functionality is ran on the current page.
135 + * Filters whether the functionality is run on the current page.
102 136 *
103 137 * @param boolean $run_on_page
104 138 * @param string $context - Optional, The feature where the check is done
105 139 */
106 - return apply_filters(
140 + $filtered_value = apply_filters(
107 141 'wpo_minify_run_on_page',
108 142 !is_admin()
109 143 && (!defined('SCRIPT_DEBUG') || !SCRIPT_DEBUG)
110 144 && !is_preview()
@@ -113,19 +147,20 @@
113 147 && !(function_exists('is_amp_endpoint') && is_amp_endpoint())
114 148 && !WP_Optimize_Minify_Functions::exclude_contents(),
115 149 $context
116 150 );
151 + return is_bool($filtered_value) ? $filtered_value : false;
117 152 }
118 153
119 154 /**
120 155 * Inline css in place, instead of inlining the large file
121 156 *
122 - * @param String $html
123 - * @param String $handle
124 - * @param String $href
125 - * @param String $media
157 + * @param string $html
158 + * @param string $handle
159 + * @param string $href
160 + * @param mixed $media
126 161 *
127 - * @return String
162 + * @return string|boolean
128 163 */
129 164 public function inline_css($html, $handle, $href, $media) {
130 165 $exclude_css = $this->get_excluded_css_list();
131 166 $ignore_list = WP_Optimize_Minify_Functions::compile_ignore_list($exclude_css);
@@ -136,9 +171,9 @@
136 171 // make sure href is complete
137 172 $href = WP_Optimize_Minify_Functions::get_hurl($href);
138 173
139 174 if ($this->options['debug']) {
140 - 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";
141 176 }
142 177
143 178
144 179 // skip all this, if the async css option is enabled
@@ -148,17 +183,16 @@
148 183 // leave conditionals alone
149 184 if (wp_styles()->get_data($handle, 'conditional')) return $html;
150 185
151 186 // mediatype fix for some plugins + remove print mediatypes
152 - if ('screen' == $media
153 - || 'screen, print' == $media
154 - || empty($media)
155 - || is_null($media)
156 - || false == $media
187 + if (!is_string($media)
188 + || '' === $media
189 + || 'screen' === $media
190 + || 'screen, print' === $media
157 191 ) {
158 192 $media = 'all';
159 193 }
160 - if (!empty($this->options['remove_print_mediatypes']) && 'print' == $media) {
194 + if (!empty($this->options['remove_print_mediatypes']) && 'print' === $media) {
161 195 return false;
162 196 }
163 197
164 198 // Exclude specific CSS files from PageSpeedInsights?
@@ -174,12 +208,17 @@
174 208 if (count($master_ignore) > 0 && WP_Optimize_Minify_Functions::in_arrayi($href, $master_ignore)) {
175 209 return $html;
176 210 }
177 211
178 - // 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
179 218 if (WP_Optimize_Minify_Functions::is_font_awesome($href)) {
180 219 // font awesome processing, async css
181 - if ('async' == $this->options['fawesome_method']) {
220 + if ('async' === $this->options['fawesome_method']) {
182 221 WP_Optimize_Minify_Print::async_style($href, $media);
183 222 return false;
184 223 } elseif ('exclude' === $this->options['fawesome_method']) {
185 224 // font awesome processing, async and exclude from PageSpeedIndex
@@ -184,17 +223,19 @@
184 223 } elseif ('exclude' === $this->options['fawesome_method']) {
185 224 // font awesome processing, async and exclude from PageSpeedIndex
186 225 WP_Optimize_Minify_Print::exclude_style($href);
187 226 return false;
188 - } elseif ('inline' == $this->options['fawesome_method']) {
227 + } elseif ('inline' === $this->options['fawesome_method']) {
189 228 WP_Optimize_Minify_Print::inline_style($handle, $href);
190 229 return false;
191 230 }
192 231 }
193 232
194 - // Check if working with google font url
233 + // Check if working with Google font url
195 234
196 - 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;
197 238 // check if google fonts should be removed
198 239 if ($this->options['remove_googlefonts']) return false;
199 240 // check if google fonts should be merged
200 241 if ($this->options['merge_google_fonts']) {
@@ -216,9 +257,9 @@
216 257 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
217 258 if (false === $json) {
218 259 $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $this->options['enable_css_minification'], 'css', $handle);
219 260 if ($this->options['debug']) {
220 - 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";
221 262 }
222 263 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
223 264 }
224 265
@@ -225,18 +266,20 @@
225 266 // decode
226 267 $res = json_decode($json, true);
227 268
228 269 // inline css or fail
229 - if (null !== $res && false != $res['status']) {
270 + if (null !== $res && false !== $res['status']) {
230 271 // add font-display
231 272 // https://developers.google.com/web/updates/2016/02/font-display
232 273 $res['code'] = str_ireplace('font-style:normal;', 'font-display:block;font-style:normal;', $res['code']);
233 274
234 - 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";
235 278 return false;
236 279 } else {
237 280 if ($this->options['debug']) {
238 - 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";
239 282 }
240 283 return $html;
241 284 }
242 285 } elseif ('async' === $this->options['gfonts_method']) {
@@ -268,9 +311,9 @@
268 311 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
269 312 if (false === $json) {
270 313 $json = WP_Optimize_Minify_Functions::download_and_minify($href, null, $this->options['enable_css_minification'], 'css', $handle);
271 314 if ($this->options['debug']) {
272 - 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";
273 316 }
274 317 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
275 318 }
276 319
@@ -277,21 +320,25 @@
277 320 // decode
278 321 $res = json_decode($json, true);
279 322
280 323 // inline it + other inlined children styles
281 - if (null !== $res && false != $res['status']) {
282 - 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";
283 328
284 329 // get inline_styles for this handle, minify and print
285 330 $inline_styles = array();
286 331 $inline_styles = wp_styles()->get_data($handle, 'after');
287 - if (false != $inline_styles) {
332 + if ($inline_styles) {
288 333
289 334 // string type
290 335 if (is_string($inline_styles)) {
291 336 $code = WP_Optimize_Minify_Functions::get_css($href, $inline_styles, $this->options['enable_css_minification']);
292 - if (!empty($code) && false != $code) {
293 - 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";
294 341 }
295 342 }
296 343
297 344 // array type
@@ -297,10 +344,12 @@
297 344 // array type
298 345 if (is_array($inline_styles)) {
299 346 foreach ($inline_styles as $st) {
300 347 $code = WP_Optimize_Minify_Functions::get_css($href, $st, $this->options['enable_css_minification']);
301 - if (!empty($code) && false != $code) {
302 - 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";
303 352 }
304 353 }
305 354 }
306 355 }
@@ -308,9 +357,9 @@
308 357 // prevent default
309 358 return false;
310 359 } else {
311 360 if ($this->options['debug']) {
312 - 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";
313 362 }
314 363 return $html;
315 364 }
316 365 echo "<!-- ERROR: WPO-Minify couldn't catch the CSS file below. Please report this on https://wordpress.org/support/plugin/wp-optimize/ -->\n";
@@ -317,15 +366,15 @@
317 366 return $html;
318 367 }
319 368
320 369 /**
321 - * 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
322 371 *
323 - * @param String $tag
324 - * @param String $handle
325 - * @param String $src
372 + * @param string $tag
373 + * @param string $handle
374 + * @param string $src
326 375 *
327 - * @return String
376 + * @return string
328 377 */
329 378 public function defer_js($tag, $handle, $src) {
330 379 $wp_domain = trim(str_ireplace(array('http://', 'https://'), '', trim(site_url(), '/')));
331 380 $exclude_js = $this->get_excluded_js_list();
@@ -331,11 +380,12 @@
331 380 $exclude_js = $this->get_excluded_js_list();
332 381 $ignore_list = WP_Optimize_Minify_Functions::compile_ignore_list($exclude_js);
333 382 // Should this defer the Poly fills for IE?
334 383 $blacklist = WP_Optimize_Minify_Functions::get_ie_blacklist();
384 +
335 385 // no query strings
336 - if (false !== stripos($src, '?ver')) {
337 - $srcf = stristr($src, '?ver', true); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.stristr_before_needleFound
386 + if (false !== stripos($src, '?ver') && WP_Optimize_Minify_Functions::is_already_minified($src)) {
387 + $srcf = stristr($src, '?ver', true);
338 388 $tag = str_ireplace($src, $srcf, $tag);
339 389 $src = $srcf;
340 390 }
341 391
@@ -369,9 +419,9 @@
369 419 }
370 420
371 421 // should we exclude defer on the login page?
372 422 if ($this->options['exclude_defer_login']
373 - && 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(), '/'))
374 424 ) {
375 425 return $tag;
376 426 }
377 427
@@ -421,11 +471,15 @@
421 471 * @return void
422 472 */
423 473 public function add_critical_path() {
424 474 if (is_front_page() && !empty($this->options['critical_path_css_is_front_page'])) {
425 - 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";
426 478 } elseif (!empty($this->options['critical_path_css'])) {
427 - 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";
428 482 }
429 483 }
430 484
431 485 /**
@@ -453,8 +507,9 @@
453 507 global $wp_styles;
454 508 if (!is_object($wp_styles)) return false;
455 509
456 510 $cache_path = WP_Optimize_Minify_Cache_Functions::cache_path();
511 + $cache_base_dir = $cache_path['cachebasedir'];
457 512 $cache_dir = $cache_path['cachedir'];
458 513 $cache_dir_url = $cache_path['cachedirurl'];
459 514 $exclude_css = $this->get_excluded_css_list();
460 515 $ignore_list = WP_Optimize_Minify_Functions::compile_ignore_list($exclude_css);
@@ -463,8 +518,9 @@
463 518 $minify_css = $this->options['enable_css_minification'];
464 519 $merge_css = $this->options['enable_merging_of_css'];
465 520 $merge_inline_extra_css_js = $this->options['merge_inline_extra_css_js'];
466 521 $process_css = $minify_css || $merge_css;
522 + $disable_google_fonts_processing = $this->options['disable_google_fonts_processing'];
467 523 $styles = clone $wp_styles;
468 524 $styles->all_deps($styles->queue);
469 525 $done = $styles->done;
470 526 $header = array();
@@ -493,9 +549,9 @@
493 549 }
494 550
495 551 // mediatype
496 552 $mt = isset($wp_styles->registered[$handle]->args) ? $wp_styles->registered[$handle]->args : 'all';
497 - 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) {
498 554 $mt = 'all';
499 555 }
500 556 $mediatype = $mt;
501 557
@@ -508,8 +564,9 @@
508 564
509 565
510 566 // mark duplicates as done and remove from the queue
511 567 if (!empty($href)) {
568 + $version = is_array($version) ? '' : $version;
512 569 $key = hash('adler32', $href . $version);
513 570 if (isset($uniq[$key])) {
514 571 $done = array_merge($done, array($handle));
515 572 continue;
@@ -516,11 +573,15 @@
516 573 } else {
517 574 $uniq[$key] = $handle;
518 575 }
519 576 }
577 +
578 + $version = '?ver=' . (!empty($version) ? $version : $wp_styles->default_version);
579 + $href_versioned = $href . $version;
580 +
520 581 // Exclude specific CSS files from PageSpeedIndex?
521 582 if (WP_Optimize_Minify_Functions::in_arrayi($href, $async_css)) {
522 - WP_Optimize_Minify_Print::exclude_style($href);
583 + WP_Optimize_Minify_Print::exclude_style($href_versioned);
523 584 $done = array_merge($done, array($handle));
524 585 continue;
525 586 }
526 587 // Fonts Awesome Processing
@@ -525,17 +586,17 @@
525 586 }
526 587 // Fonts Awesome Processing
527 588 if (WP_Optimize_Minify_Functions::is_font_awesome($href)) {
528 589 if ('inline' === $this->options['fawesome_method']) {
529 - WP_Optimize_Minify_Print::inline_style($handle, $href);
590 + WP_Optimize_Minify_Print::inline_style($handle, $href_versioned);
530 591 $done = array_merge($done, array($handle));
531 592 continue;
532 593 } elseif ('async' === $this->options['fawesome_method']) {
533 - WP_Optimize_Minify_Print::async_style($href, $mediatype);
594 + WP_Optimize_Minify_Print::async_style($href_versioned, $mediatype);
534 595 $done = array_merge($done, array($handle));
535 596 continue;
536 597 } elseif ('exclude' === $this->options['fawesome_method']) {
537 - WP_Optimize_Minify_Print::exclude_style($href);
598 + WP_Optimize_Minify_Print::exclude_style($href_versioned);
538 599 $done = array_merge($done, array($handle));
539 600 continue;
540 601 }
541 602 }
@@ -554,9 +615,9 @@
554 615 'mediatype' => $mediatype
555 616 );
556 617
557 618 // google fonts to the top (collect and skip process array)
558 - if (WP_Optimize_Minify_Functions::is_google_font($href)) {
619 + if (!$disable_google_fonts_processing && WP_Optimize_Minify_Functions::is_google_font($href)) {
559 620 if ($this->options['remove_googlefonts']) {
560 621 $done = array_merge($done, array($handle));
561 622 continue;
562 623 }
@@ -575,10 +636,12 @@
575 636 // merge google fonts if force inlining is enabled?
576 637 $nfonts = array();
577 638 if ($this->options['merge_google_fonts']) {
578 639 $nfonts[] = WP_Optimize_Minify_Fonts::concatenate_google_fonts($google_fonts);
579 - // mark the google fonts as done so they don't get processed
580 - $done = array_merge($done, array_keys($google_fonts));
640 + // mark the Google fonts as done so they don't get processed
641 + if ('inherit' !== $this->options['gfonts_method']) {
642 + $done = array_merge($done, array_keys($google_fonts));
643 + }
581 644 } else {
582 645 foreach ($google_fonts as $h => $a) {
583 646 if (!empty($a)) {
584 647 $nfonts[$h] = $a;
@@ -593,13 +656,13 @@
593 656 $tkey = 'css-'.hash('adler32', $href).'.css';
594 657 // this returns false if the cache is empty! but it doesn't check for failed
595 658 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
596 659 $json = json_decode($json, true);
597 - // check if the cache is empty or if the cache has code
598 - if (null !== $json && (false === $json || empty($json['code']))) {
660 + // check if the cache is empty or has no code
661 + if (null === $json || false === $json || empty($json['code'])) {
599 662 $res = WP_Optimize_Minify_Functions::download_and_minify($href, null, $minify_css, 'css', null);
600 663 if ($this->options['debug']) {
601 - 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";
602 665 }
603 666 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $res);
604 667 // decode
605 668 $json = json_decode($res, true);
@@ -609,14 +672,16 @@
609 672 if (null !== $json && !empty($json['code'])) {
610 673 // add font-display
611 674 // https://developers.google.com/web/updates/2016/02/font-display
612 675 $json['code'] = str_ireplace('font-style:normal;', 'font-display:block;font-style:normal;', $json['code']);
613 - 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";
614 679 $done = array_merge($done, array($handle));
615 680 } else {
616 - echo "<!-- GOOGLE FONTS REQUEST FAILED for $href -->" . "\n";
681 + echo "<!-- GOOGLE FONTS REQUEST FAILED for " . esc_html($href) . " -->" . "\n";
617 682 // inlining failed, so enqueue again
618 - 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
619 684 }
620 685 } elseif ('async' === $this->options['gfonts_method']) {
621 686 WP_Optimize_Minify_Print::async_style($href);
622 687 $done = array_merge($done, array($handle));
@@ -658,16 +723,19 @@
658 723 $file_size = WP_Optimize_Minify_Functions::get_file_size($href);
659 724
660 725 // If we can't determine file size, then we still need to proceed with normal minify process
661 726 if (!apply_filters('wp_optimize_skip_inlining', false === $file_size || $file_size > 20480 || !$this->options['inline_css'], $file_size, $href)) continue;
662 -
663 - // skip ignore list, conditional css, external css, font-awesome merge
664 - 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()))
665 733 || empty($href)
666 - || ($process_css && 'inherit' == $this->options['fawesome_method'] && WP_Optimize_Minify_Functions::is_font_awesome($href))
667 - || ($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))
668 736 ) {
669 - // colect inline css for this handle
737 + // collect inline css for this handle
670 738 if (isset($wp_styles->registered[$handle]->extra['after']) && is_array($wp_styles->registered[$handle]->extra['after'])) {
671 739 $inline_css[$handle] = WP_Optimize_Minify_Functions::minify_css_string(implode('', $wp_styles->registered[$handle]->extra['after'])); // save
672 740 $wp_styles->registered[$handle]->extra['after'] = null; // dequeue
673 741 }
@@ -672,19 +740,24 @@
672 740 $wp_styles->registered[$handle]->extra['after'] = null; // dequeue
673 741 }
674 742
675 743 // process
676 - 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) {
677 745 array_push($header, array('handles' => array(), 'media' => $mediatype, 'versions' => array()));
678 746 }
679 747
680 748 // push it to the array
681 749 array_push($header[count($header)-1]['handles'], $handle);
682 - array_push($header[count($header)-1]['handles'], $wp_styles->registered[$handle]->ver);
683 750
751 + // We need this because some plugins/theme use empty array as version
752 + // https://plugins.trac.wordpress.org/browser/mailin/tags/3.1.54/sendinblue.php#L456
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;
754 + array_push($header[count($header)-1]['versions'], $version_str);
755 +
756 + $header[count($header) - 1]['last_modified'][] = WP_Optimize_Minify_Functions::get_modification_time($wp_styles->registered[$handle]->src);
757 +
684 758 // external and ignored css
685 759 } else {
686 -
687 760 // normal enqueuing
688 761 array_push($header, array('handle' => $handle));
689 762 }
690 763 }
@@ -699,21 +772,29 @@
699 772 $header = apply_filters('wpo_minify_stylesheets', $header, 'header');
700 773
701 774 // loop through header css and merge
702 775 for ($i=0,$l=count($header); $i<$l; $i++) {
776 +
703 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 +
704 782 if ($merge_css) {
705 783 // get hash for the inline css in this group
706 784 $inline_css_group = array();
707 - foreach ($header[$i]['handles'] as $h) {
708 - if (isset($inline_css[$h]) && !empty($inline_css[$h])) {
709 - $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 + }
710 791 }
711 792 }
712 793 $inline_css_hash = md5(implode('', $inline_css_group));
713 - $hash = hash('adler32', implode('', $header[$i]['handles']).$inline_css_hash . implode('', $header[$i]['versions']));
794 + $hash = hash('adler32', $handle_str . $inline_css_hash . $last_modified_str);
714 795 } else {
715 - $hash = implode('', $header[$i]['handles']) . implode('', $header[$i]['versions']);
796 + $hash = sanitize_file_name($handle_str . $last_modified_str);
716 797 }
717 798
718 799 // static cache file info
719 800 $file_name = 'wpo-minify-header-'.$hash.($minify_css ? '.min' : '');
@@ -719,9 +800,9 @@
719 800 $file_name = 'wpo-minify-header-'.$hash.($minify_css ? '.min' : '');
720 801
721 802 // create cache files and urls
722 803 $file = $cache_dir.'/'.$file_name.'.css';
723 -
804 + $meta_json_file = $cache_base_dir.'/'.'meta.json';
724 805 $file_url = WP_Optimize_Minify_Functions::get_protocol("$cache_dir_url/$file_name.css");
725 806
726 807 // generate a new cache file
727 808 clearstatcache();
@@ -727,12 +808,14 @@
727 808 clearstatcache();
728 809 if (!file_exists($file)) {
729 810
730 811 // code and log initialization
812 + $log_header = $this->get_log_header();
731 813 $log = array(
732 - 'header' => "PROCESSED on ".date('r')." from ".home_url(add_query_arg(null, null)),
814 + 'header' => $log_header,
733 815 'files' => array()
734 816 );
817 + $meta_log = $this->meta_log_initialization($log_header);
735 818 $code = '';
736 819
737 820 // minify and write to file
738 821 foreach ($header[$i]['handles'] as $handle) {
@@ -738,10 +821,12 @@
738 821 foreach ($header[$i]['handles'] as $handle) {
739 822 if (!empty($wp_styles->registered[$handle]->src)) {
740 823
741 824 // get href per handle
742 - $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);
743 827 $version = $wp_styles->registered[$handle]->ver;
828 + $last_modified = WP_Optimize_Minify_Functions::get_modification_time($handle_src);
744 829
745 830 // inlined scripts without file
746 831 if (empty($href)) continue;
747 832
@@ -749,11 +834,12 @@
749 834 $tkey = 'css-'.hash('adler32', $handle . $href).'.css';
750 835 $json = false;
751 836 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
752 837 if (false === $json) {
753 - $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);
754 840 if ($this->options['debug']) {
755 - 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";
756 842 }
757 843 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
758 844 }
759 845
@@ -761,16 +847,20 @@
761 847 $res = json_decode($json, true);
762 848
763 849 if (null === $res) continue;
764 850
765 - if (isset($res['request']['version']) && $res['request']['version'] != $version && !$this->minify_cache_incremented) {
851 + if ($this->should_reset_minify_assets($res, $href, 'css', $handle, $version)) {
766 852 WP_Optimize_Minify_Cache_Functions::reset();
767 853 $this->minify_cache_incremented = true;
854 + $meta_log['invalidation_reason'] = 'Checksum Mismatch and version changed from ' . $res['request']['version'] . ' to ' . $version;
855 + $meta_log['files_that_changed'][$handle] = $res['log'];
768 856 }
769 857
770 858 // response has failed
771 - if (true != $res['status']) {
859 + if (true !== $res['status']) {
772 860 $log['files'][$handle] = $res['log'];
861 + $log['files'][$handle]['version'] = $version;
862 + $log['files'][$handle]['last_modified'] = $last_modified;
773 863 continue;
774 864 }
775 865
776 866 // Only add the $handle to $done if it was successfully downloaded
@@ -775,10 +865,12 @@
775 865
776 866 // Only add the $handle to $done if it was successfully downloaded
777 867 $done[] = $handle;
778 868 // append code to merged file
779 - $code .= isset($res['code']) ? $res['code'] : '';
869 + $code .= $res['code'] ?? '';
780 870 $log['files'][$handle] = $res['log'];
871 + $log['files'][$handle]['version'] = $version;
872 + $log['files'][$handle]['last_modified'] = $last_modified;
781 873
782 874 // append inlined styles
783 875 if ($merge_inline_extra_css_js && isset($inline_css[$handle]) && !empty($inline_css[$handle])) {
784 876 $code.= $inline_css[$handle];
@@ -792,8 +884,12 @@
792 884 };
793 885
794 886 // generate cache, write log
795 887 if (!empty($code)) {
888 + // Only generate meta.json file if cache is reset
889 + if (!empty($meta_log['invalidation_reason'])) {
890 + file_put_contents($meta_json_file, wp_json_encode($meta_log));
891 + }
796 892 WP_Optimize_Minify_Print::write_combined_asset($file, $code, $log);
797 893 }
798 894 } else {
799 895 $log_file = $file.'.json';
@@ -801,8 +897,9 @@
801 897 $saved_log = json_decode(file_get_contents($log_file));
802 898 if (is_object($saved_log) && property_exists($saved_log, 'files')) {
803 899 $files = (array) $saved_log->files;
804 900 foreach ($header[$i]['handles'] as $handle) {
901 + $handle = is_array($handle) ? '' : $handle;
805 902 if (isset($files[$handle]) && $files[$handle]->success) {
806 903 $done[] = $handle;
807 904 }
808 905 }
@@ -823,24 +920,18 @@
823 920 WP_Optimize_Minify_Print::async_style($file_url, $mt);
824 921 // enqueue file, if not empty
825 922 } else {
826 923 if (file_exists($file) && filesize($file) > 0) {
827 -
828 - // inline CSS if mediatype is not of type "all" (such as mobile only), if the file is smaller than 20KB
829 - if (filesize($file) < 20000 && 'all' != $header[$i]['media']) {
830 - echo '<style id="wpo-min-header-'.$i.'" media="'.$header[$i]['media'].'">'.file_get_contents($file).'</style>' . "\n";
831 - } else {
832 - // enqueue it
833 - wp_enqueue_style("wpo_min-header-$i", $file_url, array(), 'mycoolversion', $header[$i]['media']);
834 - foreach ($header[$i]['handles'] as $h) {
835 - if (!$merge_inline_extra_css_js && isset($inline_css[$h]) && !empty($inline_css[$h])) {
836 - wp_add_inline_style("wpo_min-header-$i", $inline_css[$h]);
837 - }
924 + // enqueue it
925 + wp_enqueue_style("wpo_min-header-$i", $file_url, array(), 'mycoolversion', $header[$i]['media']);
926 + foreach ($header[$i]['handles'] as $h) {
927 + if (!$merge_inline_extra_css_js && isset($inline_css[$h]) && !empty($inline_css[$h])) {
928 + wp_add_inline_style("wpo_min-header-$i", $inline_css[$h]);
838 929 }
839 930 }
840 931 } else {
841 932 // file could not be generated, output something meaningful
842 - 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))." -->";
843 934 echo "<!-- Please check if the path above is correct and ensure your server has write permission there! -->";
844 935 }
845 936 }
846 937 // other css need to be requeued for the order of files to be kept
@@ -865,8 +956,9 @@
865 956 if (!is_object($wp_scripts)) {
866 957 return;
867 958 }
868 959 $cache_path = WP_Optimize_Minify_Cache_Functions::cache_path();
960 + $cache_base_dir = $cache_path['cachebasedir'];
869 961 $cache_dir = $cache_path['cachedir'];
870 962 $cache_dir_url = $cache_path['cachedirurl'];
871 963
872 964
@@ -883,8 +975,10 @@
883 975
884 976 // mark as done (as we go)
885 977 $done = $scripts->done;
886 978
979 + $previous_load_strategy = null;
980 +
887 981 // get groups of handles
888 982 foreach ($scripts->to_do as $handle) :
889 983
890 984 // get full url
@@ -895,9 +989,9 @@
895 989 continue;
896 990 }
897 991
898 992 // Exclude JS files from PageSpeedIndex (Async) takes priority over the ignore list
899 - if (false != $async_js || is_array($async_js)) {
993 + if (!empty($async_js)) {
900 994
901 995 // check for string match
902 996 $skipjs = false;
903 997 foreach ($async_js as $l) {
@@ -902,15 +996,16 @@
902 996 $skipjs = false;
903 997 foreach ($async_js as $l) {
904 998 if (stripos($href, $l) !== false) {
905 999 // print code if there are no linebreaks, or return
906 - 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);
907 1002 $skipjs = true;
908 1003 $done = array_merge($done, array($handle));
909 1004 break;
910 1005 }
911 1006 }
912 - if (false != $skipjs) {
1007 + if (false !== $skipjs) {
913 1008 continue;
914 1009 }
915 1010 }
916 1011
@@ -919,15 +1014,24 @@
919 1014 if ($ieonly) {
920 1015 continue;
921 1016 }
922 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 +
923 1022 // skip ignore list, scripts with conditionals, external scripts
924 - 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()))
925 1024 || empty($href)
926 1025 ) {
927 1026
928 1027 // process
929 - 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 + ) {
930 1034 array_push($footer, array('handles' => array(), 'versions' => array()));
931 1035 }
932 1036
933 1037 if (isset($wp_scripts->registered[$handle]->extra['before'])) {
@@ -938,9 +1042,17 @@
938 1042
939 1043 // push it to the array
940 1044 array_push($footer[count($footer)-1]['handles'], $handle);
941 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);
942 1051 // external and ignored scripts
1052 +
1053 + $previous_load_strategy = $scripts->registered[$handle]->extra['strategy'] ?? null;
1054 +
943 1055 } else {
944 1056 array_push($footer, array('handle' => $handle));
945 1057 }
946 1058 endforeach;
@@ -946,15 +1058,19 @@
946 1058 endforeach;
947 1059
948 1060 // loop through footer scripts and merge
949 1061 for ($i=0,$l=count($footer); $i<$l; $i++) {
1062 +
950 1063 if (!isset($footer[$i]['handle'])) {
951 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 +
952 1068 if ($merge_js) {
953 - // Change the hash based on version numbers
954 - $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);
955 1071 } else {
956 - $hash = implode('', $footer[$i]['handles']) . implode('', $footer[$i]['versions']);
1072 + $hash = sanitize_file_name($handles_str . $last_modified_str);
957 1073 }
958 1074
959 1075 // static cache file info
960 1076 $file_name = 'wpo-minify-footer-'.$hash.($minify_js ? '.min' : '');
@@ -960,8 +1076,9 @@
960 1076 $file_name = 'wpo-minify-footer-'.$hash.($minify_js ? '.min' : '');
961 1077
962 1078 // create cache files and urls
963 1079 $file = $cache_dir.'/'.$file_name.'.js';
1080 + $meta_json_file = $cache_base_dir.'/'.'meta.json';
964 1081 $file_url = WP_Optimize_Minify_Functions::get_protocol($cache_dir_url.'/'.$file_name.'.js');
965 1082
966 1083 // generate a new cache file
967 1084 clearstatcache();
@@ -967,20 +1084,29 @@
967 1084 clearstatcache();
968 1085 if (!file_exists($file)) {
969 1086
970 1087 // code and log initialization
1088 + $log_header = $this->get_log_header();
971 1089 $log = array(
972 - 'header' => "PROCESSED on ".date('r')." from ".home_url(add_query_arg(null, null)),
1090 + 'header' => $log_header,
973 1091 'files' => array()
974 1092 );
1093 + $meta_log = $this->meta_log_initialization($log_header);
1094 + $before_code = '';
975 1095 $code = '';
1096 + $after_code = '';
976 1097
977 1098 // minify and write to file
978 1099 foreach ($footer[$i]['handles'] as $handle) :
979 1100 if (!empty($wp_scripts->registered[$handle]->src)) {
1101 + // only add minified scripts once to the bundle
1102 + if (in_array($handle, $done)) continue;
1103 +
980 1104 // get href per handle
981 - $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);
982 1107 $version = $wp_scripts->registered[$handle]->ver;
1108 + $last_modified = WP_Optimize_Minify_Functions::get_modification_time($handle_src);
983 1109 // inlined scripts without file
984 1110 if (empty($href)) {
985 1111 continue;
986 1112 }
@@ -988,11 +1114,12 @@
988 1114 $tkey = 'js-'.hash('adler32', $handle . $href).'.js';
989 1115 $json = false;
990 1116 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
991 1117 if (false === $json) {
992 - $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);
993 1120 if ($this->options['debug']) {
994 - 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";
995 1122 }
996 1123 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
997 1124 }
998 1125
@@ -1000,16 +1127,21 @@
1000 1127 $res = json_decode($json, true);
1001 1128
1002 1129 if (null === $res) continue;
1003 1130
1004 - if (isset($res['request']['version']) && $res['request']['version'] != $version && !$this->minify_cache_incremented) {
1131 + if ($this->should_reset_minify_assets($res, $href, 'js', $handle, $version)) {
1005 1132 WP_Optimize_Minify_Cache_Functions::reset();
1006 1133 $this->minify_cache_incremented = true;
1134 + $meta_log['invalidation_reason'] = 'Checksum Mismatch and version changed from ' . $res['request']['version'] . ' to ' . $version;
1135 + $meta_log['files_that_changed'][$handle] = $res['log'];
1007 1136 }
1008 1137
1009 1138 // response has failed
1010 - if (true != $res['status']) {
1139 + if (true !== $res['status']) {
1011 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;
1012 1144 continue;
1013 1145 }
1014 1146
1015 1147 $done[] = $handle;
@@ -1016,9 +1148,9 @@
1016 1148 // Add extra data from wp_add_inline_script before
1017 1149 if (!empty($wp_scripts->registered[$handle]->extra)) {
1018 1150 if (!empty($wp_scripts->registered[$handle]->extra['before']) && is_array($wp_scripts->registered[$handle]->extra['before'])) {
1019 1151 if ($merge_inline_extra_css_js) {
1020 - $code.= "\n" . WP_Optimize_Minify_Functions::prepare_merged_js(implode("\n", array_filter($wp_scripts->registered[$handle]->extra['before'])), $href . ' - BEFORE');
1152 + $before_code .= "\n" . implode("\n", array_filter($wp_scripts->registered[$handle]->extra['before']));
1021 1153 }
1022 1154 }
1023 1155 }
1024 1156
@@ -1025,22 +1157,28 @@
1025 1157 // Add translation
1026 1158 if (!empty($wp_scripts->registered[$handle]->textdomain)) {
1027 1159 $code .= "\n" . $wp_scripts->print_translations($handle, false);
1028 1160 }
1029 -
1030 - // append code to merged file
1031 - $code .= isset($res['code']) ? WP_Optimize_Minify_Functions::prepare_merged_js($res['code'], $href) : '';
1032 - $log['files'][$handle] = $res['log'];
1033 1161
1034 1162 // Add extra data from wp_add_inline_script after
1035 1163 if (!empty($wp_scripts->registered[$handle]->extra)) {
1036 1164 if (!empty($wp_scripts->registered[$handle]->extra['after']) && is_array($wp_scripts->registered[$handle]->extra['after'])) {
1037 1165 if ($merge_inline_extra_css_js) {
1038 - $code.= "\n" . WP_Optimize_Minify_Functions::prepare_merged_js(implode("\n", array_filter($wp_scripts->registered[$handle]->extra['after'])), $href. ' - AFTER');
1166 + $after_code .= "\n" . implode("\n", array_filter($wp_scripts->registered[$handle]->extra['after']));
1039 1167 }
1040 1168 }
1041 1169 }
1042 -
1170 +
1171 + // append code to merged file
1172 + $code .= $before_code . "\n";
1173 + $code .= $res['code'] ?? '';
1174 + $code .= "\n" . $after_code . "\n";
1175 + $code = WP_Optimize_Minify_Functions::prepare_merged_js($code, $href);
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;
1180 +
1043 1181 // consider dependencies on handles with an empty src
1044 1182 } else {
1045 1183 wp_dequeue_script($handle);
1046 1184 wp_enqueue_script($handle);
@@ -1048,8 +1186,12 @@
1048 1186 endforeach;
1049 1187
1050 1188 // generate cache, write log
1051 1189 if (!empty($code)) {
1190 + // Only generate meta.json file if cache is reset
1191 + if (!empty($meta_log['invalidation_reason'])) {
1192 + file_put_contents($meta_json_file, wp_json_encode($meta_log));
1193 + }
1052 1194 WP_Optimize_Minify_Print::write_combined_asset($file, $code, $log);
1053 1195 }
1054 1196 } else {
1055 1197 $log_file = $file.'.json';
@@ -1072,9 +1214,9 @@
1072 1214 }
1073 1215 }
1074 1216
1075 1217 // register minified file
1076 - 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
1077 1219
1078 1220 // add all extra data from wp_localize_script
1079 1221 $before_code = '';
1080 1222 $data = array();
@@ -1087,14 +1229,14 @@
1087 1229 // Add extra data from wp_add_inline_script before
1088 1230 if (!empty($wp_scripts->registered[$handle]->extra)) {
1089 1231 if (!empty($wp_scripts->registered[$handle]->extra['before']) && is_array($wp_scripts->registered[$handle]->extra['before'])) {
1090 1232 if (!$merge_inline_extra_css_js) {
1091 - $before_code.= "\n" . WP_Optimize_Minify_Functions::prepare_merged_js(implode("\n", array_filter($wp_scripts->registered[$handle]->extra['before'])), $href.' - BEFORE');
1233 + $before_code.= "\n" . implode("\n", array_filter($wp_scripts->registered[$handle]->extra['before'])) . "\n";
1092 1234 }
1093 1235 }
1094 1236 if (!empty($wp_scripts->registered[$handle]->extra['after']) && is_array($wp_scripts->registered[$handle]->extra['after'])) {
1095 1237 if (!$merge_inline_extra_css_js) {
1096 - $after_code.= "\n" . WP_Optimize_Minify_Functions::prepare_merged_js(implode("\n", array_filter($wp_scripts->registered[$handle]->extra['after'])), $href.' - AFTER');
1238 + $after_code.= "\n" . implode("\n", array_filter($wp_scripts->registered[$handle]->extra['after'])) . "\n";
1097 1239 }
1098 1240 }
1099 1241 }
1100 1242 }
@@ -1110,11 +1252,16 @@
1110 1252 wp_enqueue_script("wpo_min-footer-$i");
1111 1253 if (!empty($after_code)) {
1112 1254 wp_add_inline_script("wpo_min-footer-$i", $after_code, 'after');
1113 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 + }
1114 1261 } else {
1115 1262 // file could not be generated, output something meaningful
1116 - 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))." -->";
1117 1264 echo "<!-- Please check if the path above is correct and ensure your server has write permission there! -->";
1118 1265 }
1119 1266
1120 1267 // other scripts need to be requeued for the order of files to be kept
@@ -1129,9 +1276,9 @@
1129 1276 }
1130 1277
1131 1278 /**
1132 1279 * Process header JavaScript
1133 - * Dependant on 'enable_js' option
1280 + * Dependent on 'enable_js' option
1134 1281 *
1135 1282 * @return void
1136 1283 */
1137 1284 public function process_header_scripts() {
@@ -1137,8 +1284,9 @@
1137 1284 public function process_header_scripts() {
1138 1285 global $wp_scripts;
1139 1286 if (!is_object($wp_scripts)) return;
1140 1287 $cache_path = WP_Optimize_Minify_Cache_Functions::cache_path();
1288 + $cache_base_dir = $cache_path['cachebasedir'];
1141 1289 $cache_dir = $cache_path['cachedir'];
1142 1290 $cache_dir_url = $cache_path['cachedirurl'];
1143 1291 $exclude_js = $this->get_excluded_js_list();
1144 1292 $ignore_list = WP_Optimize_Minify_Functions::compile_ignore_list($exclude_js);
@@ -1153,8 +1301,10 @@
1153 1301 // mark as done (as we go)
1154 1302 $done = $scripts->done;
1155 1303 $excluded_dependencies = array();
1156 1304
1305 + $previous_load_strategy = null;
1306 +
1157 1307 // Prepare and separate assets (get groups of handles)
1158 1308 foreach ($scripts->to_do as $handle) {
1159 1309 // get full url
1160 1310 $href = WP_Optimize_Minify_Functions::get_hurl($wp_scripts->registered[$handle]->src);
@@ -1159,9 +1309,9 @@
1159 1309 // get full url
1160 1310 $href = WP_Optimize_Minify_Functions::get_hurl($wp_scripts->registered[$handle]->src);
1161 1311 // inlined scripts without file
1162 1312 if (empty($href)) {
1163 - wp_enqueue_script($handle, false);
1313 + wp_enqueue_script($handle, false); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Not needed
1164 1314 continue;
1165 1315 }
1166 1316
1167 1317 // Only go through items without a group
@@ -1170,9 +1320,10 @@
1170 1320 // check for string match
1171 1321 $skipjs = false;
1172 1322 foreach ($async_js as $l) {
1173 1323 if (stripos($href, $l) !== false) {
1174 - 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);
1175 1326 $skipjs = true;
1176 1327 $done = array_merge($done, array($handle));
1177 1328 break;
1178 1329 }
@@ -1183,9 +1334,9 @@
1183 1334 ) {
1184 1335 continue;
1185 1336 }
1186 1337
1187 - // Skip jQuery from the merged files if defering is ENABLED and defer_jquery is DISABLED
1338 + // Skip jQuery from the merged files if deferring is ENABLED and defer_jquery is DISABLED
1188 1339 if ('all' === $this->options['enable_defer_js']
1189 1340 && !$this->options['defer_jquery']
1190 1341 && (false !== stripos($href, '/jquery.js')
1191 1342 || false !== stripos($href, '/jquery.min.js')
@@ -1193,14 +1344,23 @@
1193 1344 ) {
1194 1345 continue;
1195 1346 }
1196 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 +
1197 1352 // Group handles - skip ignore list, scripts with conditionals, external scripts
1198 - 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()))
1199 1354 || empty($href)
1200 1355 ) {
1201 1356 // process
1202 - 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 + ) {
1203 1363 array_push($header, array('handles' => array(), 'versions' => array()));
1204 1364 }
1205 1365
1206 1366 // Force loading of dependencies
@@ -1233,9 +1393,16 @@
1233 1393
1234 1394 // push it to the array
1235 1395 array_push($header[count($header)-1]['handles'], $handle);
1236 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);
1237 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 +
1238 1405 // external and ignored scripts
1239 1406 } else {
1240 1407 // add the ignored assets
1241 1408 array_push($header, array('handle' => $handle));
@@ -1242,20 +1409,24 @@
1242 1409 }
1243 1410
1244 1411 // make sure that the scripts skipped here, show up in the footer
1245 1412 } else {
1246 - 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
1247 1414 }
1248 1415 }
1249 1416
1250 1417 // loop through header scripts and merge
1251 1418 for ($i=0,$l=count($header); $i < $l; $i++) {
1419 +
1252 1420 if (!isset($header[$i]['handle'])) {
1253 -
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 +
1254 1425 if ($merge_js) {
1255 - $hash = hash('adler32', implode('', $header[$i]['handles']) . implode('', $header[$i]['versions']));
1426 + $hash = hash('adler32', $handles_str . $last_modified_str);
1256 1427 } else {
1257 - $hash = implode('', $header[$i]['handles']) . implode('', $header[$i]['versions']);
1428 + $hash = sanitize_file_name($handles_str . $last_modified_str);
1258 1429 }
1259 1430
1260 1431 // static cache file info
1261 1432 $file_name = 'wpo-minify-header-'.$hash.($minify_js ? '.min' : '');
@@ -1260,8 +1431,9 @@
1260 1431 // static cache file info
1261 1432 $file_name = 'wpo-minify-header-'.$hash.($minify_js ? '.min' : '');
1262 1433 // create cache files and urls
1263 1434 $file = $cache_dir.'/'.$file_name.'.js';
1435 + $meta_json_file = $cache_base_dir.'/'.'meta.json';
1264 1436 $file_url = WP_Optimize_Minify_Functions::get_protocol($cache_dir_url.'/'.$file_name.'.js');
1265 1437
1266 1438 // generate a new cache file
1267 1439 clearstatcache();
@@ -1267,21 +1439,29 @@
1267 1439 clearstatcache();
1268 1440 if (!file_exists($file)) {
1269 1441
1270 1442 // code and log initialization
1443 + $log_header = $this->get_log_header();
1271 1444 $log = array(
1272 - 'header' => "PROCESSED on ".date('r')." from ".home_url(add_query_arg(null, null)),
1445 + 'header' => $log_header,
1273 1446 'files' => array()
1274 1447 );
1448 + $meta_log = $this->meta_log_initialization($log_header);
1449 + $before_code = '';
1275 1450 $code = '';
1451 + $after_code = '';
1276 1452
1277 1453 // minify and write to file
1278 1454 foreach ($header[$i]['handles'] as $handle) {
1279 1455 if (!empty($wp_scripts->registered[$handle]->src)) {
1456 + // only add minified scripts once to the bundle
1457 + if (in_array($handle, $done)) continue;
1280 1458
1281 1459 // get href per handle
1282 - $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);
1283 1462 $version = $wp_scripts->registered[$handle]->ver;
1463 + $last_modified = WP_Optimize_Minify_Functions::get_modification_time($handle_src);
1284 1464 if (empty($href)) continue;
1285 1465 // download, minify, cache
1286 1466 $tkey = 'js-'.hash('adler32', $handle . $href).'.js';
1287 1467 $json = false;
@@ -1286,11 +1466,12 @@
1286 1466 $tkey = 'js-'.hash('adler32', $handle . $href).'.js';
1287 1467 $json = false;
1288 1468 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
1289 1469 if (false === $json) {
1290 - $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);
1291 1472 if ($this->options['debug']) {
1292 - 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";
1293 1474 }
1294 1475 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
1295 1476 }
1296 1477
@@ -1298,16 +1479,21 @@
1298 1479 $res = json_decode($json, true);
1299 1480
1300 1481 if (null === $res) continue;
1301 1482
1302 - if (isset($res['request']['version']) && $res['request']['version'] != $version && !$this->minify_cache_incremented) {
1483 + if ($this->should_reset_minify_assets($res, $href, 'js', $handle, $version)) {
1303 1484 WP_Optimize_Minify_Cache_Functions::reset();
1304 1485 $this->minify_cache_incremented = true;
1486 + $meta_log['invalidation_reason'] = 'Checksum Mismatch and version changed from ' . $res['request']['version'] . ' to ' . $version;
1487 + $meta_log['files_that_changed'][$handle] = $res['log'];
1305 1488 }
1306 1489
1307 1490 // response has failed
1308 - if (true != $res['status']) {
1491 + if (true !== $res['status']) {
1309 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;
1310 1496 continue;
1311 1497 }
1312 1498
1313 1499 // Add extra data from wp_add_inline_script before
@@ -1313,9 +1499,9 @@
1313 1499 // Add extra data from wp_add_inline_script before
1314 1500 if (!empty($wp_scripts->registered[$handle]->extra)) {
1315 1501 if (!empty($wp_scripts->registered[$handle]->extra['before']) && is_array($wp_scripts->registered[$handle]->extra['before'])) {
1316 1502 if ($merge_inline_extra_css_js) {
1317 - $code .= "\n" . WP_Optimize_Minify_Functions::prepare_merged_js(implode("\n", array_filter($wp_scripts->registered[$handle]->extra['before'])), $href.' - BEFORE');
1503 + $before_code .= "\n" . implode("\n", array_filter($wp_scripts->registered[$handle]->extra['before']));
1318 1504 }
1319 1505 }
1320 1506 }
1321 1507
@@ -1326,21 +1512,27 @@
1326 1512 if (!empty($wp_scripts->registered[$handle]->textdomain)) {
1327 1513 $code .= "\n" . $wp_scripts->print_translations($handle, false);
1328 1514 }
1329 1515
1330 - // append code to merged file
1331 - $code .= isset($res['code']) ? WP_Optimize_Minify_Functions::prepare_merged_js($res['code'], $href) : '';
1332 - $log['files'][$handle] = $res['log'];
1333 -
1334 1516 // Add extra data from wp_add_inline_script after
1335 1517 if (!empty($wp_scripts->registered[$handle]->extra)) {
1336 1518 if (!empty($wp_scripts->registered[$handle]->extra['after']) && is_array($wp_scripts->registered[$handle]->extra['after'])) {
1337 1519 if ($merge_inline_extra_css_js) {
1338 - $code.= "\n" . WP_Optimize_Minify_Functions::prepare_merged_js(implode("\n", array_filter($wp_scripts->registered[$handle]->extra['after'])), $href.' - AFTER');
1520 + $after_code.= "\n" . implode("\n", array_filter($wp_scripts->registered[$handle]->extra['after']));
1339 1521 }
1340 1522 }
1341 1523 }
1342 -
1524 +
1525 + // append code to merged file
1526 + $code .= $before_code . "\n";
1527 + $code .= isset($res['code']) ? $res['code'] : '';
1528 + $code .= "\n" . $after_code . "\n";
1529 + $code = WP_Optimize_Minify_Functions::prepare_merged_js($code, $href);
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;
1534 +
1343 1535 // consider dependencies on handles with an empty src
1344 1536 } else {
1345 1537 wp_dequeue_script($handle);
1346 1538 wp_enqueue_script($handle);
@@ -1348,8 +1540,12 @@
1348 1540 }
1349 1541
1350 1542 // generate cache, write log
1351 1543 if (!empty($code)) {
1544 + // Only generate meta.json file if cache is reset
1545 + if (!empty($meta_log['invalidation_reason'])) {
1546 + file_put_contents($meta_json_file, wp_json_encode($meta_log));
1547 + }
1352 1548 WP_Optimize_Minify_Print::write_combined_asset($file, $code, $log);
1353 1549 }
1354 1550 } else {
1355 1551 $log_file = $file.'.json';
@@ -1357,8 +1553,9 @@
1357 1553 $saved_log = json_decode(file_get_contents($log_file));
1358 1554 if (is_object($saved_log) && property_exists($saved_log, 'files')) {
1359 1555 $files = (array) $saved_log->files;
1360 1556 foreach ($header[$i]['handles'] as $handle) {
1557 + $handle = is_array($handle) ? '' : $handle;
1361 1558 if (isset($files[$handle]) && $files[$handle]->success) {
1362 1559 $done[] = $handle;
1363 1560 }
1364 1561 }
@@ -1373,9 +1570,9 @@
1373 1570 }
1374 1571
1375 1572 // register minified file
1376 1573 $dependencies = isset($excluded_dependencies[$i]) ? $excluded_dependencies[$i] : array();
1377 - 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
1378 1575
1379 1576 // add all extra data from wp_localize_script
1380 1577 $before_code = '';
1381 1578 $data = array();
@@ -1389,14 +1586,14 @@
1389 1586 // Add extra data from wp_add_inline_script before
1390 1587 if (!empty($wp_scripts->registered[$handle]->extra)) {
1391 1588 if (!empty($wp_scripts->registered[$handle]->extra['before']) && is_array($wp_scripts->registered[$handle]->extra['before'])) {
1392 1589 if (!$merge_inline_extra_css_js) {
1393 - $before_code.= "\n" . WP_Optimize_Minify_Functions::prepare_merged_js(implode("\n", array_filter($wp_scripts->registered[$handle]->extra['before'])), $href.' - BEFORE');
1590 + $before_code.= "\n" . implode("\n", array_filter($wp_scripts->registered[$handle]->extra['before'])) . "\n";
1394 1591 }
1395 1592 }
1396 1593 if (!empty($wp_scripts->registered[$handle]->extra['after']) && is_array($wp_scripts->registered[$handle]->extra['after'])) {
1397 1594 if (!$merge_inline_extra_css_js) {
1398 - $after_code.= "\n" . WP_Optimize_Minify_Functions::prepare_merged_js(implode("\n", array_filter($wp_scripts->registered[$handle]->extra['after'])), $href.' - AFTER');
1595 + $after_code.= "\n" . implode("\n", array_filter($wp_scripts->registered[$handle]->extra['after'])) . "\n";
1399 1596 }
1400 1597 }
1401 1598 }
1402 1599 }
@@ -1412,11 +1609,16 @@
1412 1609 wp_enqueue_script("wpo_min-header-$i");
1413 1610 if (!empty($after_code)) {
1414 1611 wp_add_inline_script("wpo_min-header-$i", $after_code, 'after');
1415 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 + }
1416 1618 } else {
1417 1619 // file could not be generated, output something meaningful
1418 - 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))." -->";
1419 1621 echo "<!-- Please check if the path above is correct and ensure your server has write permission there! -->";
1420 1622 echo "<!-- If you found a bug, please report this on https://wordpress.org/support/plugin/wp-optimize/ -->";
1421 1623 }
1422 1624
@@ -1439,8 +1641,9 @@
1439 1641 public function process_footer_css() {
1440 1642 global $wp_styles;
1441 1643 if (!is_object($wp_styles)) return;
1442 1644 $cache_path = WP_Optimize_Minify_Cache_Functions::cache_path();
1645 + $cache_base_dir = $cache_path['cachebasedir'];
1443 1646 $cache_dir = $cache_path['cachedir'];
1444 1647 $cache_dir_url = $cache_path['cachedirurl'];
1445 1648 $exclude_css = $this->get_excluded_css_list();
1446 1649 $ignore_list = WP_Optimize_Minify_Functions::compile_ignore_list($exclude_css);
@@ -1447,8 +1650,9 @@
1447 1650 $async_css = $this->get_async_css_list();
1448 1651 $minify_css = $this->options['enable_css_minification'];
1449 1652 $merge_css = $this->options['enable_merging_of_css'];
1450 1653 $process_css = $minify_css || $merge_css;
1654 + $disable_google_fonts_processing = $this->options['disable_google_fonts_processing'];
1451 1655 $log = "";
1452 1656 $code = "";
1453 1657 $styles = clone $wp_styles;
1454 1658 $styles->all_deps($styles->queue);
@@ -1467,15 +1671,15 @@
1467 1671 $wp_styles->done = $done;
1468 1672 return;
1469 1673 }
1470 1674
1471 - // dequeue and get a list of google fonts, or requeue external
1675 + // dequeue and get a list of Google fonts, or requeue external
1472 1676 foreach ($styles->to_do as $handle) {
1473 1677 $href = WP_Optimize_Minify_Functions::get_hurl($wp_styles->registered[$handle]->src);
1474 1678 // inlined scripts without file
1475 1679 if (empty($href)) continue;
1476 1680
1477 - if (WP_Optimize_Minify_Functions::is_google_font($href)) {
1681 + if (!$disable_google_fonts_processing && WP_Optimize_Minify_Functions::is_google_font($href)) {
1478 1682 wp_dequeue_style($handle);
1479 1683 if ($this->options['remove_googlefonts']) {
1480 1684 $done = array_merge($done, array($handle));
1481 1685 continue;
@@ -1536,15 +1740,14 @@
1536 1740 WP_Optimize_Minify_Print::inline_style($handle, $href);
1537 1741 $done = array_merge($done, array($handle));
1538 1742 } else {
1539 1743 // fallback, enqueue google fonts
1540 - 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
1541 1745 }
1542 1746 }
1543 1747 }
1544 1748 }
1545 1749
1546 -
1547 1750 // get groups of handles
1548 1751 $uniq = array();
1549 1752 foreach ($styles->to_do as $handle) {
1550 1753
@@ -1557,11 +1760,11 @@
1557 1760 $conditional = null; if (isset($wp_styles->registered[$handle]->extra["conditional"])) {
1558 1761 $conditional = $wp_styles->registered[$handle]->extra["conditional"]; // such as ie7, ie8, ie9, etc
1559 1762 }
1560 1763
1561 - // mediatype
1764 + // media type
1562 1765 $mt = isset($wp_styles->registered[$handle]->args) ? $wp_styles->registered[$handle]->args : 'all';
1563 - if ('screen' == $mt || 'screen, print' == $mt || empty($mt) || is_null($mt) || false == $mt) {
1766 + if ('screen' === $mt || 'screen, print' === $mt || empty($mt)) {
1564 1767 $mt = 'all';
1565 1768 }
1566 1769 $mediatype = $mt;
1567 1770
@@ -1575,8 +1778,9 @@
1575 1778 }
1576 1779
1577 1780 // mark duplicates as done and remove from the queue
1578 1781 if (!empty($href)) {
1782 + $version = is_array($version) ? '' : $version;
1579 1783 $key = hash('adler32', $href . $version);
1580 1784 if (isset($uniq[$key])) {
1581 1785 $done = array_merge($done, array($handle));
1582 1786 continue;
@@ -1590,11 +1794,14 @@
1590 1794 if ($ieonly) {
1591 1795 continue;
1592 1796 }
1593 1797
1798 + $version = '?ver=' . (!empty($version) ? $version : $wp_styles->default_version);
1799 + $href_versioned = $href . $version;
1800 +
1594 1801 // Exclude specific CSS files from PageSpeedIndex?
1595 - if (false != $async_css && is_array($async_css) && WP_Optimize_Minify_Functions::in_arrayi($href, $async_css)) {
1596 - 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);
1597 1804 $done = array_merge($done, array($handle));
1598 1805 continue;
1599 1806 }
1600 1807
@@ -1599,17 +1806,17 @@
1599 1806 }
1600 1807
1601 1808 if (WP_Optimize_Minify_Functions::is_font_awesome($href)) {
1602 1809 if ('inline' === $this->options['fawesome_method']) {
1603 - WP_Optimize_Minify_Print::inline_style($handle, $href);
1810 + WP_Optimize_Minify_Print::inline_style($handle, $href_versioned);
1604 1811 $done = array_merge($done, array($handle));
1605 1812 continue;
1606 1813 } elseif ('async' === $this->options['fawesome_method']) {
1607 - WP_Optimize_Minify_Print::async_style($href, $mediatype);
1814 + WP_Optimize_Minify_Print::async_style($href_versioned, $mediatype);
1608 1815 $done = array_merge($done, array($handle));
1609 1816 continue;
1610 1817 } elseif ('exclude' === $this->options['fawesome_method']) {
1611 - WP_Optimize_Minify_Print::exclude_style($href);
1818 + WP_Optimize_Minify_Print::exclude_style($href_versioned);
1612 1819 $done = array_merge($done, array($handle));
1613 1820 continue;
1614 1821 }
1615 1822 }
@@ -1619,14 +1826,17 @@
1619 1826 $done = array_merge($done, array($handle));
1620 1827 continue;
1621 1828 }
1622 1829
1623 - // skip ignore list, conditional css, external css, font-awesome merge
1624 - 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()))
1625 1835 || empty($href)
1626 1836 ) {
1627 1837
1628 - // colect inline css for this handle
1838 + // collect inline css for this handle
1629 1839 if (isset($wp_styles->registered[$handle]->extra['after']) && is_array($wp_styles->registered[$handle]->extra['after'])) {
1630 1840 $inline_css[$handle] = WP_Optimize_Minify_Functions::minify_css_string(implode('', $wp_styles->registered[$handle]->extra['after'])); // save
1631 1841 $wp_styles->registered[$handle]->extra['after'] = null; // dequeue
1632 1842 }
@@ -1631,15 +1841,16 @@
1631 1841 $wp_styles->registered[$handle]->extra['after'] = null; // dequeue
1632 1842 }
1633 1843
1634 1844 // process
1635 - 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) {
1636 1846 array_push($footer, array('handles' => array(), 'media' => $mediatype, 'versions' => array()));
1637 1847 }
1638 1848
1639 1849 // push it to the array get latest modified time
1640 1850 array_push($footer[count($footer)-1]['handles'], $handle);
1641 - array_push($footer[count($footer)-1]['handles'], $version);
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);
1642 1853
1643 1854 // external and ignored css
1644 1855 } else {
1645 1856
@@ -1658,21 +1869,28 @@
1658 1869 $footer = apply_filters('wpo_minify_stylesheets', $footer, 'footer');
1659 1870
1660 1871 // loop through footer css and merge
1661 1872 for ($i=0,$l=count($footer); $i<$l; $i++) {
1873 +
1662 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 +
1663 1879 if ($merge_css) {
1664 1880 // get hash for the inline css in this group
1665 1881 $inline_css_group = array();
1666 - foreach ($footer[$i]['handles'] as $h) {
1667 - if (isset($inline_css[$h]) && !empty($inline_css[$h])) {
1668 - $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 + }
1669 1887 }
1670 1888 }
1671 1889 $inline_css_hash = md5(implode('', $inline_css_group));
1672 - $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);
1673 1891 } else {
1674 - $hash = implode('', $footer[$i]['handles']) . implode('', $footer[$i]['versions']);
1892 + $hash = sanitize_file_name($handles_str . $last_modified_str);
1675 1893 }
1676 1894
1677 1895 // static cache file info
1678 1896 $file_name = 'wpo-minify-footer-'.$hash.($minify_css ? '.min' : '');
@@ -1678,8 +1896,9 @@
1678 1896 $file_name = 'wpo-minify-footer-'.$hash.($minify_css ? '.min' : '');
1679 1897
1680 1898 // create cache files and urls
1681 1899 $file = $cache_dir.'/'.$file_name.'.css';
1900 + $meta_json_file = $cache_base_dir.'/'.'meta.json';
1682 1901 $file_url = WP_Optimize_Minify_Functions::get_protocol($cache_dir_url.'/'.$file_name.'.css');
1683 1902
1684 1903 // generate a new cache file
1685 1904 clearstatcache();
@@ -1685,12 +1904,14 @@
1685 1904 clearstatcache();
1686 1905 if (!file_exists($file)) {
1687 1906
1688 1907 // code and log initialization
1908 + $log_header = $this->get_log_header();
1689 1909 $log = array(
1690 - 'header' => "PROCESSED on ".date('r')." from ".home_url(add_query_arg(null, null)),
1910 + 'header' => $log_header,
1691 1911 'files' => array()
1692 1912 );
1913 + $meta_log = $this->meta_log_initialization($log_header);
1693 1914 $code = '';
1694 1915
1695 1916 // minify and write to file
1696 1917 foreach ($footer[$i]['handles'] as $handle) {
@@ -1696,11 +1917,13 @@
1696 1917 foreach ($footer[$i]['handles'] as $handle) {
1697 1918 if (!empty($wp_styles->registered[$handle]->src)) {
1698 1919
1699 1920 // get href per handle
1700 - $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);
1701 1923 $version = $wp_styles->registered[$handle]->ver;
1702 - // inlined scripts without hreffile
1924 + $last_modified = WP_Optimize_Minify_Functions::get_modification_time($handle_src);
1925 + // inlined scripts without href file
1703 1926 if (empty($href)) continue;
1704 1927
1705 1928 // download, minify, cache
1706 1929 $tkey = 'css-'.hash('adler32', $handle . $href).'.css';
@@ -1706,11 +1929,12 @@
1706 1929 $tkey = 'css-'.hash('adler32', $handle . $href).'.css';
1707 1930 $json = false;
1708 1931 $json = WP_Optimize_Minify_Cache_Functions::get_transient($tkey);
1709 1932 if (false === $json) {
1710 - $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);
1711 1935 if ($this->options['debug']) {
1712 - 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";
1713 1937 }
1714 1938 WP_Optimize_Minify_Cache_Functions::set_transient($tkey, $json);
1715 1939 }
1716 1940
@@ -1718,16 +1942,20 @@
1718 1942 $res = json_decode($json, true);
1719 1943
1720 1944 if (null === $res) continue;
1721 1945
1722 - if (isset($res['request']['version']) && $res['request']['version'] != $version && !$this->minify_cache_incremented) {
1946 + if ($this->should_reset_minify_assets($res, $href, 'css', $handle, $version)) {
1723 1947 WP_Optimize_Minify_Cache_Functions::reset();
1724 1948 $this->minify_cache_incremented = true;
1949 + $meta_log['invalidation_reason'] = 'Checksum Mismatch and version changed from ' . $res['request']['version'] . ' to ' . $version;
1950 + $meta_log['files_that_changed'][$handle] = $res['log'];
1725 1951 }
1726 1952
1727 1953 // response has failed
1728 - if (true != $res['status']) {
1954 + if (true !== $res['status']) {
1729 1955 $log['files'][$handle] = $res['log'];
1956 + $log['files'][$handle]['version'] = $version;
1957 + $log['files'][$handle]['last_modified'] = $last_modified;
1730 1958 continue;
1731 1959 }
1732 1960
1733 1961 $done[] = $handle;
@@ -1732,10 +1960,12 @@
1732 1960
1733 1961 $done[] = $handle;
1734 1962
1735 1963 // append code to merged file
1736 - $code .= isset($res['code']) ? $res['code'] : '';
1964 + $code .= $res['code'] ?? '';
1737 1965 $log['files'][$handle] = $res['log'];
1966 + $log['files'][$handle]['version'] = $version;
1967 + $log['files'][$handle]['last_modified'] = $last_modified;
1738 1968
1739 1969 // append inlined styles
1740 1970 if (isset($inline_css[$handle]) && !empty($inline_css[$handle])) {
1741 1971 $code.= $inline_css[$handle];
@@ -1745,12 +1975,16 @@
1745 1975 } else {
1746 1976 wp_dequeue_script($handle);
1747 1977 wp_enqueue_script($handle);
1748 1978 }
1749 - };
1979 + }
1750 1980
1751 1981 // generate cache, add inline css, write log
1752 1982 if (!empty($code)) {
1983 + // Only generate meta.json file if cache is reset
1984 + if (!empty($meta_log['invalidation_reason'])) {
1985 + file_put_contents($meta_json_file, wp_json_encode($meta_log));
1986 + }
1753 1987 WP_Optimize_Minify_Print::write_combined_asset($file, $code, $log);
1754 1988 }
1755 1989 } else {
1756 1990 $log_file = $file.'.json';
@@ -1785,13 +2019,13 @@
1785 2019 if (filesize($file) < 20000 && $this->options['inline_css']) {
1786 2020 $this->inline_css(file_get_contents($file), $handle, $file_url, $footer[$i]['media']);
1787 2021 } else {
1788 2022 // enqueue it
1789 - 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
1790 2024 }
1791 2025 } else {
1792 2026 // file could not be generated, output something meaningful
1793 - 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))." -->";
1794 2028 echo "<!-- Please check if the path above is correct and ensure your server has write permission there! -->";
1795 2029 }
1796 2030 }
1797 2031
@@ -1806,8 +2040,129 @@
1806 2040 $wp_styles->done = $done;
1807 2041 }
1808 2042
1809 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 + /**
1810 2165 * Orders the CSS per media type
1811 2166 *
1812 2167 * @param array $list - The list of assets
1813 2168 * @return array
@@ -1851,9 +2206,9 @@
1851 2206 * @return void;
1852 2207 */
1853 2208 public function add_google_fonts_merged() {
1854 2209 // must have something to do
1855 - if (count($this->collect_google_fonts) == 0) return;
2210 + if (count($this->collect_google_fonts) === 0) return;
1856 2211
1857 2212 // merge google fonts
1858 2213 $href = WP_Optimize_Minify_Fonts::concatenate_google_fonts($this->collect_google_fonts);
1859 2214 if (empty($href)) {
@@ -1899,14 +2254,19 @@
1899 2254 // always false for admin pages
1900 2255 if (is_admin()) return false;
1901 2256
1902 2257 // get host with multisite support and query strings
1903 - $host = htmlentities($_SERVER['SERVER_NAME']);
2258 + $host = isset($_SERVER['SERVER_NAME']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_NAME'])) : '';
1904 2259 if (empty($host)) {
1905 - $host = htmlentities($_SERVER['HTTP_HOST']);
2260 + $host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '';
1906 2261 }
1907 - $request_query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
1908 - $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 + }
1909 2269
1910 2270 // initialize headers
1911 2271 $headers = array();
1912 2272
@@ -1914,9 +2274,9 @@
1914 2274 if ($this->options['enabled_css_preload']
1915 2275 && count($this->collect_preload_css) > 0
1916 2276 ) {
1917 2277 foreach ($this->collect_preload_css as $u) {
1918 - // 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
1919 2279 if (strpos($u, '/assets/wpo-minify-footer-') !== false) {
1920 2280 continue;
1921 2281 }
1922 2282
@@ -1930,9 +2290,9 @@
1930 2290 && count($this->collect_preload_js) > 0
1931 2291 ) {
1932 2292 foreach ($this->collect_preload_js as $u) {
1933 2293
1934 - // 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
1935 2295 if (false !== strpos($u, '/assets/wpo-minify-footer-')) {
1936 2296 continue;
1937 2297 }
1938 2298
@@ -1941,9 +2301,9 @@
1941 2301 }
1942 2302 }
1943 2303
1944 2304 // must have something
1945 - if (count($headers) == 0) {
2305 + if (count($headers) === 0) {
1946 2306 return false;
1947 2307 } else {
1948 2308 $headers = implode("\n", $headers);
1949 2309 }
@@ -1959,9 +2319,9 @@
1959 2319 // reset file cache
1960 2320 clearstatcache();
1961 2321
1962 2322 // if there are no query strings
1963 - if ($b == $a) {
2323 + if ($b === $a) {
1964 2324 if (!file_exists($a)) {
1965 2325 WP_Optimize_Minify_Print::write_header($a, $headers);
1966 2326 }
1967 2327 return false;
@@ -1974,13 +2334,13 @@
1974 2334
1975 2335 /**
1976 2336 * Collect all wpo_min JS files and save them to a headers file
1977 2337 *
1978 - * @param String $html
1979 - * @param String $handle
1980 - * @param String $src
2338 + * @param string $html
2339 + * @param string $handle
2340 + * @param string $src
1981 2341 *
1982 - * @return String
2342 + * @return string
1983 2343 */
1984 2344 public function collect_js_preload_headers($html, $handle, $src) {
1985 2345 if (false !== strpos($src, 'assets/wpo-minify')) {
1986 2346 if (!in_array($src, $this->collect_preload_js)) {
@@ -2027,14 +2387,18 @@
2027 2387 return false;
2028 2388 }
2029 2389
2030 2390 // get host with multisite support and query strings
2031 - $host = htmlentities($_SERVER['SERVER_NAME']);
2391 + $host = isset($_SERVER['SERVER_NAME']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_NAME'])) : '';
2032 2392 if (empty($host)) {
2033 - $host = htmlentities($_SERVER['HTTP_HOST']);
2393 + $host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '';
2034 2394 }
2035 - $request_query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
2036 - $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 + }
2037 2401
2038 2402 // get cache path
2039 2403 $cache_path = WP_Optimize_Minify_Cache_Functions::cache_path();
2040 2404 $header_dir = $cache_path['headerdir'];
@@ -2047,12 +2411,12 @@
2047 2411 // reset file cache
2048 2412 clearstatcache();
2049 2413
2050 2414 // return header files or fallback
2051 - if ($b == $a && file_exists($a)) {
2415 + if ($b === $a && file_exists($a)) {
2052 2416 return file_get_contents($a);
2053 2417 }
2054 - if ($b != $a && file_exists($b)) {
2418 + if ($b !== $a && file_exists($b)) {
2055 2419 return file_get_contents($b);
2056 2420 }
2057 2421
2058 2422 return false;
@@ -2058,9 +2422,9 @@
2058 2422 return false;
2059 2423 }
2060 2424
2061 2425 /**
2062 - * Add pre-connect and pre-load headers
2426 + * Add pre-connect and preload headers
2063 2427 *
2064 2428 * @return void
2065 2429 */
2066 2430 public function extra_preload_headers() {
@@ -2069,9 +2433,9 @@
2069 2433 // fetch headers
2070 2434 $pre_connect = $this->get_pre_connect_list();
2071 2435
2072 2436 // preload
2073 - if (is_array($pre_connect) && count($pre_connect) > 0) {
2437 + if (count($pre_connect) > 0) {
2074 2438 foreach ($pre_connect as $url) {
2075 2439 if (!empty($url) && filter_var($url, FILTER_VALIDATE_URL)) {
2076 2440 header("Link: <$url>; rel=preconnect", false);
2077 2441 }
@@ -2078,9 +2442,9 @@
2078 2442 }
2079 2443 }
2080 2444
2081 2445 $headers = $this->get_preload_headers();
2082 - if (false != $headers) {
2446 + if ($headers) {
2083 2447 $nh = array_map('trim', explode("\n", $headers));
2084 2448 foreach ($nh as $h) {
2085 2449 if (!empty($h)) {
2086 2450 header($h, false);
@@ -2089,8 +2453,30 @@
2089 2453 }
2090 2454 }
2091 2455
2092 2456 /**
2457 + * Add caching headers
2458 + *
2459 + * @param array $headers An array of headers
2460 + *
2461 + * @return array An array of modified headers
2462 + */
2463 + public function add_caching_headers($headers) {
2464 + $cache = WP_Optimize()->get_page_cache();
2465 + if ($cache->is_enabled()) return $headers;
2466 +
2467 + if (!isset($headers['Cache-Control'])) {
2468 + $headers['Cache-Control'] = 'must-revalidate';
2469 + }
2470 +
2471 + if (!isset($headers['Last-Modified'])) {
2472 + $headers['Last-Modified'] = gmdate('D, d M Y H:i:s', time()) . ' GMT';
2473 + }
2474 +
2475 + return $headers;
2476 + }
2477 +
2478 + /**
2093 2479 * Includes dependency files
2094 2480 */
2095 2481 private function include_dependencies() {
2096 2482 if (!class_exists('WP_Optimize_Minify_Functions')) {
@@ -2117,15 +2503,15 @@
2117 2503 /**
2118 2504 * Handles header meta information removal
2119 2505 */
2120 2506 private function remove_header_meta_info() {
2121 - // no resource hints, generator tag, shortlinks, manifest link, etc
2507 + // no resource hints, generator tag, shortlink, manifest link, etc
2122 2508 remove_action('wp_head', 'wp_resource_hints', 2);
2123 2509 remove_action('wp_head', 'wp_generator');
2124 2510 remove_action('template_redirect', 'wp_shortlink_header', 11);
2125 2511 remove_action('wp_head', 'wlwmanifest_link');
2126 2512 remove_action('wp_head', 'rsd_link');
2127 - remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
2513 + remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
2128 2514 remove_action('wp_head', 'feed_links', 2);
2129 2515 remove_action('wp_head', 'feed_links_extra', 3);
2130 2516 WP_Optimize_Minify_Functions::remove_redundant_shortlink();
2131 2517 }
@@ -2151,11 +2537,65 @@
2151 2537 || ( 'all' === $this->options['enable_defer_js'] && 'async_using_js' === $this->options['defer_js_type'] )
2152 2538 ) {
2153 2539 add_action('wp_head', array('WP_Optimize_Minify_Print', 'add_load_async'), 0);
2154 2540 }
2541 +
2542 + // Process script module from generated html
2543 + ob_start(array($this, "process_script_modules"));
2155 2544 }
2156 2545
2157 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 + /**
2158 2598 * Handles css processing
2159 2599 */
2160 2600 private function process_css() {
2161 2601 add_action('wp_head', array($this, 'add_critical_path'), 2);
@@ -2161,11 +2601,11 @@
2161 2601 add_action('wp_head', array($this, 'add_critical_path'), 2);
2162 2602
2163 2603 // merge, if inline is selected but prevent optimization for these locations
2164 2604 if ($this->options['inline_css']) {
2165 - // 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'
2166 2606 add_filter('style_loader_tag', array($this, 'inline_css'), PHP_INT_MAX, 4);
2167 - // this prints the google fonts
2607 + // this prints the Google fonts
2168 2608 add_action('wp_print_styles', array($this, 'add_google_fonts_merged'), PHP_INT_MAX);
2169 2609 add_action('wp_print_footer_scripts', array($this, 'add_google_fonts_merged'), PHP_INT_MAX);
2170 2610 }
2171 2611 // Preloading
@@ -2171,14 +2611,14 @@
2171 2611 // Preloading
2172 2612 if ($this->options['enabled_css_preload']) {
2173 2613 add_filter('style_loader_tag', array($this, 'collect_css_preload_headers'), PHP_INT_MAX, 3);
2174 2614 }
2175 - // Optimize the css and collect the google fonts for merging
2615 + // Optimize the css and collect the Google fonts for merging
2176 2616 add_action('wp_print_styles', array($this, 'process_header_css'), PHP_INT_MAX);
2177 2617 add_action('wp_print_footer_scripts', array($this, 'process_footer_css'), 9);
2178 2618
2179 2619 /**
2180 - * 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
2181 2621 *
2182 2622 * @param boolean $maintain_css_order
2183 2623 * @return boolean
2184 2624 * @default true
@@ -2184,14 +2624,16 @@
2184 2624 * @default true
2185 2625 */
2186 2626 if (!apply_filters('wpo_minify_maintain_css_order', true)) {
2187 2627 // Reorder stylesheets
2188 - 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'));
2189 2629 }
2190 2630 }
2191 2631
2192 2632 /**
2193 2633 * Determines whether we should minify html or not
2634 + *
2635 + * @return bool
2194 2636 */
2195 2637 private function should_process_html() {
2196 2638 return $this->options['html_minification'] && !is_admin() && $this->is_cache_preload();
2197 2639 }
@@ -2197,8 +2639,10 @@
2197 2639 }
2198 2640
2199 2641 /**
2200 2642 * Determines whether to use loadCSS polyfill or not
2643 + *
2644 + * @return bool
2201 2645 */
2202 2646 private function should_use_loadCSS() {
2203 2647 return $this->options['loadcss']
2204 2648 || 'async' === $this->options['fawesome_method']
@@ -2209,8 +2653,9 @@
2209 2653 * Removes query string from static assets
2210 2654 */
2211 2655 private function remove_query_string_from_static_assets() {
2212 2656 add_filter('style_loader_src', array('WP_Optimize_Minify_Functions', 'remove_cssjs_ver'), 10, 2);
2657 + add_filter('script_loader_src', array('WP_Optimize_Minify_Functions', 'remove_cssjs_ver'), 10, 2);
2213 2658 }
2214 2659
2215 2660 /**
2216 2661 * Converts the lines in a textarea option value into an array
@@ -2269,6 +2714,64 @@
2269 2714 */
2270 2715 private function get_pre_connect_list() {
2271 2716 $pre_connect = $this->options['hpreconnect'];
2272 2717 return $this->convert_option_to_array($pre_connect);
2718 + }
2719 +
2720 + /**
2721 + * Array to string conversion
2722 + *
2723 + * @param array $arr
2724 + * @return string
2725 + */
2726 + private function array_to_string_conversion($arr) {
2727 + $str = '';
2728 + // implode won't work, because element can be an array
2729 + foreach ($arr as $value) {
2730 + $str .= is_array($value) ? '' : $value;
2731 + }
2732 + return $str;
2733 + }
2734 +
2735 + /**
2736 + * Decides whether minify cache should be incremented or not
2737 + *
2738 + * @param array $res
2739 + * @param string $href
2740 + * @param string $type
2741 + * @param string $handle
2742 + * @param mixed $version
2743 + *
2744 + * @return bool true when cache is invalid, false otherwise
2745 + */
2746 + private function should_reset_minify_assets($res, $href, $type, $handle, $version) {
2747 + if (isset($res['request']['version']) && $res['request']['version'] != $version && !$this->minify_cache_incremented) {
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);
2750 + $new_res = json_decode($new_json, true);
2751 +
2752 + /**
2753 + * In case `download_and_minify` fails because of
2754 + * Network issues, Syntax errors in updated code,
2755 + * Wrong use of `wpo_minify_get_js` and `wpo_minify_get_css` filters
2756 + * We don't want to invalidate current assets, so bail out
2757 + */
2758 + if (null === $new_res) return false;
2759 +
2760 + $hash = hash('sha256', $res['code']);
2761 + $new_hash = hash('sha256', $new_res['code']);
2762 + return strcmp($hash, $new_hash);
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;
2273 2776 }
2274 2777 }