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