Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.89% covered (warning)
88.89%
88 / 99
64.29% covered (warning)
64.29%
9 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
Defer_Fonts
88.89% covered (warning)
88.89%
88 / 99
64.29% covered (warning)
64.29%
9 / 14
45.54
0.00% covered (danger)
0.00%
0 / 1
 get_slug
100.00% covered (success)
100.00%
1 / 1
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
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 setup
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 replace_core_font_faces
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 print_deferred_font_faces
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
7
 get_response_headers
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 csp_blocks_inline_script
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
13
 get_excluded_families
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 split_excluded
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 with_swap
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 extract_css
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 get_loader_script
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Defers the web fonts WordPress prints from theme.json and the Font Library until the page has loaded.
4 *
5 * @package automattic/jetpack-boost
6 */
7
8namespace Automattic\Jetpack_Boost\Modules\Optimizations\Defer_Fonts;
9
10use Automattic\Jetpack\Schema\Schema;
11use Automattic\Jetpack\WP_JS_Data_Sync\Data_Sync;
12use Automattic\Jetpack_Boost\Contracts\Changes_Output_After_Activation;
13use Automattic\Jetpack_Boost\Contracts\Changes_Output_On_Activation;
14use Automattic\Jetpack_Boost\Contracts\Feature;
15use Automattic\Jetpack_Boost\Contracts\Has_Data_Sync;
16use Automattic\Jetpack_Boost\Contracts\Optimization;
17use Automattic\Jetpack_Boost\Data_Sync\Minify_Excludes_State_Entry;
18
19/**
20 * Prints core's @font-face rules with `font-display: swap` and injects them after the `load` event.
21 */
22class Defer_Fonts implements Feature, Changes_Output_On_Activation, Changes_Output_After_Activation, Optimization, Has_Data_Sync {
23
24    /**
25     * Key in sessionStorage remembering which font set this visit has already downloaded.
26     *
27     * Not localStorage: it outlives the HTTP cache, and a stale hash would load uncached fonts alongside the LCP image.
28     */
29    const STORAGE_KEY = 'jetpack-boost-defer-fonts';
30
31    /**
32     * Font-family name prefixes left to load normally until the site owner edits the list.
33     */
34    const DEFAULT_EXCLUDES = array( 'Font Awesome', 'FontAwesome' );
35
36    /**
37     * Milliseconds to wait for `load` before adding the fonts anyway, for pages a slow embed holds back.
38     */
39    const LOAD_WAIT_MS = 3000;
40
41    /**
42     * Get the slug for this module.
43     *
44     * @return string
45     */
46    public static function get_slug() {
47        return 'defer_fonts';
48    }
49
50    /**
51     * Check if the feature is available.
52     *
53     * @return bool
54     */
55    public static function is_available() {
56        return true;
57    }
58
59    /**
60     * Register the data sync entry holding the font families left to load normally.
61     *
62     * @param Data_Sync $instance The data sync instance.
63     */
64    public function register_data_sync( Data_Sync $instance ) {
65        $instance->register(
66            'defer_fonts_excludes',
67            Schema::as_array( Schema::as_string() )->fallback( self::DEFAULT_EXCLUDES ),
68            new Minify_Excludes_State_Entry( 'defer_fonts_excludes' )
69        );
70    }
71
72    /**
73     * Cached pages need to be invalidated when the exclusion list changes.
74     *
75     * @return string[] Action names fired when the exclusion list is saved.
76     */
77    public static function get_change_output_action_names() {
78        $option = JETPACK_BOOST_DATASYNC_NAMESPACE . '_defer_fonts_excludes';
79
80        return array(
81            'add_option_' . $option,
82            'update_option_' . $option,
83        );
84    }
85
86    /**
87     * Setup the module. This runs on every page load.
88     */
89    public function setup() {
90        if ( jetpack_boost_page_optimize_bail() ) {
91            return;
92        }
93
94        add_action( 'wp_head', array( $this, 'replace_core_font_faces' ), 0 );
95    }
96
97    /**
98     * Swap core's font-face printer for the deferred one, keeping its position in the head.
99     */
100    public function replace_core_font_faces() {
101        $priority = has_action( 'wp_head', 'wp_print_font_faces' );
102        if ( false === $priority ) {
103            return;
104        }
105
106        remove_action( 'wp_head', 'wp_print_font_faces', $priority );
107        add_action( 'wp_head', array( $this, 'print_deferred_font_faces' ), $priority );
108    }
109
110    /**
111     * Print the theme's font faces as a deferred loader, with a <noscript> fallback.
112     *
113     * Falls back to core's output when a Content-Security-Policy header set from PHP would block the loader.
114     * A policy sent by the web server or a <meta> tag can't be seen here, so such sites should leave the module off.
115     */
116    public function print_deferred_font_faces() {
117        list( $fonts, $excluded ) = self::split_excluded( \WP_Font_Face_Resolver::get_fonts_from_theme_json(), self::get_excluded_families() );
118
119        $css = '';
120        if ( ! empty( $fonts ) ) {
121            ob_start();
122            ( new \WP_Font_Face() )->generate_and_print( self::with_swap( $fonts ) );
123            $css = self::extract_css( (string) ob_get_clean() );
124        }
125
126        /** This filter is documented in app/modules/optimizations/render-blocking-js/class-render-blocking-js.php */
127        $ignore_attribute = apply_filters( 'jetpack_boost_render_blocking_js_ignore_attribute', 'data-jetpack-boost' );
128
129        $loader = '' === $css ? '' : wp_get_inline_script_tag(
130            self::get_loader_script( $css ),
131            array(
132                'id'              => 'jetpack-boost-defer-fonts',
133                $ignore_attribute => 'ignore',
134            )
135        );
136
137        if ( '' !== $loader && self::csp_blocks_inline_script( $this->get_response_headers(), $loader ) ) {
138            wp_print_font_faces();
139            return;
140        }
141
142        if ( ! empty( $excluded ) ) {
143            wp_print_font_faces( $excluded );
144        }
145        if ( '' === $loader ) {
146            return;
147        }
148
149        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSS generated and escaped by WP_Font_Face.
150        echo '<noscript><style class="wp-fonts-local">' . $css . "</style></noscript>\n";
151        echo $loader; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built by wp_get_inline_script_tag().
152    }
153
154    /**
155     * Response headers set so far, as headers_list() returns them.
156     *
157     * @return string[]
158     */
159    protected function get_response_headers() {
160        return headers_list();
161    }
162
163    /**
164     * Whether an enforced Content-Security-Policy header would stop the inline loader from running.
165     *
166     * @param string[] $headers Response headers, as headers_list() returns them.
167     * @param string   $tag     The loader's <script> tag, including any nonce WordPress added.
168     * @return bool
169     */
170    public static function csp_blocks_inline_script( array $headers, $tag ) {
171        $nonce = preg_match( '/\snonce=["\']([^"\']+)["\']/', $tag, $match ) ? $match[1] : null;
172
173        $policies = array();
174        foreach ( $headers as $header ) {
175            // Report-Only policies don't block, and don't match: their header name continues past "Policy".
176            if ( preg_match( '/^content-security-policy\s*:(.*)$/i', $header, $value ) ) {
177                // One header can carry several comma-joined policies, and each is enforced.
178                $policies = array_merge( $policies, explode( ',', $value[1] ) );
179            }
180        }
181
182        foreach ( $policies as $policy ) {
183            $directives = array();
184            foreach ( explode( ';', $policy ) as $directive ) {
185                $parts = preg_split( '/\s+/', trim( $directive ), -1, PREG_SPLIT_NO_EMPTY );
186                $name  = strtolower( (string) array_shift( $parts ) );
187                if ( '' !== $name && ! isset( $directives[ $name ] ) ) {
188                    $directives[ $name ] = $parts;
189                }
190            }
191
192            $sources = $directives['script-src-elem'] ?? $directives['script-src'] ?? $directives['default-src'] ?? null;
193            if ( null === $sources || ( null !== $nonce && in_array( "'nonce-{$nonce}'", $sources, true ) ) ) {
194                continue;
195            }
196
197            // A nonce, hash or 'strict-dynamic' makes browsers ignore 'unsafe-inline'.
198            $keywords = array_map( 'strtolower', $sources );
199            if ( preg_grep( "/^'(nonce-|sha256-|sha384-|sha512-|strict-dynamic')/", $keywords ) || ! in_array( "'unsafe-inline'", $keywords, true ) ) {
200                return true;
201            }
202        }
203
204        return false;
205    }
206
207    /**
208     * The font-family name prefixes the site owner saved, such as icon fonts that must not flash.
209     *
210     * @return string[]
211     */
212    public static function get_excluded_families() {
213        $saved = function_exists( 'jetpack_boost_ds_get' ) ? jetpack_boost_ds_get( 'defer_fonts_excludes' ) : self::DEFAULT_EXCLUDES;
214
215        /**
216         * Filters the font-family names Defer Web Fonts loads normally, matched case-insensitively as a prefix.
217         *
218         * @since $$next-version$$
219         *
220         * @param string[] $prefixes Font-family name prefixes from the module's settings.
221         */
222        return (array) apply_filters( 'jetpack_boost_defer_fonts_excluded_families', is_array( $saved ) ? $saved : self::DEFAULT_EXCLUDES );
223    }
224
225    /**
226     * Split font families into those to defer and those whose name starts with an excluded prefix.
227     *
228     * @param array    $fonts    Font families, each a list of font faces, as WP_Font_Face_Resolver returns them.
229     * @param string[] $prefixes Font-family name prefixes to leave to core, matched case-insensitively.
230     * @return array The families to defer, then the excluded ones.
231     */
232    public static function split_excluded( array $fonts, array $prefixes ) {
233        $normalize = static function ( $name ) {
234            return strtolower( trim( (string) $name, "\"' " ) );
235        };
236        $prefixes  = array_filter( array_map( $normalize, $prefixes ), 'strlen' );
237
238        $deferred = array();
239        $excluded = array();
240        foreach ( $fonts as $key => $faces ) {
241            $family = $normalize( reset( $faces )['font-family'] ?? '' );
242
243            $is_excluded = false;
244            foreach ( $prefixes as $prefix ) {
245                if ( str_starts_with( $family, $prefix ) ) {
246                    $is_excluded = true;
247                    break;
248                }
249            }
250
251            if ( $is_excluded ) {
252                $excluded[ $key ] = $faces;
253            } else {
254                $deferred[ $key ] = $faces;
255            }
256        }
257
258        return array( $deferred, $excluded );
259    }
260
261    /**
262     * Set `font-display: swap` on every font face resolved from theme.json.
263     *
264     * @param array $fonts Font families, each a list of font faces, as WP_Font_Face_Resolver returns them.
265     * @return array
266     */
267    public static function with_swap( array $fonts ) {
268        foreach ( $fonts as $family => $faces ) {
269            foreach ( array_keys( $faces ) as $index ) {
270                $fonts[ $family ][ $index ]['font-display'] = 'swap';
271            }
272        }
273
274        return $fonts;
275    }
276
277    /**
278     * Pull the CSS out of the <style> element WP_Font_Face prints.
279     *
280     * @param string $html Printed markup.
281     * @return string
282     */
283    public static function extract_css( $html ) {
284        if ( ! preg_match( '#<style\b[^>]*>(.*)</style>#is', $html, $matches ) ) {
285            return '';
286        }
287
288        return trim( $matches[1] );
289    }
290
291    /**
292     * Script that adds the font faces after `load`, or straight away once this browser has them cached.
293     *
294     * @param string $css The @font-face rules.
295     * @return string
296     */
297    public static function get_loader_script( $css ) {
298        $encode = static function ( $value ) {
299            return wp_json_encode( $value, JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES );
300        };
301
302        return sprintf(
303            // Adds once: on `load`, after LOAD_WAIT_MS at the latest, or at once if `load` already fired (delayed-JS plugins).
304            // Waits a frame before fonts.ready so the new fonts are pending when it is checked.
305            '(function(css,key,hash,wait){var d=document,stored,done;function add(){if(done){return}done=1;var s=d.createElement("style");s.className="wp-fonts-local";s.textContent=css;d.head.appendChild(s);d.fonts&&requestAnimationFrame(function(){d.fonts.ready.then(function(){try{sessionStorage.setItem(key,hash)}catch(e){}})})}try{stored=sessionStorage.getItem(key)}catch(e){}if(stored===hash||d.readyState==="complete"){add()}else{addEventListener("load",add);setTimeout(add,wait)}})(%s,%s,%s,%d);',
306            $encode( $css ),
307            $encode( self::STORAGE_KEY . '-' . get_current_blog_id() ),
308            $encode( substr( md5( $css ), 0, 12 ) ),
309            /**
310             * Filters how long Defer Web Fonts waits for `load` before adding the fonts anyway.
311             *
312             * Raise it when a slow LCP image would otherwise share bandwidth with the fonts.
313             *
314             * @since $$next-version$$
315             *
316             * @param int $wait Milliseconds to wait. Default 3000.
317             */
318            max( 0, (int) apply_filters( 'jetpack_boost_defer_fonts_load_wait', self::LOAD_WAIT_MS ) )
319        );
320    }
321}