Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
59.46% covered (warning)
59.46%
110 / 185
33.33% covered (danger)
33.33%
7 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
Render_Blocking_JS
59.46% covered (warning)
59.46%
110 / 185
33.33% covered (danger)
33.33%
7 / 21
438.86
0.00% covered (danger)
0.00%
0 / 1
 setup
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 is_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_data_sync
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_change_output_action_names
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 start_output_filtering
65.52% covered (warning)
65.52%
19 / 29
0.00% covered (danger)
0.00%
0 / 1
41.85
 handle_output_stream
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
4.01
 get_script_tags
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 ignore_exclusion_scripts
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
2.04
 pin_position_dependent_scripts
53.33% covered (warning)
53.33%
8 / 15
0.00% covered (danger)
0.00%
0 / 1
7.54
 ignore_attribute_lookahead
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 recalculate_buffer_split
20.00% covered (danger)
20.00%
1 / 5
0.00% covered (danger)
0.00%
0 / 1
1.51
 append_script_tags
50.00% covered (danger)
50.00%
3 / 6
0.00% covered (danger)
0.00%
0 / 1
2.50
 handle_exclusions
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 add_ignore_attribute
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_opened_script
58.33% covered (warning)
58.33%
7 / 12
0.00% covered (danger)
0.00%
0 / 1
2.29
 is_current_request_excluded
16.67% covered (danger)
16.67%
1 / 6
0.00% covered (danger)
0.00%
0 / 1
19.47
 is_url_excluded
33.33% covered (danger)
33.33%
3 / 9
0.00% covered (danger)
0.00%
0 / 1
12.41
 normalize_url_path
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
3.19
 strip_home_path
12.50% covered (danger)
12.50%
1 / 8
0.00% covered (danger)
0.00%
0 / 1
14.72
 get_exclusion_regex
53.12% covered (warning)
53.12%
17 / 32
0.00% covered (danger)
0.00%
0 / 1
17.34
 get_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Implements the system to avoid render blocking JS execution.
