PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.1.6
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.1.6
1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 1.2.0 All 28 releases
xspeed / includes / class-minifier.php

class-minifier.php in xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN 1.1.6, at includes/class-minifier.php

486 lines 19.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Asset minifier — HTML, CSS, JS.
4 *
5 * Uses matthiasmullie/minify for CSS/JS. Local enqueued assets are minified
6 * once, cached on disk, and the loader URL is rewritten to point at the
7 * cached file.
8 *
9 * @package XSpeed
10 */
11
12 namespace XSpeed;
13
14 defined( 'ABSPATH' ) || exit;
15
16 class Minifier {
17
18 const MIN_SUBDIR = 'min';
19
20 /**
21 * Absolute path to the minified-cache directory. Always derived from
22 * XSPEED_CACHE_DIR (the plugin's own cache root) — never assembled from
23 * arbitrary URL fragments.
24 */
25 public static function min_dir() {
26 return trailingslashit( XSPEED_CACHE_DIR ) . self::MIN_SUBDIR;
27 }
28
29 /**
30 * Public URL of the minified-cache directory. Built from content_url() +
31 * the known relative path, not by string-replacing WP_CONTENT_DIR out of
32 * a filesystem path (which would assume the filesystem layout matches
33 * the URL layout — it does not on Bedrock-style installs, multisite with
34 * mapped domains, or any setup with a relocated wp-content).
35 */
36 private static function min_url() {
37 // XSPEED_CACHE_DIR lives under wp-content (defined in xspeed.php as
38 // WP_CONTENT_DIR . '/cache/xspeed'), so the URL is content_url() +
39 // the known suffix. We do not derive URLs from arbitrary filesystem
40 // paths anywhere in this plugin.
41 $url = trailingslashit( content_url( 'cache/xspeed' ) ) . self::MIN_SUBDIR;
42 // Force the site's scheme: content_url() derives its scheme from
43 // is_ssl(), which is false behind a TLS-terminating reverse proxy, so
44 // it can emit an http:// URL on an https page — the browser then blocks
45 // the minified stylesheet as mixed content and the page renders
46 // unstyled. Match home_url()'s registered scheme instead. (FBS-83633)
47 $scheme = wp_parse_url( home_url(), PHP_URL_SCHEME ) ?: 'https';
48 return set_url_scheme( $url, $scheme );
49 }
50
51 public function __construct() {
52 // Only run on the frontend — never minify wp-admin, AJAX, REST or cron
53 // asset URLs. Page caching already handles the logged-in case for
54 // the HTML response; minify scope is the public frontend.
55 if ( is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) || ( defined( 'DOING_CRON' ) && DOING_CRON ) || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
56 return;
57 }
58
59 // Settings now live in the per-module option (xspeed_module_minify),
60 // owned by XSpeed\Modules\Minify\MinifyModule. We read through
61 // Settings_Manager so schema-validated values are returned even
62 // if the option was hand-edited.
63 $opts = Settings_Manager::get( 'minify' );
64
65 if ( ! empty( $opts['minify_css'] ) ) {
66 add_filter( 'style_loader_src', array( __CLASS__, 'rewrite_style' ), 10, 2 );
67 }
68 if ( ! empty( $opts['minify_js'] ) ) {
69 add_filter( 'script_loader_src', array( __CLASS__, 'rewrite_script' ), 10, 2 );
70 }
71
72 // Phase 4.1a — filter-only "smarter minifier" features. Each is
73 // gated on its own toggle so users can enable any subset.
74 if ( ! empty( $opts['remove_query_strings'] ) ) {
75 add_filter( 'style_loader_src', array( Minify_Filters::class, 'strip_version_query' ), 20 );
76 add_filter( 'script_loader_src', array( Minify_Filters::class, 'strip_version_query' ), 20 );
77 }
78 if ( ! empty( $opts['defer_js'] ) ) {
79 add_filter( 'script_loader_tag', array( Minify_Filters::class, 'defer_script_tag' ), 20, 3 );
80 }
81 if ( ! empty( $opts['delay_js'] ) ) {
82 // Delay applies a transform that's mutually exclusive with
83 // plain defer — when both are on, delay wins (the bootstrap
84 // will re-attach as a regular <script> on interaction).
85 add_filter( 'script_loader_tag', array( Minify_Filters::class, 'delay_script_tag' ), 30, 3 );
86 add_action( 'wp_footer', array( Minify_Filters::class, 'print_delay_bootstrap' ), 1000 );
87 // script_loader_tag only fires for wp_enqueue_script()'d assets.
88 // Analytics / pixel / chat-widget tags printed straight into
89 // wp_head bypass it, and those are usually the heaviest scripts
90 // on the page — so sweep the finished buffer too. Runs before
91 // minify_html (same filter, default priority) and is baked into
92 // the cache file, so it replays on static hits where PHP never
93 // boots.
94 add_filter( 'xspeed_cache_final_html', array( Minify_Filters::class, 'delay_raw_script_tags' ), 20 );
95 }
96 if ( ! empty( $opts['async_css'] ) ) {
97 add_filter( 'style_loader_tag', array( Minify_Filters::class, 'async_style_tag' ), 20, 2 );
98 }
99
100 /*
101 * CSS combining runs on the FINISHED HTML, not the enqueue queue.
102 *
103 * The queue-walking version could not be made correct: whatever it
104 * wrote at priority 999, WordPress edited afterwards. Core's
105 * wp_maybe_inline_styles() inlines any queued handle carrying a `path`
106 * and sets src=false on it, which silently threw away the combined URL
107 * and took the sheets we had blanked with it — six stylesheets became
108 * one and the site rendered unstyled. See Css_Combine_Buffer's header
109 * for the full trace. (#195)
110 *
111 * Two entry points, because the page cache's filter is not always
112 * available: `xspeed_cache_final_html` fires only on a cacheable MISS,
113 * so on a site with the cache off — or on an excluded URL like /cart —
114 * combining would silently stop working. Css_Combine_Buffer::boot()
115 * opens its own buffer in exactly those cases and no-ops otherwise, so
116 * the page is transformed once either way.
117 */
118 if ( ! empty( $opts['combine_css'] ) ) {
119 add_filter( 'xspeed_cache_final_html', array( Css_Combine_Buffer::class, 'process' ), 5 );
120 Css_Combine_Buffer::boot();
121 }
122 if ( ! empty( $opts['combine_js'] ) ) {
123 // JS stays on the enqueue path for now: dependency order,
124 // async/defer and wp_add_inline_script make it a different
125 // problem, and the reported break is CSS-only. Moving it is worth
126 // its own change rather than doubling the blast radius here.
127 add_action( 'wp_enqueue_scripts', array( Asset_Combiner::class, 'combine_scripts' ), 999 );
128 }
129 }
130
131 /**
132 * HTML elements that participate in an inline formatting context, where
133 * whitespace between two of them renders as a visible space.
134 *
135 * Deliberately excludes <br> (nothing to separate) and replaced/embedded
136 * inline elements that sit alone. Anything not listed is treated as block
137 * level, where inter-tag whitespace collapses to nothing and is safe to
138 * strip. (FBS-84090)
139 */
140 private const INLINE_TAGS = array(
141 'a', 'abbr', 'b', 'bdi', 'bdo', 'cite', 'code', 'data', 'del', 'dfn',
142 'em', 'i', 'ins', 'kbd', 'label', 'mark', 'q', 'rp', 'rt', 'ruby',
143 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u',
144 'var', 'wbr', 'img', 'button', 'select', 'output',
145 );
146
147 /** True when $tag renders inline, so whitespace beside it is visible. */
148 private static function is_inline( string $tag ): bool {
149 return in_array( strtolower( $tag ), self::INLINE_TAGS, true );
150 }
151
152 /**
153 * Why minification is being skipped, when it is. '' when it will run.
154 *
155 * minify_html can read "on" in every settings surface while producing
156 * byte-identical HTML, because the guard below silently returns the
157 * input. Field report: a live site showed `minify_html: on` with 3,856
158 * indented lines in the delivered HTML and nothing anywhere explaining
159 * the contradiction — the setting looked broken rather than suppressed.
160 * Callers that report status MUST consult this so the refusal is
161 * visible. (Same class as Cache::static_rewrite_block_reason().)
162 *
163 * @return string 'wp_debug', 'filter', or ''.
164 */
165 public static function skip_reason(): string {
166 $debug_skip = defined( 'WP_DEBUG' ) && WP_DEBUG;
167 if ( ! apply_filters( 'xspeed_skip_minify', $debug_skip ) ) {
168 return '';
169 }
170 // Distinguish the built-in WP_DEBUG rule from a third party
171 // filtering the escape hatch — the fixes are different.
172 return $debug_skip ? 'wp_debug' : 'filter';
173 }
174
175 public static function minify_html( $html ) {
176 if ( '' !== self::skip_reason() ) {
177 return $html;
178 }
179
180 $placeholders = array();
181 $pattern = '#<(pre|textarea|script|style)\b[^>]*>.*?</\1>#is';
182 $html = preg_replace_callback(
183 $pattern,
184 function ( $m ) use ( &$placeholders ) {
185 $key = '__XSPEED_PH_' . count( $placeholders ) . '__';
186 $placeholders[ $key ] = $m[0];
187 return $key;
188 },
189 $html
190 );
191
192 $html = preg_replace( '/<!--(?!\[if).*?-->/s', '', $html );
193 $html = preg_replace( '/\s+/', ' ', $html );
194
195 /*
196 * Collapse whitespace BETWEEN TAGS — but never where it is visible.
197 *
198 * Whitespace separating two INLINE elements is a real, rendered space:
199 * WooCommerce emits `</del> <ins>` for a sale price, and that single
200 * character is the gap between "$32.50" and "$29.50". Stripping it
201 * printed "$32.50$29.50" run together, and only with cache on — the
202 * un-minified page was fine. (FBS-84090)
203 *
204 * So the strip only applies when at least one side is a BLOCK-level
205 * (or non-rendered) tag, where the whitespace collapses away anyway.
206 * Inline-to-inline boundaries keep their single space.
207 */
208 $html = preg_replace_callback(
209 // left tag name (may be a closing tag) … whitespace … right tag name
210 '#</?([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>\s+<(/?)([a-zA-Z][a-zA-Z0-9-]*)#',
211 static function ( $m ) {
212 // Keep the space only when BOTH sides are inline elements —
213 // that is the one case where it is actually rendered.
214 $keep = self::is_inline( $m[1] ) && self::is_inline( $m[3] );
215 $open = substr( $m[0], 0, strrpos( $m[0], '<' ) ); // through the left tag's '>'
216 return rtrim( $open ) . ( $keep ? ' ' : '' ) . '<' . $m[2] . $m[3];
217 },
218 $html
219 );
220 $html = trim( $html );
221
222 foreach ( $placeholders as $key => $original ) {
223 $html = str_replace( $key, $original, $html );
224 }
225
226 return $html;
227 }
228
229 public static function rewrite_style( $src, $handle ) {
230 unset( $handle );
231 return self::rewrite_asset( $src, 'css' );
232 }
233
234 public static function rewrite_script( $src, $handle ) {
235 $rewritten = self::rewrite_asset( $src, 'js' );
236
237 // Remember the pre-minify URL for this handle. script_loader_tag
238 // runs later and only ever sees the rewritten src (a hashed
239 // /cache/xspeed/min/<key>.js path), so a user's URL-substring
240 // delay/exclusion target would never match once minification is
241 // on. Minify_Filters::original_src() gives those checks the URL
242 // the user actually wrote their target against. (FBS field report)
243 if ( is_string( $handle ) && '' !== $handle && is_string( $src ) && $src !== $rewritten ) {
244 Minify_Filters::remember_original_src( $handle, $src );
245 }
246
247 return $rewritten;
248 }
249
250 /**
251 * Replace a local CSS/JS URL with a cached, minified equivalent.
252 *
253 * @param string $src Original asset URL.
254 * @param string $type 'css' or 'js'.
255 * @return string Possibly rewritten URL.
256 */
257 private static function rewrite_asset( $src, $type ) {
258 if ( ! is_string( $src ) || '' === $src ) {
259 return $src;
260 }
261
262 // Skip already-minified files.
263 if ( false !== strpos( $src, '.min.' ) ) {
264 return $src;
265 }
266
267 // Skip anything we already produced. The Asset_Combiner writes a
268 // pre-minified combined-<hash>.css under min/combined/ and enqueues it
269 // as `xspeed-combined-css`; the per-file minifier used to re-minify
270 // that combined output into a SECOND file (min/<hash2>.css) with its
271 // own mtime-derived hash. The served HTML then pinned that second
272 // hash, so a purge/regeneration (which changes the combined file's
273 // mtime -> a new hash2) left the cached page pointing at a file that
274 // no longer existed -> 404 -> unstyled/broken frontend. Leaving our
275 // own cache output untouched keeps a single, stable URL end-to-end.
276 if ( false !== strpos( $src, '/cache/xspeed/' ) ) {
277 return $src;
278 }
279
280 // Resolve to a local path; bail if external or unresolvable.
281 $path = self::url_to_path( $src );
282 if ( ! $path || ! is_readable( $path ) ) {
283 return $src;
284 }
285
286 // Build a cache filename keyed on path + mtime so edits invalidate.
287 $mtime = filemtime( $path );
288 $key = md5( $path . '|' . $mtime );
289 $cache = self::cache_path( $key, $type );
290
291 if ( ! file_exists( $cache ) ) {
292 $ok = self::minify_file( $path, $cache, $type );
293 if ( ! $ok ) {
294 return $src;
295 }
296 }
297
298 // Return a URL to the cached file. Built from known constants — never
299 // from str_replace on a filesystem path (which would assume the FS
300 // layout mirrors the URL layout).
301 return self::min_url() . '/' . $key . '.' . $type;
302 }
303
304 private static function minify_file( $source_path, $target_path, $type ) {
305 if ( ! class_exists( '\\MatthiasMullie\\Minify\\CSS' ) ) {
306 return false;
307 }
308
309 // Path-traversal guard: refuse to write anywhere outside our cache
310 // dir, even if a malicious filter ever produced a poisoned key.
311 $cache_root = self::min_dir();
312 self::ensure_dir( $cache_root );
313 $real_root = realpath( $cache_root );
314 $real_dir = realpath( dirname( $target_path ) );
315 if ( ! $real_root || ! $real_dir || 0 !== strpos( $real_dir, $real_root ) ) {
316 return false;
317 }
318
319 try {
320 if ( 'css' === $type ) {
321 // Passing the TARGET path makes matthiasmullie/minify rebase every
322 // relative url(...) / @import against the minified file's location.
323 // Without it, a stylesheet moved from e.g.
324 // .../font-awesome/css/all.css to cache/xspeed/min/<key>.css keeps
325 // its original url(../webfonts/…) — which then resolves against the
326 // cache dir and 404s (missing FontAwesome/eicons/WooCommerce fonts).
327 $minifier = new \MatthiasMullie\Minify\CSS( $source_path );
328 $minified = $minifier->minify( $target_path );
329 return '' !== $minified && file_exists( $target_path );
330 }
331
332 $minifier = new \MatthiasMullie\Minify\JS( $source_path );
333 $minified = $minifier->minify();
334
335 // Sanity check: paren/brace/bracket/backtick balance must be preserved.
336 // matthiasmullie/minify can silently truncate mid-template-literal on
337 // complex modern JS — bail rather than ship a broken file.
338 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- WP_Filesystem requires admin context; minification runs on frontend page renders. Source already validated as readable on line 121.
339 $source = file_get_contents( $source_path );
340 if ( false === $source || ! self::balanced( $source, $minified ) ) {
341 return false;
342 }
343
344 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_put_contents_file_put_contents -- WP_Filesystem requires admin context; minification runs on frontend page renders.
345 $bytes = file_put_contents( $target_path, $minified );
346 return false !== $bytes && file_exists( $target_path );
347 } catch ( \Throwable $e ) {
348 return false;
349 }
350 }
351
352 /**
353 * Cheap structural sanity check between source + minified bodies.
354 *
355 * Counts paired-delimiter tokens (parens, braces, brackets, backticks)
356 * in each and bails when the counts disagree — matthiasmullie/minify
357 * has been observed to silently truncate inside template literals on
358 * complex modern JS (see commit history), shipping a body that LOOKS
359 * minified but is structurally broken and crashes the page at parse.
360 *
361 * Backticks are paired (open + close = same token), so the count
362 * itself must match exactly. Strings inside the source can contain
363 * literal `{` / `}` / `[` / `]` that throw off the count by the same
364 * amount in both bodies (since they survive minification as-is), so
365 * the equality check is robust to that noise.
366 */
367 private static function balanced( string $source, string $minified ): bool {
368 $pairs = array( '(', ')', '{', '}', '[', ']', '`' );
369 foreach ( $pairs as $token ) {
370 if ( substr_count( $source, $token ) !== substr_count( $minified, $token ) ) {
371 return false;
372 }
373 }
374 return true;
375 }
376
377 /**
378 * Resolve a local asset URL to a filesystem path using a strict allowlist
379 * of "URL prefix → filesystem prefix" pairs registered with WordPress.
380 *
381 * We never assume `site_url()` maps to `ABSPATH` (the WordPress root can
382 * live above the document root in Bedrock-style installs, behind a proxy,
383 * or on multisite with mapped domains). Each branch resolves through a
384 * known WP API (plugins, themes, content, includes) and validates that
385 * `realpath()` of the result still lives under the expected base — so a
386 * crafted `..`-laden URL cannot escape into the filesystem.
387 *
388 * @param string $url Asset URL (may be protocol-relative or absolute).
389 * @return string|false Absolute filesystem path on success, false otherwise.
390 */
391 private static function url_to_path( $url ) {
392 if ( ! is_string( $url ) || '' === $url ) {
393 return false;
394 }
395
396 // Drop query string + fragment.
397 $clean = strtok( $url, '?#' );
398
399 // Normalise protocol-relative + scheme variants of the host so we
400 // match regardless of whether the asset URL came in over http/https.
401 $site_host = wp_parse_url( home_url(), PHP_URL_HOST );
402 if ( 0 === strpos( $clean, '//' ) ) {
403 $clean = 'https:' . $clean;
404 }
405 if ( $site_host ) {
406 $asset_host = wp_parse_url( $clean, PHP_URL_HOST );
407 if ( $asset_host && $asset_host !== $site_host ) {
408 return false; // External asset — never touch.
409 }
410 }
411
412 $candidates = array(
413 array( plugins_url(), WP_PLUGIN_DIR ),
414 array( get_stylesheet_directory_uri(), get_stylesheet_directory() ),
415 array( get_template_directory_uri(), get_template_directory() ),
416 array( content_url(), WP_CONTENT_DIR ),
417 array( includes_url(), ABSPATH . WPINC ),
418 );
419
420 foreach ( $candidates as $pair ) {
421 list( $url_base, $path_base ) = $pair;
422 if ( ! $url_base || ! $path_base ) {
423 continue;
424 }
425 $url_base = rtrim( $url_base, '/' );
426 if ( 0 !== strpos( $clean, $url_base . '/' ) && $clean !== $url_base ) {
427 continue;
428 }
429
430 $relative = ltrim( substr( $clean, strlen( $url_base ) ), '/' );
431 $candidate = trailingslashit( $path_base ) . $relative;
432
433 $real_base = realpath( $path_base );
434 $real = realpath( $candidate );
435 if ( ! $real_base || ! $real ) {
436 return false;
437 }
438 // Guard against `..`-traversal: resolved path must stay inside
439 // the registered base.
440 if ( 0 !== strpos( $real, $real_base ) ) {
441 return false;
442 }
443 return $real;
444 }
445
446 return false;
447 }
448
449 private static function cache_path( $key, $type ) {
450 return self::min_dir() . '/' . $key . '.' . $type;
451 }
452
453 private static function ensure_dir( $dir ) {
454 if ( ! file_exists( $dir ) ) {
455 wp_mkdir_p( $dir );
456 Cache::write_silence( $dir );
457 }
458 }
459
460 public static function purge_minified() {
461 self::rmtree_files( self::min_dir() );
462 }
463
464 /**
465 * Recursively delete every file under $dir (and the emptied
466 * subdirectories), keeping $dir itself. The previous glob('$dir/*')
467 * was non-recursive and no-ops on directories, so combined assets in
468 * min/combined/ were never cleared — a purge left a stale
469 * combined-<hash>.css the regenerated page no longer referenced.
470 * (FBS-83114 / FBS-83116)
471 */
472 private static function rmtree_files( string $dir ): void {
473 if ( ! is_dir( $dir ) ) {
474 return;
475 }
476 foreach ( (array) glob( $dir . '/*' ) as $path ) {
477 if ( is_dir( $path ) ) {
478 self::rmtree_files( $path );
479 @rmdir( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir, WordPress.PHP.NoSilencedErrors.Discouraged -- best-effort cleanup of our own cache subdir; WP_Filesystem is unavailable on the frontend purge path.
480 continue;
481 }
482 wp_delete_file( $path );
483 }
484 }
485 }
486