PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.4.1
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.4.1
1.4.1 1.4.0 1.3.7 1.3.6 1.3.5 1.3.4 1.3.3 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 All 35 releases
← All changes | includes/class-minifier.php +592 -55 1.0.5 → 1.4.1 View file →
@@ -21,9 +21,9 @@
21 21 * Absolute path to the minified-cache directory. Always derived from
22 22 * XSPEED_CACHE_DIR (the plugin's own cache root) — never assembled from
23 23 * arbitrary URL fragments.
24 24 */
25 - private static function min_dir() {
25 + public static function min_dir() {
26 26 return trailingslashit( XSPEED_CACHE_DIR ) . self::MIN_SUBDIR;
27 27 }
28 28
29 29 /**
@@ -37,9 +37,16 @@
37 37 // XSPEED_CACHE_DIR lives under wp-content (defined in xspeed.php as
38 38 // WP_CONTENT_DIR . '/cache/xspeed'), so the URL is content_url() +
39 39 // the known suffix. We do not derive URLs from arbitrary filesystem
40 40 // paths anywhere in this plugin.
41 - return trailingslashit( content_url( 'cache/xspeed' ) ) . self::MIN_SUBDIR;
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 );
42 49 }
43 50
44 51 public function __construct() {
45 52 // Only run on the frontend — never minify wp-admin, AJAX, REST or cron
@@ -48,8 +55,17 @@
48 55 if ( is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) || ( defined( 'DOING_CRON' ) && DOING_CRON ) || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
49 56 return;
50 57 }
51 58
59 + // A page-builder editing screen is a front-end URL, so none of the
60 + // guards above catch it. Optimizing it breaks the editor outright --
61 + // Combine JS reorders the builder's own dependency graph and the
62 + // toolbar never renders. There is no speed to win on a logged-in,
63 + // uncacheable editing request anyway. (#281)
64 + if ( Builder_Editor::is_active() ) {
65 + return;
66 + }
67 +
52 68 // Settings now live in the per-module option (xspeed_module_minify),
53 69 // owned by XSpeed\Modules\Minify\MinifyModule. We read through
54 70 // Settings_Manager so schema-validated values are returned even
55 71 // if the option was hand-edited.
@@ -59,8 +75,15 @@
59 75 add_filter( 'style_loader_src', array( __CLASS__, 'rewrite_style' ), 10, 2 );
60 76 }
61 77 if ( ! empty( $opts['minify_js'] ) ) {
62 78 add_filter( 'script_loader_src', array( __CLASS__, 'rewrite_script' ), 10, 2 );
79 + // The src rewrite above runs before any plugin's own
80 + // `script_loader_tag` filter can stamp data-no-minify /
81 + // data-no-optimize onto the tag, so the marker arrives too late
82 + // to prevent it. Priority 15: after third-party tag filters at
83 + // the default 10 have printed their markers, before our defer
84 + // (20) and delay (30) look at the tag. (#456)
85 + add_filter( 'script_loader_tag', array( Minify_Filters::class, 'restore_marked_script_src' ), 15, 3 );
63 86 }
64 87
65 88 // Phase 4.1a — filter-only "smarter minifier" features. Each is
66 89 // gated on its own toggle so users can enable any subset.
@@ -75,28 +98,138 @@
75 98 // Delay applies a transform that's mutually exclusive with
76 99 // plain defer — when both are on, delay wins (the bootstrap
77 100 // will re-attach as a regular <script> on interaction).
78 101 add_filter( 'script_loader_tag', array( Minify_Filters::class, 'delay_script_tag' ), 30, 3 );
102 + // Smart Delay: a delayed handle's before/after snippets park with
103 + // it, or the inline consumer would run at parse time against a
104 + // global that now arrives on first interaction. This filter fires
105 + // for every inline script WordPress prints, so it also covers
106 + // pages the cache buffer never filters.
107 + add_filter( 'wp_inline_script_attributes', array( Minify_Filters::class, 'park_smart_inline' ), 30, 2 );
108 + // A snippet never stays parked behind a live script. Runs after
109 + // the late opt-out revert, which can un-delay the tag.
110 + add_filter( 'script_loader_tag', array( Minify_Filters::class, 'unpark_orphaned_smart_inline' ), Minify_Filters::late_opt_out_priority() + 1, 3 );
79 111 add_action( 'wp_footer', array( Minify_Filters::class, 'print_delay_bootstrap' ), 1000 );
112 + // script_loader_tag only fires for wp_enqueue_script()'d assets.
113 + // Analytics / pixel / chat-widget tags printed straight into
114 + // wp_head bypass it, and those are usually the heaviest scripts
115 + // on the page — so sweep the finished buffer too. Runs before
116 + // minify_html (same filter, default priority) and is baked into
117 + // the cache file, so it replays on static hits where PHP never
118 + // boots.
119 + add_filter( 'xspeed_cache_final_html', array( Minify_Filters::class, 'delay_raw_script_tags' ), 20 );
120 + // The vendors' own install snippets are INLINE (no src at all),
121 + // so the src sweep above never sees them; this one parks an
122 + // inline body that names a known third-party host.
123 + add_filter( 'xspeed_cache_final_html', array( Minify_Filters::class, 'delay_inline_snippets' ), 21 );
80 124 }
125 +
126 + // Everything above honors data-no-optimize / data-no-minify, but
127 + // only sees markers stamped before priority 30. Borlabs Cookie
128 + // stamps at 100, so its consent config was minified AND delayed
129 + // despite carrying both markers. Snapshot the tag before our
130 + // transforms (9) and hand the original back if a marker turns up
131 + // after them (1000, past Borlabs' own 100 and 999). Registered
132 + // whenever any of the three is on,
133 + // since each one is individually enough to damage a marked
134 + // script. (#469)
135 + if ( ! empty( $opts['minify_js'] ) || ! empty( $opts['defer_js'] ) || ! empty( $opts['delay_js'] ) ) {
136 + add_filter( 'script_loader_tag', array( Minify_Filters::class, 'snapshot_tag' ), 9, 3 );
137 + add_filter(
138 + 'script_loader_tag',
139 + array( Minify_Filters::class, 'revert_late_marked_tag' ),
140 + Minify_Filters::late_opt_out_priority(),
141 + 3
142 + );
143 + }
81 144 if ( ! empty( $opts['async_css'] ) ) {
82 145 add_filter( 'style_loader_tag', array( Minify_Filters::class, 'async_style_tag' ), 20, 2 );
146 + // style_loader_tag only fires for wp_enqueue_style()'d sheets.
147 + // Themes print Google/Bunny/Typekit font CSS as literal <link>
148 + // markup in the head, so those sheets never reach the filter and
149 + // stay render-blocking — sweep the finished buffer for the known
150 + // font-CSS hosts. Baked into the cache file, so it replays on
151 + // static hits where PHP never boots.
152 + add_filter( 'xspeed_cache_final_html', array( Minify_Filters::class, 'async_raw_font_css_links' ), 22 );
83 153 }
84 154
85 - // Phase 4.1b — combine engine. Hook late so every plugin /
86 - // theme has finished enqueueing by the time we walk the queue.
87 - // Priority 999 mirrors the WP-Optimize / Rocket convention.
155 + /*
156 + * CSS combining runs on the FINISHED HTML, not the enqueue queue.
157 + *
158 + * The queue-walking version could not be made correct: whatever it
159 + * wrote at priority 999, WordPress edited afterwards. Core's
160 + * wp_maybe_inline_styles() inlines any queued handle carrying a `path`
161 + * and sets src=false on it, which silently threw away the combined URL
162 + * and took the sheets we had blanked with it — six stylesheets became
163 + * one and the site rendered unstyled. See Css_Combine_Buffer's header
164 + * for the full trace. (#195)
165 + *
166 + * Two entry points, because the page cache's filter is not always
167 + * available: `xspeed_cache_final_html` fires only on a cacheable MISS,
168 + * so on a site with the cache off — or on an excluded URL like /cart —
169 + * combining would silently stop working. Css_Combine_Buffer::boot()
170 + * opens its own buffer in exactly those cases and no-ops otherwise, so
171 + * the page is transformed once either way.
172 + */
88 173 if ( ! empty( $opts['combine_css'] ) ) {
89 - add_action( 'wp_enqueue_scripts', array( Asset_Combiner::class, 'combine_styles' ), 999 );
174 + add_filter( 'xspeed_cache_final_html', array( Css_Combine_Buffer::class, 'process' ), 5 );
175 + Css_Combine_Buffer::boot();
90 176 }
91 177 if ( ! empty( $opts['combine_js'] ) ) {
178 + // JS stays on the enqueue path for now: dependency order,
179 + // async/defer and wp_add_inline_script make it a different
180 + // problem, and the reported break is CSS-only. Moving it is worth
181 + // its own change rather than doubling the blast radius here.
92 182 add_action( 'wp_enqueue_scripts', array( Asset_Combiner::class, 'combine_scripts' ), 999 );
93 183 }
94 184 }
95 185
186 + /**
187 + * HTML elements that participate in an inline formatting context, where
188 + * whitespace between two of them renders as a visible space.
189 + *
190 + * Deliberately excludes <br> (nothing to separate) and replaced/embedded
191 + * inline elements that sit alone. Anything not listed is treated as block
192 + * level, where inter-tag whitespace collapses to nothing and is safe to
193 + * strip. (FBS-84090)
194 + */
195 + private const INLINE_TAGS = array(
196 + 'a', 'abbr', 'b', 'bdi', 'bdo', 'cite', 'code', 'data', 'del', 'dfn',
197 + 'em', 'i', 'ins', 'kbd', 'label', 'mark', 'q', 'rp', 'rt', 'ruby',
198 + 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u',
199 + 'var', 'wbr', 'img', 'button', 'select', 'output',
200 + );
201 +
202 + /** True when $tag renders inline, so whitespace beside it is visible. */
203 + private static function is_inline( string $tag ): bool {
204 + return in_array( strtolower( $tag ), self::INLINE_TAGS, true );
205 + }
206 +
207 + /**
208 + * Why minification is being skipped, when it is. '' when it will run.
209 + *
210 + * minify_html can read "on" in every settings surface while producing
211 + * byte-identical HTML, because the guard below silently returns the
212 + * input. Field report: a live site showed `minify_html: on` with 3,856
213 + * indented lines in the delivered HTML and nothing anywhere explaining
214 + * the contradiction — the setting looked broken rather than suppressed.
215 + * Callers that report status MUST consult this so the refusal is
216 + * visible. (Same class as Cache::static_rewrite_block_reason().)
217 + *
218 + * @return string 'wp_debug', 'filter', or ''.
219 + */
220 + public static function skip_reason(): string {
221 + $debug_skip = defined( 'WP_DEBUG' ) && WP_DEBUG;
222 + if ( ! apply_filters( 'xspeed_skip_minify', $debug_skip ) ) {
223 + return '';
224 + }
225 + // Distinguish the built-in WP_DEBUG rule from a third party
226 + // filtering the escape hatch — the fixes are different.
227 + return $debug_skip ? 'wp_debug' : 'filter';
228 + }
229 +
96 230 public static function minify_html( $html ) {
97 - $debug_skip = defined( 'WP_DEBUG' ) && WP_DEBUG;
98 - if ( apply_filters( 'xspeed_skip_minify', $debug_skip ) ) {
231 + if ( '' !== self::skip_reason() ) {
99 232 return $html;
100 233 }
101 234
102 235 $placeholders = array();
@@ -103,10 +236,18 @@
103 236 $pattern = '#<(pre|textarea|script|style)\b[^>]*>.*?</\1>#is';
104 237 $html = preg_replace_callback(
105 238 $pattern,
106 239 function ( $m ) use ( &$placeholders ) {
107 - $key = '__XSPEED_PH_' . count( $placeholders ) . '__';
108 - $placeholders[ $key ] = $m[0];
240 + $key = '__XSPEED_PH_' . count( $placeholders ) . '__';
241 + // The placeholder pass exists to protect content whose
242 + // whitespace is significant (<pre>, <textarea>) and to keep
243 + // the tag-boundary regex off script bodies. <style> and
244 + // <script> were grouped in with them, so protection became a
245 + // permanent exemption: on builder sites where most CSS is
246 + // inline, a page with minify ON shipped fully indented. Minify
247 + // the BODY here, before it's stashed, so the outer passes
248 + // still never see it. (#2)
249 + $placeholders[ $key ] = self::minify_inline_block( $m[0], strtolower( $m[1] ) );
109 250 return $key;
110 251 },
111 252 $html
112 253 );
@@ -112,9 +253,34 @@
112 253 );
113 254
114 255 $html = preg_replace( '/<!--(?!\[if).*?-->/s', '', $html );
115 256 $html = preg_replace( '/\s+/', ' ', $html );
116 - $html = preg_replace( '/>\s+</', '><', $html );
257 +
258 + /*
259 + * Collapse whitespace BETWEEN TAGS — but never where it is visible.
260 + *
261 + * Whitespace separating two INLINE elements is a real, rendered space:
262 + * WooCommerce emits `</del> <ins>` for a sale price, and that single
263 + * character is the gap between "$32.50" and "$29.50". Stripping it
264 + * printed "$32.50$29.50" run together, and only with cache on — the
265 + * un-minified page was fine. (FBS-84090)
266 + *
267 + * So the strip only applies when at least one side is a BLOCK-level
268 + * (or non-rendered) tag, where the whitespace collapses away anyway.
269 + * Inline-to-inline boundaries keep their single space.
270 + */
271 + $html = preg_replace_callback(
272 + // left tag name (may be a closing tag) … whitespace … right tag name
273 + '#</?([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>\s+<(/?)([a-zA-Z][a-zA-Z0-9-]*)#',
274 + static function ( $m ) {
275 + // Keep the space only when BOTH sides are inline elements —
276 + // that is the one case where it is actually rendered.
277 + $keep = self::is_inline( $m[1] ) && self::is_inline( $m[3] );
278 + $open = substr( $m[0], 0, strrpos( $m[0], '<' ) ); // through the left tag's '>'
279 + return rtrim( $open ) . ( $keep ? ' ' : '' ) . '<' . $m[2] . $m[3];
280 + },
281 + $html
282 + );
117 283 $html = trim( $html );
118 284
119 285 foreach ( $placeholders as $key => $original ) {
120 286 $html = str_replace( $key, $original, $html );
@@ -128,10 +294,21 @@
128 294 return self::rewrite_asset( $src, 'css' );
129 295 }
130 296
131 297 public static function rewrite_script( $src, $handle ) {
132 - unset( $handle );
133 - return self::rewrite_asset( $src, 'js' );
298 + $rewritten = self::rewrite_asset( $src, 'js' );
299 +
300 + // Remember the pre-minify URL for this handle. script_loader_tag
301 + // runs later and only ever sees the rewritten src (a hashed
302 + // /cache/xspeed/min/<key>.js path), so a user's URL-substring
303 + // delay/exclusion target would never match once minification is
304 + // on. Minify_Filters::original_src() gives those checks the URL
305 + // the user actually wrote their target against. (FBS field report)
306 + if ( is_string( $handle ) && '' !== $handle && is_string( $src ) && $src !== $rewritten ) {
307 + Minify_Filters::remember_original_src( $handle, $src );
308 + }
309 +
310 + return $rewritten;
134 311 }
135 312
136 313 /**
137 314 * Replace a local CSS/JS URL with a cached, minified equivalent.
@@ -149,8 +326,23 @@
149 326 if ( false !== strpos( $src, '.min.' ) ) {
150 327 return $src;
151 328 }
152 329
330 + // Skip anything we already produced. The Asset_Combiner minifies the
331 + // combined body itself before writing combined-<hash>.css under
332 + // min/combined/ (issue #331 — that used to be asserted here but was
333 + // not actually true, so the artifact shipped unminified), and enqueues it
334 + // as `xspeed-combined-css`; the per-file minifier used to re-minify
335 + // that combined output into a SECOND file (min/<hash2>.css) with its
336 + // own mtime-derived hash. The served HTML then pinned that second
337 + // hash, so a purge/regeneration (which changes the combined file's
338 + // mtime -> a new hash2) left the cached page pointing at a file that
339 + // no longer existed -> 404 -> unstyled/broken frontend. Leaving our
340 + // own cache output untouched keeps a single, stable URL end-to-end.
341 + if ( false !== strpos( $src, '/cache/xspeed/' ) ) {
342 + return $src;
343 + }
344 +
153 345 // Resolve to a local path; bail if external or unresolvable.
154 346 $path = self::url_to_path( $src );
155 347 if ( ! $path || ! is_readable( $path ) ) {
156 348 return $src;
@@ -155,18 +347,37 @@
155 347 if ( ! $path || ! is_readable( $path ) ) {
156 348 return $src;
157 349 }
158 350
159 - // Build a cache filename keyed on path + mtime so edits invalidate.
160 - $mtime = filemtime( $path );
161 - $key = md5( $path . '|' . $mtime );
162 - $cache = self::cache_path( $key, $type );
351 + // Nowhere to write means nothing to serve. Without this gate an
352 + // unwritable min/ cost a full minification on EVERY render, each one
353 + // thrown away when the write failed.
354 + if ( ! self::min_dir_writable() ) {
355 + return $src;
356 + }
163 357
164 - if ( ! file_exists( $cache ) ) {
165 - $ok = self::minify_file( $path, $cache, $type );
166 - if ( ! $ok ) {
167 - return $src;
358 + // The file is named after its minified CONTENT, found through a
359 + // per-source manifest that is validated by stat() alone on the hot
360 + // path. See Asset_Manifest for the rules. The old name was
361 + // md5(path|mtime): an in-place edit that kept the mtime served new
362 + // bytes under a URL cached for a year, an @import child's edit
363 + // changed nothing, and a touch with no change orphaned every cached
364 + // page that linked the old name.
365 + $key = Asset_Manifest::key_for(
366 + $type,
367 + $path,
368 + static function ( string $source ) use ( $type ): array {
369 + return 'css' === $type ? Asset_Manifest::css_dependencies( $source ) : array();
370 + },
371 + static function ( string $source ) use ( $type ) {
372 + return self::build( $source, $type );
373 + },
374 + static function ( string $key ) use ( $type ): bool {
375 + return file_exists( self::cache_path( $key, $type ) );
168 376 }
377 + );
378 + if ( null === $key ) {
379 + return $src;
169 380 }
170 381
171 382 // Return a URL to the cached file. Built from known constants — never
172 383 // from str_replace on a filesystem path (which would assume the FS
@@ -173,44 +384,110 @@
173 384 // layout mirrors the URL layout).
174 385 return self::min_url() . '/' . $key . '.' . $type;
175 386 }
176 387
177 - private static function minify_file( $source_path, $target_path, $type ) {
178 - if ( ! class_exists( '\\MatthiasMullie\\Minify\\CSS' ) ) {
179 - return false;
388 + /**
389 + * Whether min/ can be written, asked once per request.
390 + *
391 + * @var bool|null
392 + */
393 + private static $writable = null;
394 +
395 + /**
396 + * Minifications run by this process.
397 + *
398 + * @var int
399 + */
400 + private static $builds = 0;
401 +
402 + /** Forget the per-request answers. Tests only. */
403 + public static function reset_request_state(): void {
404 + self::$writable = null;
405 + self::$builds = 0;
406 + }
407 +
408 + /** How many sources this process has minified. Tests and diagnostics. */
409 + public static function builds(): int {
410 + return self::$builds;
411 + }
412 +
413 + /** Can minified files be written this request? */
414 + public static function min_dir_writable(): bool {
415 + if ( null === self::$writable ) {
416 + $dir = self::min_dir();
417 + self::ensure_dir( $dir );
418 + self::$writable = is_dir( $dir ) && wp_is_writable( $dir );
180 419 }
420 + return self::$writable;
421 + }
181 422
182 - // Path-traversal guard: refuse to write anywhere outside our cache
183 - // dir, even if a malicious filter ever produced a poisoned key.
184 - $cache_root = self::min_dir();
185 - self::ensure_dir( $cache_root );
186 - $real_root = realpath( $cache_root );
187 - $real_dir = realpath( dirname( $target_path ) );
188 - if ( ! $real_root || ! $real_dir || 0 !== strpos( $real_dir, $real_root ) ) {
189 - return false;
423 + /**
424 + * Minify a source into min/<md5 of output>.<type> and return the key.
425 + *
426 + * The output is built in memory and published with an atomic rename, so a
427 + * concurrent render never links a half-written file. When a file with the
428 + * same content already exists nothing is written: same bytes, same name.
429 + *
430 + * @param string $source Absolute source path.
431 + * @param string $type 'css' or 'js'.
432 + * @return string|null|false Key; null when the source cannot be minified;
433 + * false when the output could not be written.
434 + */
435 + private static function build( string $source, string $type ) {
436 + ++self::$builds;
437 + $minified = self::minify_to_string( $source, $type );
438 + if ( null === $minified ) {
439 + return null;
190 440 }
441 + $key = md5( $minified );
442 + $target = self::cache_path( $key, $type );
443 + if ( file_exists( $target ) ) {
444 + return $key;
445 + }
446 + return Asset_Manifest::write_atomic( $target, $minified ) ? $key : false;
447 + }
191 448
449 + /**
450 + * Minified bytes of a source, or null on failure.
451 + *
452 + * @param string $source_path Absolute source path.
453 + * @param string $type 'css' or 'js'.
454 + */
455 + private static function minify_to_string( string $source_path, string $type ): ?string {
456 + if ( ! class_exists( '\\MatthiasMullie\\Minify\\CSS' ) ) {
457 + return null;
458 + }
459 +
192 460 try {
193 - $minifier = ( 'css' === $type )
194 - ? new \MatthiasMullie\Minify\CSS( $source_path )
195 - : new \MatthiasMullie\Minify\JS( $source_path );
461 + if ( 'css' === $type ) {
462 + // execute() with a path inside min/ rebases every relative
463 + // url(...) / @import against the minified file's location,
464 + // which is what minify( $target ) did before without writing.
465 + // Every output lives in the same directory, so any name there
466 + // rebases identically. Without the rebase a stylesheet moved
467 + // from e.g. .../font-awesome/css/all.css to
468 + // cache/xspeed/min/<key>.css keeps its original
469 + // url(../webfonts/…), which then resolves against the cache
470 + // dir and 404s (missing FontAwesome/eicons/WooCommerce fonts).
471 + $minifier = new \MatthiasMullie\Minify\CSS( $source_path );
472 + $minified = (string) $minifier->execute( self::min_dir() . '/rebase.css' );
473 + return '' !== $minified ? $minified : null;
474 + }
196 475
197 - $minified = $minifier->minify();
476 + $minifier = new \MatthiasMullie\Minify\JS( $source_path );
477 + $minified = (string) $minifier->minify();
198 478
199 479 // Sanity check: paren/brace/bracket/backtick balance must be preserved.
200 480 // matthiasmullie/minify can silently truncate mid-template-literal on
201 481 // complex modern JS — bail rather than ship a broken file.
202 - // 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.
482 + // 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 by the caller.
203 483 $source = file_get_contents( $source_path );
204 - if ( false === $source || ! self::balanced( $source, $minified ) ) {
205 - return false;
484 + if ( false === $source || '' === $minified || ! self::balanced( $source, $minified ) ) {
485 + return null;
206 486 }
207 -
208 - // phpcs:ignore WordPress.WP.AlternativeFunctions.file_put_contents_file_put_contents -- WP_Filesystem requires admin context; minification runs on frontend page renders.
209 - $bytes = file_put_contents( $target_path, $minified );
210 - return false !== $bytes && file_exists( $target_path );
487 + return $minified;
211 488 } catch ( \Throwable $e ) {
212 - return false;
489 + return null;
213 490 }
214 491 }
215 492
216 493 /**
@@ -227,18 +504,175 @@
227 504 * literal `{` / `}` / `[` / `]` that throw off the count by the same
228 505 * amount in both bodies (since they survive minification as-is), so
229 506 * the equality check is robust to that noise.
230 507 */
231 - private static function balanced( string $source, string $minified ): bool {
232 - $pairs = array( '(', ')', '{', '}', '[', ']', '`' );
233 - foreach ( $pairs as $token ) {
234 - if ( substr_count( $source, $token ) !== substr_count( $minified, $token ) ) {
508 + /**
509 + * Minify the body of one captured inline block, or return it untouched.
510 + *
511 + * Only `<style>` and JavaScript `<script>` bodies are eligible:
512 + *
513 + * - `<pre>` / `<textarea>` — whitespace is rendered, never touch it.
514 + * - `<script>` with a non-JS `type` — `application/ld+json`,
515 + * `text/template`, `text/x-handlebars` and anything unrecognised are
516 + * data or markup, not code. Minifying JSON-LD would corrupt structured
517 + * data; minifying a template would eat the markup it holds. An unknown
518 + * type is treated as non-JS on purpose: guessing wrong breaks the page,
519 + * while skipping only forgoes a few bytes.
520 + * - `<script src="...">` — the body is empty; the file path already goes
521 + * through rewrite_asset().
522 + *
523 + * Every result is checked with balanced(), the same structural guard the
524 + * file path uses, so a body the library truncates is shipped as-is rather
525 + * than broken. (#2)
526 + *
527 + * @param string $block Full matched tag, opening tag through closing tag.
528 + * @param string $tag Lowercased tag name.
529 + * @return string Minified block, or $block unchanged.
530 + */
531 + private static function minify_inline_block( string $block, string $tag ): string {
532 + if ( 'style' !== $tag && 'script' !== $tag ) {
533 + return $block; // pre / textarea — significant whitespace.
534 + }
535 + if ( ! class_exists( '\\MatthiasMullie\\Minify\\CSS' ) ) {
536 + return $block;
537 + }
538 +
539 + // Split into opening tag / body / closing tag. Anything that doesn't
540 + // match this shape isn't something we should be rewriting.
541 + if ( ! preg_match( '#^(<' . $tag . '\b[^>]*>)(.*)(</' . $tag . '\s*>)$#is', $block, $parts ) ) {
542 + return $block;
543 + }
544 + list( , $open, $body, $close ) = $parts;
545 +
546 + if ( '' === trim( $body ) ) {
547 + return $block;
548 + }
549 +
550 + // The tag asked to be left alone (data-no-optimize / data-no-minify —
551 + // the convention consent managers print on their config scripts). (#456)
552 + if ( Minify_Filters::tag_opts_out( $open ) ) {
553 + return $block;
554 + }
555 +
556 + // Refuse a body that is already structurally broken. balanced() only
557 + // compares source against minified, so it passes when BOTH are equally
558 + // unbalanced — `function x( {` minifies to `function x({`, same counts,
559 + // guard satisfied, broken code reformatted. Rewriting a body we can't
560 + // parse risks turning a page that happens to work into one that does
561 + // not, for no gain. (#2 AC: a syntactically broken block is left
562 + // untouched.)
563 + if ( ! self::self_consistent( $body ) ) {
564 + return $block;
565 + }
566 +
567 + if ( 'script' === $tag ) {
568 + // An external script has no body worth minifying.
569 + if ( preg_match( '#\bsrc\s*=#i', $open ) ) {
570 + return $block;
571 + }
572 + // No type, or an explicitly JavaScript type, is code. Everything
573 + // else is data/markup — see the docblock.
574 + $js_types = array(
575 + 'text/javascript',
576 + 'application/javascript',
577 + 'application/ecmascript',
578 + 'text/ecmascript',
579 + 'module',
580 + );
581 + if ( preg_match( '#\btype\s*=\s*["\']?([^"\'\s>]+)#i', $open, $type_match ) ) {
582 + if ( ! in_array( strtolower( trim( $type_match[1] ) ), $js_types, true ) ) {
583 + return $block;
584 + }
585 + }
586 + }
587 +
588 + try {
589 + $minifier = 'style' === $tag
590 + ? new \MatthiasMullie\Minify\CSS()
591 + : new \MatthiasMullie\Minify\JS();
592 + $minifier->add( $body );
593 + $minified = $minifier->minify();
594 + } catch ( \Throwable $e ) {
595 + return $block;
596 + }
597 +
598 + // A minifier that returns nothing for a non-empty body has failed, not
599 + // succeeded — shipping '' would silently delete the rule set.
600 + if ( ! is_string( $minified ) || '' === trim( $minified ) ) {
601 + return $block;
602 + }
603 + if ( ! self::balanced( $body, $minified ) ) {
604 + return $block;
605 + }
606 +
607 + return $open . $minified . $close;
608 + }
609 +
610 + /**
611 + * Does a body's own paired delimiters balance?
612 + *
613 + * balanced() is a RELATIVE check — source against minified — so it cannot
614 + * see input that was already broken: an unbalanced body minifies to an
615 + * equally unbalanced one and the counts still agree. This is the absolute
616 + * check, applied to the source alone before we touch it.
617 + *
618 + * Deliberately naive: it counts tokens without parsing, so a brace inside
619 + * a string or comment skews it. That only ever makes it MORE conservative —
620 + * a false negative skips minification, which costs bytes, while a false
621 + * positive would ship broken code. (#2)
622 + *
623 + * @param string $body Inline block body.
624 + */
625 + private static function self_consistent( string $body ): bool {
626 + $pairs = array(
627 + '{' => '}',
628 + '(' => ')',
629 + '[' => ']',
630 + );
631 + foreach ( $pairs as $open => $close ) {
632 + if ( substr_count( $body, $open ) !== substr_count( $body, $close ) ) {
235 633 return false;
236 634 }
237 635 }
636 + // Backticks and quotes pair with themselves, so an odd count means an
637 + // unterminated literal.
638 + foreach ( array( '`' ) as $token ) {
639 + if ( 0 !== substr_count( $body, $token ) % 2 ) {
640 + return false;
641 + }
642 + }
238 643 return true;
239 644 }
240 645
646 + private static function balanced( string $source, string $minified ): bool {
647 + unset( $source );
648 +
649 + // Judge the OUTPUT, not the difference between input and output.
650 + //
651 + // This used to compare token counts across the pair, on the stated
652 + // assumption that "literal braces inside strings survive minification
653 + // unchanged, so they cancel out". Comments do not: stripping them is
654 + // the minifier's whole job, and every brace, bracket and backtick
655 + // inside one disappears with it. So any file whose comments contain a
656 + // delimiter — a commented-out block, a URL in a docblock, an SVG in a
657 + // note — failed the check and silently shipped unminified.
658 + //
659 + // It is not a rare shape. EmbedPress's front.js counts 372 braces
660 + // against 368, 61 brackets against 58 and 110 backticks against 102
661 + // purely from comment removal, so 67 KB shipped raw where 46 KB was
662 + // correct — and `node --check` confirms that rejected output parses
663 + // fine. A guard that refuses valid work is not conservative, it is
664 + // broken: it costs bytes on every request and reports nothing.
665 + //
666 + // What the guard is FOR still stands (#2): matthiasmullie/minify can
667 + // truncate inside a template literal on complex modern JS and return a
668 + // body that looks minified but is structurally broken. That failure is
669 + // visible in the output alone — an unterminated literal leaves an odd
670 + // backtick count and unmatched braces — which is exactly what
671 + // self_consistent() measures, without the false positives.
672 + return self::self_consistent( $minified );
673 + }
674 +
241 675 /**
242 676 * Resolve a local asset URL to a filesystem path using a strict allowlist
243 677 * of "URL prefix → filesystem prefix" pairs registered with WordPress.
244 678 *
@@ -280,19 +714,40 @@
280 714 array( content_url(), WP_CONTENT_DIR ),
281 715 array( includes_url(), ABSPATH . WPINC ),
282 716 );
283 717
718 + // The host check above normalised the HOST but not the SCHEME, and the
719 + // prefix match below is a plain string compare — so an https asset URL
720 + // never matched an http base and the file silently shipped unminified.
721 + // That is not a corner case: WP_CONTENT_URL is derived from a stored
722 + // option, `plugins_url()` from another, and a site moved to https
723 + // without rewriting every row (or one behind a TLS-terminating proxy
724 + // where `is_ssl()` reads false) serves https pages off http-rooted
725 + // bases all day. Comparing scheme-less is the whole fix; the host
726 + // equality test already did the security work of refusing anything
727 + // off-site, and this runs after it.
728 + $strip_scheme = static function ( string $value ): string {
729 + return (string) preg_replace( '#^https?://#i', '//', $value );
730 + };
731 + $clean_match = $strip_scheme( $clean );
732 +
284 733 foreach ( $candidates as $pair ) {
285 734 list( $url_base, $path_base ) = $pair;
286 735 if ( ! $url_base || ! $path_base ) {
287 736 continue;
288 737 }
289 - $url_base = rtrim( $url_base, '/' );
290 - if ( 0 !== strpos( $clean, $url_base . '/' ) && $clean !== $url_base ) {
738 + $url_base = rtrim( $url_base, '/' );
739 + $base_match = $strip_scheme( $url_base );
740 + if ( 0 !== strpos( $clean_match, $base_match . '/' ) && $clean_match !== $base_match ) {
291 741 continue;
292 742 }
293 743
294 - $relative = ltrim( substr( $clean, strlen( $url_base ) ), '/' );
744 + // Slice the scheme-less pair, not the original. `https://…` and
745 + // `http://…` differ by one byte, so an offset taken from the base
746 + // as written would cut one character short of (or past) the path
747 + // when the two schemes disagree — which is the case this fix
748 + // exists for.
749 + $relative = ltrim( substr( $clean_match, strlen( $base_match ) ), '/' );
295 750 $candidate = trailingslashit( $path_base ) . $relative;
296 751
297 752 $real_base = realpath( $path_base );
298 753 $real = realpath( $candidate );
@@ -320,14 +775,96 @@
320 775 Cache::write_silence( $dir );
321 776 }
322 777 }
323 778
779 + /**
780 + * Delete every minified and combined asset, network-wide.
781 + *
782 + * Output files are named by content, so an ordinary purge has no reason
783 + * to delete them: a page rendered after it links the same names. Only a
784 + * network purge, an update, an explicit assets purge and deactivation
785 + * come here. Deleting is still a race against renders in flight, which
786 + * may already hold the names of files about to vanish; the purge stamp
787 + * bumped here lets the page cache refuse to store those renders.
788 + *
789 + * @return int Files removed. Most callers are `add_action` callbacks and
790 + * ignore it; `wp xspeed purge` reports it as a line item.
791 + */
324 792 public static function purge_minified() {
325 - $dir = self::min_dir();
793 + $removed = self::rmtree_files( self::min_dir() );
794 + if ( $removed > 0 ) {
795 + self::bump_purge_stamp();
796 + }
797 + return $removed;
798 + }
799 +
800 + /**
801 + * Delete one blog's manifests, leaving every output file in place.
802 + *
803 + * What a subsite's assets purge can safely do on a network whose blogs
804 + * share min/: the next render of each source re-reads its bytes and
805 + * rebuilds only if they changed, and no other blog's cached page loses a
806 + * file it links. Outputs nothing links any more are left to Cache_GC.
807 + *
808 + * @param int $blog_id Blog whose manifests to drop.
809 + * @return int Manifests removed.
810 + */
811 + public static function purge_manifests( int $blog_id ): int {
812 + $dir = Asset_Manifest::dir( $blog_id );
813 + $removed = self::rmtree_files( $dir );
814 + @rmdir( $dir ); // 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.
815 + return $removed;
816 + }
817 +
818 + /** File holding the purge stamp. Network-wide, like min/ itself. */
819 + public static function purge_stamp_path(): string {
820 + return rtrim( (string) XSPEED_CACHE_DIR, '/' ) . '/min-purge.stamp';
821 + }
822 +
823 + /**
824 + * Token that changes every time purge_minified() deletes something.
825 + *
826 + * The page cache reads it when a render starts and again before storing
827 + * the page. A different value means files the page may link were deleted
828 + * in between, so the page is served but not cached.
829 + *
830 + * @return string '' when no purge has ever deleted anything.
831 + */
832 + public static function purge_stamp(): string {
833 + $stamp = @file_get_contents( self::purge_stamp_path() ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- absent until the first purge; tiny cache sidecar read on the front end, where WP_Filesystem is unavailable.
834 + return is_string( $stamp ) ? trim( $stamp ) : '';
835 + }
836 +
837 + /** Replace the purge stamp with a new random token. */
838 + private static function bump_purge_stamp(): void {
839 + $path = self::purge_stamp_path();
840 + if ( ! is_dir( dirname( $path ) ) ) {
841 + return;
842 + }
843 + Asset_Manifest::write_atomic( $path, bin2hex( random_bytes( 8 ) ) );
844 + }
845 +
846 + /**
847 + * Recursively delete every file under $dir (and the emptied
848 + * subdirectories), keeping $dir itself. The previous glob('$dir/*')
849 + * was non-recursive and no-ops on directories, so combined assets in
850 + * min/combined/ were never cleared — a purge left a stale
851 + * combined-<hash>.css the regenerated page no longer referenced.
852 + * (FBS-83114 / FBS-83116)
853 + */
854 + private static function rmtree_files( string $dir ): int {
326 855 if ( ! is_dir( $dir ) ) {
327 - return;
856 + return 0;
328 857 }
329 - foreach ( glob( $dir . '/*' ) as $file ) {
330 - wp_delete_file( $file );
858 + $removed = 0;
859 + foreach ( (array) glob( $dir . '/*' ) as $path ) {
860 + if ( is_dir( $path ) ) {
861 + $removed += self::rmtree_files( $path );
862 + @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.
863 + continue;
864 + }
865 + wp_delete_file( $path );
866 + ++$removed;
331 867 }
868 + return $removed;
332 869 }
333 870 }