4 *
5 * @link       https://automattic.com
6 * @since      0.2
7 * @package    automattic/jetpack-boost
8 */
9
10namespace Automattic\Jetpack_Boost\Modules\Optimizations\Render_Blocking_JS;
11
12use Automattic\Jetpack\Schema\Schema;
13use Automattic\Jetpack\WP_JS_Data_Sync\Data_Sync;
14use Automattic\Jetpack_Boost\Contracts\Changes_Output_After_Activation;
15use Automattic\Jetpack_Boost\Contracts\Changes_Output_On_Activation;
16use Automattic\Jetpack_Boost\Contracts\Feature;
17use Automattic\Jetpack_Boost\Contracts\Has_Data_Sync;
18use Automattic\Jetpack_Boost\Contracts\Optimization;
19use Automattic\Jetpack_Boost\Data_Sync\Minify_Excludes_State_Entry;
20use Automattic\Jetpack_Boost\Lib\Output_Filter;
21
22/**
23 * Class Render_Blocking_JS
24 */
25class Render_Blocking_JS implements Feature, Changes_Output_On_Activation, Changes_Output_After_Activation, Optimization, Has_Data_Sync {
26    /**
27     * Substring that marks an inline script as producing position-dependent
28     * output (document.write()/document.writeln()). Such scripts must stay where
29     * they are rather than being moved to the end of the document. The fast-path
30     * guard and the per-script check must use the same needle to stay in lockstep.
31     *
32     * @var string
33     */
34    private const POSITION_DEPENDENT_OUTPUT_NEEDLE = 'document.write';
35
36    /**
37     * Holds the script tags removed from the output buffer.
38     *
39     * @var array
40     */
41    protected $buffered_script_tags = array();
42
43    /**
44     * HTML attribute name to be added to <script> tag to make it
45     * ignored by this class.
46     *
47     * @var string|null
48     */
49    private $ignore_attribute;
50
51    /**
52     * HTML attribute value to be added to <script> tag to make it
53     * ignored by this class.
54     *
55     * @var string
56     */
57    private $ignore_value = 'ignore';
58
59    /**
60     * Utility class that supports output filtering.
61     *
62     * @var Output_Filter
63     */
64    private $output_filter = null;
65
66    /**
67     * Flag indicating an opened <script> tag in output.
68     *
69     * @var string
70     */
71    private $is_opened_script = false;
72
73    public function setup() {
74        $this->output_filter = new Output_Filter();
75
76        /**
77         * Filters the ignore attribute
78         *
79         * @param $string $ignore_attribute The string used to ignore elements of the page.
80         *
81         * @since   1.0.0
82         */
83        $this->ignore_attribute = apply_filters( 'jetpack_boost_render_blocking_js_ignore_attribute', 'data-jetpack-boost' );
84
85        add_action( 'template_redirect', array( $this, 'start_output_filtering' ), -999999 );
86
87        /**
88         * Shortcodes can sometimes output script to embed widget. It's safer to ignore them.
89         */
90        add_filter( 'do_shortcode_tag', array( $this, 'add_ignore_attribute' ) );
91    }
92
93    public static function is_available() {
94        return true;
95    }
96
97    /**
98     * Register the data sync entry holding the list of URL patterns
99     * excluded from JS deferring.
100     *
101     * @param Data_Sync $instance The data sync instance.
102     */
103    public function register_data_sync( Data_Sync $instance ) {
104        $instance->register(
105            'render_blocking_js_excludes',
106            Schema::as_array( Schema::as_string() )->fallback( array() ),
107            new Minify_Excludes_State_Entry( 'render_blocking_js_excludes' )
108        );
109    }
110
111    /**
112     * Cached pages need to be invalidated when the exclusion list changes.
113     *
114     * @return string[] Action names fired when the exclusion list is updated.
115     */
116    public static function get_change_output_action_names() {
117        $option = JETPACK_BOOST_DATASYNC_NAMESPACE . '_render_blocking_js_excludes';
118
119        // `add_option_*` covers the very first save, when the option is created
120        // rather than updated, so the cache is invalidated on that write too.
121        return array(
122            'add_option_' . $option,
123            'update_option_' . $option,
124        );
125    }
126
127    /**
128     * Set up an output filtering callback.
129     *
130     * @return void
131     */
132    public function start_output_filtering() {
133        /**
134         * We're doing heavy output filtering in this module
135         * by using output buffering.
136         *
137         * Here are a few scenarios when we shouldn't do it:
138         */
139
140        /**
141         * Filter to disable defer blocking JS
142         *
143         * @param bool $defer return false to disable defer blocking
144         *
145         * @since   1.0.0
146         */
147        if ( false === apply_filters( 'jetpack_boost_should_defer_js', '__return_true' ) ) {
148            return;
149        }
150
151        // Disable in robots.txt.
152        if ( isset( $_SERVER['REQUEST_URI'] ) && strpos( home_url( wp_unslash( $_SERVER['REQUEST_URI'] ) ), 'robots.txt' ) !== false ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- This is validating.
153            return;
154        }
155
156        // Disable in other possible AJAX requests setting cors related header.
157        if ( isset( $_SERVER['HTTP_SEC_FETCH_MODE'] ) && 'cors' === strtolower( $_SERVER['HTTP_SEC_FETCH_MODE'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating.
158            return;
159        }
160
161        // Disable in other possible AJAX requests setting XHR related header.
162        if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && 'xmlhttprequest' === strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating.
163            return;
164        }
165
166        // Disable in all XLS (see the WP_Sitemaps_Renderer class which is responsible for rendering Sitemaps data to XML
167        // in accordance with sitemap protocol).
168        if ( isset( $_SERVER['REQUEST_URI'] ) &&
169            (
170                // phpcs:disable WordPress.Security.ValidatedSanitizedInput -- This is validating.
171                str_contains( $_SERVER['REQUEST_URI'], '.xsl' ) ||
172                str_contains( $_SERVER['REQUEST_URI'], 'sitemap-stylesheet=index' ) ||
173                str_contains( $_SERVER['REQUEST_URI'], 'sitemap-stylesheet=sitemap' )
174                // phpcs:enable WordPress.Security.ValidatedSanitizedInput
175            ) ) {
176            return;
177        }
178
179        // Disable in all POST Requests.
180        // phpcs:disable WordPress.Security.NonceVerification.Missing
181        if ( ! empty( $_POST ) ) {
182            return;
183        }
184
185        // Disable in customizer previews
186        if ( is_customize_preview() ) {
187            return;
188        }
189
190        // Disable in feeds, AJAX, Cron, XML.
191        if ( is_feed() || wp_doing_ajax() || wp_doing_cron() || wp_is_xml_request() ) {
192            return;
193        }
194
195        // Disable in sitemaps.
196        if ( ! empty( get_query_var( 'sitemap' ) ) ) {
197            return;
198        }
199
200        // Disable in AMP pages.
201        if ( function_exists( 'amp_is_request' ) && amp_is_request() ) {
202            return;
203        }
204
205        // Disable on URLs excluded by the user.
206        if ( $this->is_current_request_excluded() ) {
207            // Leave the page output completely untouched, as if the module was off.
208            remove_filter( 'do_shortcode_tag', array( $this, 'add_ignore_attribute' ) );
209            return;
210        }
211
212        // Print the filtered script tags to the very end of the page.
213        add_filter( 'jetpack_boost_output_filtering_last_buffer', array( $this, 'append_script_tags' ), 10, 1 );
214
215        // Handle exclusions.
216        add_filter( 'script_loader_tag', array( $this, 'handle_exclusions' ), 10, 2 );
217
218        $this->output_filter->add_callback( array( $this, 'handle_output_stream' ) );
219    }
220
221    /**
222     * Remove all inline and external <script> tags from the default output.
223     *
224     * @param string $buffer_start First part of the buffer.
225     * @param string $buffer_end   Second part of the buffer.
226     *
227     * For explanation on why there are two parts of a buffer here, see
228     * the comments and examples in the Output_Filter class.
229     *
230     * @return array Parts of the buffer.
231     */
232    public function handle_output_stream( $buffer_start, $buffer_end ) {
233        $joint_buffer = $this->ignore_exclusion_scripts( $buffer_start . $buffer_end );
234        $script_tags  = $this->get_script_tags( $joint_buffer );
235
236        if ( ! $script_tags ) {
237            if ( $this->is_opened_script ) {
238                // We have an opened script tag, move everything to the second buffer to avoid printing it to the page.
239                // We will do this until the </script> closing tag is encountered.
240                return array( '', $joint_buffer );
241            }
242
243            // No script tags detected, return both chunks unaltered.
244            return array( $buffer_start, $buffer_end );
245        }
246
247        // Makes sure all whole <script>...</script> tags are in $buffer_start.
248        list( $buffer_start, $buffer_end ) = $this->recalculate_buffer_split( $joint_buffer, $script_tags );
249
250        foreach ( $script_tags as $script_tag ) {
251            $this->buffered_script_tags[] = $script_tag[0];
252            $buffer_start                 = str_replace( $script_tag[0], '', $buffer_start );
253        }
254
255        // Detect a lingering opened script.
256        $this->is_opened_script = $this->is_opened_script( $buffer_start . $buffer_end );
257
258        return array( $buffer_start, $buffer_end );
259    }
260
261    /**
262     * Matches <script> tags with their content in a string buffer.
263     *
264     * @param string $buffer Captured piece of output buffer.
265     *
266     * @return array
267     */
268    protected function get_script_tags( $buffer ) {
269        $regex = '~<script' . $this->ignore_attribute_lookahead() . '([^>]*)>[\s\S]*?<\/script>~si';
270        preg_match_all( $regex, $buffer, $script_tags, PREG_OFFSET_CAPTURE );
271
272        // No script_tags in the joint buffer.
273        if ( empty( $script_tags[0] ) ) {
274            return array();
275        }
276
277        /**
278         * Filter to remove any scripts that should not be moved to the end of the document.
279         *
280         * @param array $script_tags array of script tags. Remove any scripts that should not be moved to the end of the documents.
281         *
282         * @since   1.0.0
283         */
284        return apply_filters( 'jetpack_boost_render_blocking_js_exclude_scripts', $script_tags[0] );
285    }
286
287    /**
288     * Adds the ignore attribute to scripts in the exclusion list.
289     *
290     * @param string $buffer Captured piece of output buffer.
291     *
292     * @return string
293     */
294    protected function ignore_exclusion_scripts( $buffer ) {
295        $exclusions = array(
296            // Scripts inside HTML comments.
297            '~<!--.*?-->~si',
298
299            // Scripts with types that do not execute complex code. Moving them down can be dangerous
300            // and does not benefit performance. Includes types: application/json, application/ld+json and importmap.
301            '~<script\s+[^\>]*type=(?<q>["\']*)(application\/(ld\+)?json|importmap)\k<q>.*?>.*?<\/script>~si',
302        );
303
304        $excluded = preg_replace_callback(
305            $exclusions,
306            function ( $script_match ) {
307                return $this->add_ignore_attribute( $script_match[0] );
308            },
309            $buffer
310        );
311        // preg_replace_callback() returns null on PCRE failure; keep the original
312        // buffer in that case rather than propagating null downstream.
313        if ( null !== $excluded ) {
314            $buffer = $excluded;
315        }
316
317        return $this->pin_position_dependent_scripts( $buffer );
318    }
319
320    /**
321     * Keep inline scripts whose output is position-dependent in their original place.
322     *
323     * Scripts using document.write()/document.writeln() insert markup at the script's
324     * location, so moving such a script to the end of the document renders its output
325     * after the footer instead of inside the content (e.g. a Custom HTML block).
326     * Marking the script with the ignore attribute keeps the rest of the pipeline
327     * from moving it. Scripts that already carry the ignore attribute are skipped so
328     * their behavior and markup are unchanged.
329     *
330     * Best-effort and deliberately conservative: it pins the common case (an inline
331     * script that calls document.write) and otherwise leaves the script to the
332     * default move behavior. It does not pin scripts that write their own
333     * '<script ...>' markup (no safe in-place edit exists), nor exotic call forms a
334     * substring check cannot see. A miss never corrupts the page â€” worst case is a
335     * script that still moves, exactly as it does without this method.
336     *
337     * @param string $buffer Captured piece of output buffer.
338     *
339     * @return string
340     */
341    private function pin_position_dependent_scripts( $buffer ) {
342        // Fast path: skip the inline-script scan entirely when the buffer cannot
343        // contain a position-dependent script.
344        if ( false === stripos( $buffer, self::POSITION_DEPENDENT_OUTPUT_NEEDLE ) ) {
345            return $buffer;
346        }
347
348        // Match inline scripts only (no src attribute) that do not already carry
349        // the ignore attribute. This runs on the buffer Output_Filter hands us
350        // (a bounded window), not a whole page; the lazy [\s\S]*? would be
351        // superlinear on a multi-megabyte single buffer, so keep it window-scoped.
352        $inline_script_regex = '~<script\b(?![^>]*\ssrc\s*=)' . $this->ignore_attribute_lookahead() . '[^>]*>[\s\S]*?</script>~i';
353
354        $result = preg_replace_callback(
355            $inline_script_regex,
356            function ( $script_match ) {
357                // Intentionally conservative: a simple case-insensitive substring check
358                // for "document.write" (which also covers "document.writeln"). It does
359                // not parse JS, so exotic call forms it cannot see â€” document['write'](),
360                // "document . write()", or an uppercase <SCRIPT> tag that
361                // add_ignore_attribute()'s lowercase replace won't touch â€” simply fall
362                // back to the default behavior (the script is moved, as it is today).
363                // That is the safe direction: a miss never corrupts the page.
364                if ( false === stripos( $script_match[0], self::POSITION_DEPENDENT_OUTPUT_NEEDLE ) ) {
365                    return $script_match[0];
366                }
367
368                // Do not touch a script that writes its own '<script ...>' markup. There
369                // is no safe in-place edit for it: add_ignore_attribute() does a global
370                // str_replace() on '<script', which rewrites the inner literal and can
371                // break the quoting of the string the script writes; tagging only the
372                // outer tag would instead let get_script_tags() match and move that inner
373                // literal. Such scripts keep the default behavior rather than risk
374                // corrupting the page.
375                if ( substr_count( strtolower( $script_match[0] ), '<script' ) > 1 ) {
376                    return $script_match[0];
377                }
378
379                return $this->add_ignore_attribute( $script_match[0] );
380            },
381            $buffer
382        );
383
384        // preg_replace_callback() returns null on PCRE failure (e.g. backtrack limit
385        // on a pathological buffer); fall back to the unmodified buffer so the page is
386        // never blanked. Mirrors the guard in is_opened_script().
387        return null === $result ? $buffer : $result;
388    }
389
390    /**
391     * Negative lookahead asserting a <script> tag does not already carry the
392     * ignore attribute. Shared by the regexes that select movable scripts so the
393     * attribute-matching rule lives in one place.
394     *
395     * @return string Regex fragment (uses named group "q"; safe to use once per pattern).
396     */
397    private function ignore_attribute_lookahead() {
398        return sprintf(
399            '(?![^>]*%s=(?<q>["\']*)%s\k<q>)',
400            preg_quote( $this->ignore_attribute, '~' ),
401            preg_quote( $this->ignore_value, '~' )
402        );
403    }
404
405    /**
406     * Splits the buffer into two parts.
407     *
408     * First part contains all whole <script> tags, the second part
409     * contains the rest of the buffer.
410     *
411     * @param string $buffer      Captured piece of output buffer.
412     * @param array  $script_tags Matched <script> tags.
413     *
414     * @return array
415     */
416    protected function recalculate_buffer_split( $buffer, $script_tags ) {
417        $last_script_tag_index        = count( $script_tags ) - 1;
418        $last_script_tag_end_position = strrpos( $buffer, $script_tags[ $last_script_tag_index ][0] ) + strlen( $script_tags[ $last_script_tag_index ][0] );
419
420        // Bundle all script tags into the first buffer.
421        $buffer_start = substr( $buffer, 0, $last_script_tag_end_position );
422
423        // Leave the rest of the data in the second buffer.
424        $buffer_end = substr( $buffer, $last_script_tag_end_position );
425
426        return array( $buffer_start, $buffer_end );
427    }
428
429    /**
430     * Insert the buffered script tags just before the body tag if possible in the last buffer
431     * otherwise at append it at the end.
432     *
433     * @param string $buffer String buffer.
434     *
435     * @return string
436     */
437    public function append_script_tags( $buffer ) {
438        $script_tags = implode( '', $this->buffered_script_tags );
439        // Reset tags in case there's another buffer after this one.
440        $this->buffered_script_tags = array();
441
442        if ( str_contains( $buffer, '</body>' ) ) {
443            $buffer = str_replace( '</body>', $script_tags . '</body>', $buffer );
444        } else {
445            $buffer .= $script_tags;
446        }
447
448        return $buffer;
449    }
450
451    /**
452     * Exclude certain scripts from being processed by this class.
453     *
454     * @param string $tag    <script> opening tag.
455     * @param string $handle Script handle from register_ or enqueue_ methods.
456     *
457     * @return string
458     */
459    public function handle_exclusions( $tag, $handle ) {
460        /**
461         * Filter to provide an array of registered script handles that should not be moved to the end of the document.
462         *
463         * @param array $script_handles array of script handles. Remove any scripts that should not be moved to the end of the documents.
464         *
465         * @since   1.0.0
466         */
467        $exclude_handles = apply_filters( 'jetpack_boost_render_blocking_js_exclude_handles', array() );
468
469        if ( ! in_array( $handle, $exclude_handles, true ) ) {
470            return $tag;
471        }
472
473        return $this->add_ignore_attribute( $tag );
474    }
475
476    /**
477     * Add the ignore attribute to the script tags.
478     *
479     * Case-insensitive so uppercase/mixed-case tags (`<SCRIPT>`, valid HTML and
480     * common in hand-written Custom HTML / legacy embeds) are handled too; a
481     * case-sensitive match would silently no-op on them and leave them movable.
482     *
483     * @param string $html HTML code possibly containing a <script> opening tag.
484     *
485     * @return string
486     */
487    public function add_ignore_attribute( $html ) {
488        return str_ireplace( '<script', sprintf( '<script %s="%s"', esc_html( $this->ignore_attribute ), esc_attr( $this->ignore_value ) ), $html );
489    }
490
491    /**
492     * Detects an unclosed script tag in a buffer.
493     *
494     * @param string $buffer Joint buffer.
495     *
496     * @return bool
497     */
498    public function is_opened_script( $buffer ) {
499        // Strip fully-paired ignored <script>...</script> blocks so the counts below are symmetric.
500        $ignored_pair_regex = sprintf(
501            '~<script[^>]*%s=(?<q>["\']*)%s\k<q>[^>]*>[\s\S]*?</script>~si',
502            preg_quote( $this->ignore_attribute, '~' ),
503            preg_quote( $this->ignore_value, '~' )
504        );
505        $stripped           = preg_replace( $ignored_pair_regex, '', $buffer );
506        if ( null === $stripped ) {
507            $stripped = $buffer;
508        }
509
510        // Strip HTML comments so a commented-out </script> doesn't skew the count.
511        $stripped = preg_replace( '~<!--[\s\S]*?-->~', '', $stripped ) ?? $stripped;
512
513        $opening_tags_count = preg_match_all( '~<\s*script(\s[^>]*)?>~i', $stripped );
514        $closing_tags_count = preg_match_all( '~<\s*/\s*script\s*>~i', $stripped );
515
516        return $opening_tags_count > $closing_tags_count;
517    }
518
519    /**
520     * Checks if the current request URL matches one of the exclusion patterns
521     * configured by the user.
522     *
523     * Runs at template_redirect time, when REQUEST_URI is available.
524     *
525     * @return bool
526     */
527    private function is_current_request_excluded() {
528        if ( ! isset( $_SERVER['REQUEST_URI'] ) ) {
529            return false;
530        }
531
532        $patterns = function_exists( 'jetpack_boost_ds_get' ) ? jetpack_boost_ds_get( 'render_blocking_js_excludes' ) : array();
533        if ( empty( $patterns ) || ! is_array( $patterns ) ) {
534            return false;
535        }
536
537        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Only used for comparison.
538        return self::is_url_excluded( wp_unslash( $_SERVER['REQUEST_URI'] ), $patterns );
539    }
540
541    /**
542     * Checks whether a request URI matches any of the given exclusion patterns.
543     *
544     * Patterns follow the semantics documented for Page Cache bypass patterns:
545     * they are compared against the URL path (query strings are ignored),
546     * a `(.*)` or `*` wildcard matches any part of the path, trailing slashes
547     * are optional and the comparison is case-insensitive.
548     *
549     * Two things differ from Page Cache, so keep them in mind before unifying the
550     * two implementations: every character outside the wildcard tokens is escaped
551     * via preg_quote() and matched literally (a pattern like `page.html` never
552     * acts as a regular expression), and the path is percent-decoded so a pattern
553     * typed as it appears in the address bar matches an encoded request path.
554     *
555     * @param string $request_uri The request URI to check.
556     * @param array  $patterns    List of URL patterns.
557     *
558     * @return bool
559     */
560    public static function is_url_excluded( $request_uri, $patterns ) {
561        $path = self::normalize_url_path( $request_uri );
562
563        foreach ( $patterns as $pattern ) {
564            $regex = self::get_exclusion_regex( $pattern );
565            if ( null === $regex ) {
566                continue;
567            }
568
569            $matched = preg_match( $regex, $path );
570
571            /*
572             * preg_match() returns false when PCRE cannot evaluate the pattern â€”
573             * e.g. a pathological pattern with several literal-separated wildcards
574             * hits the backtrack limit on a long URL. Treat that as a match so a
575             * deliberate exclusion is honoured (defer stays off on the page)
576             * rather than silently ignored.
577             */
578            if ( 1 === $matched || false === $matched ) {
579                return true;
580            }
581        }
582
583        return false;
584    }
585
586    /**
587     * Extracts a normalized path from a URL or request URI.
588     *
589     * Drops the query string, ensures a leading slash and removes trailing
590     * slashes (except for the root path).
591     *
592     * @param string $url URL or request URI.
593     *
594     * @return string
595     */
596    private static function normalize_url_path( $url ) {
597        $path = (string) wp_parse_url( $url, PHP_URL_PATH );
598
599        // Decode percent-encoding so a pattern typed as it appears in the address
600        // bar (e.g. `foo bar`, or a non-ASCII slug) matches the encoded request
601        // path (`/foo%20bar`). Both the pattern and the request pass through here,
602        // so the two sides stay symmetric.
603        $path = rawurldecode( $path );
604
605        $path = '/' . ltrim( $path, '/' );
606
607        if ( '/' !== $path ) {
608            $path = rtrim( $path, '/' );
609        }
610
611        return self::strip_home_path( $path );
612    }
613
614    /**
615     * Removes the site's home directory prefix from a path.
616     *
617     * On a subdirectory install (e.g. a site at `/blog/`) the request URI
618     * includes the subdirectory but user-entered patterns generally do not.
619     * Stripping the home directory from both sides makes the comparison relative
620     * to the home root, so a `checkout` pattern matches `/blog/checkout`.
621     *
622     * @param string $path A normalized URL path (leading slash, no query/trailing slash).
623     *
624     * @return string
625     */
626    private static function strip_home_path( $path ) {
627        $home_path = rtrim( (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH ), '/' );
628
629        if ( '' === $home_path ) {
630            return $path;
631        }
632
633        if ( 0 === strcasecmp( $path, $home_path ) ) {
634            return '/';
635        }
636
637        if ( 0 === strncasecmp( $path, $home_path . '/', strlen( $home_path ) + 1 ) ) {
638            return substr( $path, strlen( $home_path ) );
639        }
640
641        return $path;
642    }
643
644    /**
645     * Turns a single exclusion pattern into an anchored regular expression.
646     *
647     * @param mixed $pattern A user-provided URL pattern.
648     *
649     * @return string|null The regular expression, or null if the pattern is empty.
650     */
651    private static function get_exclusion_regex( $pattern ) {
652        if ( ! is_string( $pattern ) ) {
653            return null;
654        }
655
656        $pattern = trim( $pattern );
657        if ( '' === $pattern ) {
658            return null;
659        }
660
661        /*
662         * Reject malformed URL patterns. A full URL with a scheme but no path
663         * (e.g. a typo'd `http://[::1`) would otherwise collapse to `/` and
664         * silently exclude only the homepage. A pathless URL that points at this
665         * site (e.g. the home URL pasted as `https://example.com`) is allowed
666         * through, since it legitimately means the homepage.
667         */
668        $parsed = wp_parse_url( $pattern );
669        if ( false === $parsed ) {
670            return null;
671        }
672        if ( isset( $parsed['scheme'] ) && empty( $parsed['path'] ) ) {
673            $home_host = wp_parse_url( home_url( '/' ), PHP_URL_HOST );
674            if ( empty( $parsed['host'] ) || 0 !== strcasecmp( $parsed['host'], (string) $home_host ) ) {
675                return null;
676            }
677        }
678
679        // Allow full URLs by stripping the home URL prefix (both secure and non-secure).
680        $home_url = home_url( '/' );
681        $pattern  = str_ireplace(
682            array(
683                $home_url,
684                str_replace( 'http:', 'https:', $home_url ),
685            ),
686            '/',
687            $pattern
688        );
689
690        $pattern = self::normalize_url_path( $pattern );
691
692        /*
693         * Split on wildcard tokens, treating any run of adjacent wildcards as a
694         * single split point. The possessive `++` is important: without coalescing,
695         * a pattern such as `****` would expand to one `.*` group per character, and
696         * thousands of wildcards would compile to thousands of groups and exhaust
697         * memory when matched against every front-end request. Possessive (rather
698         * than greedy `+`) keeps the split itself linear, so a pathological run of
699         * thousands of adjacent wildcards cannot exhaust the PCRE backtrack/JIT
700         * stack and make preg_split() return false.
701         */
702        $tokens = preg_split( '/(?:\(\.\*\)|\(\*\)|\.\*|\*)++/', $pattern );
703        if ( false === $tokens ) {
704            return null;
705        }
706
707        // Everything between wildcards is matched literally; only the wildcards
708        // become a (non-capturing) `.*` group.
709        $quoted = array_map(
710            function ( $token ) {
711                return preg_quote( $token, '~' );
712            },
713            $tokens
714        );
715
716        return '~^' . implode( '(?:.*)', $quoted ) . '/?$~i';
717    }
718
719    public static function get_slug() {
720        return 'render_blocking_js';
721    }
722}