Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
74.47% covered (warning)
74.47%
70 / 94
57.89% covered (warning)
57.89%
11 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Cloud_CSS
74.47% covered (warning)
74.47%
70 / 94
57.89% covered (warning)
57.89%
11 / 19
71.36
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setup
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 activate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_ready
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_change_output_action_names
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_always_available_endpoints
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 display_critical_css
43.75% covered (danger)
43.75%
7 / 16
0.00% covered (danger)
0.00%
0 / 1
15.72
 generate_cloud_css
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
2
 handle_save_post
57.14% covered (warning)
57.14%
4 / 7
0.00% covered (danger)
0.00%
0 / 1
8.83
 handle_style_save
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 regenerate_after_style_save
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 regenerate_cloud_css
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 is_post_in_latest_providers_list
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 handle_critical_css_invalidated
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_all_providers
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_existing_sources
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 update_total_problem_count
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3namespace Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS;
4
5use Automattic\Jetpack\Boost_Core\Lib\Boost_API;
6use Automattic\Jetpack_Boost\Contracts\Changes_Output_After_Activation;
7use Automattic\Jetpack_Boost\Contracts\Feature;
8use Automattic\Jetpack_Boost\Contracts\Has_Activate;
9use Automattic\Jetpack_Boost\Contracts\Needs_To_Be_Ready;
10use Automattic\Jetpack_Boost\Contracts\Needs_Website_To_Be_Public;
11use Automattic\Jetpack_Boost\Contracts\Optimization;
12use Automattic\Jetpack_Boost\Lib\Cornerstone\Cornerstone_Utils;
13use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Invalidator;
14use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State;
15use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Storage;
16use Automattic\Jetpack_Boost\Lib\Critical_CSS\Display_Critical_CSS;
17use Automattic\Jetpack_Boost\Lib\Critical_CSS\Generator;
18use Automattic\Jetpack_Boost\Lib\Critical_CSS\Regenerate;
19use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Source_Providers;
20use Automattic\Jetpack_Boost\Lib\Environment_Change_Detector;
21use Automattic\Jetpack_Boost\Lib\Premium_Features;
22use Automattic\Jetpack_Boost\REST_API\Contracts\Has_Always_Available_Endpoints;
23use Automattic\Jetpack_Boost\REST_API\Endpoints\Update_Cloud_CSS;
24
25class Cloud_CSS implements Feature, Has_Activate, Has_Always_Available_Endpoints, Changes_Output_After_Activation, Optimization, Needs_To_Be_Ready, Needs_Website_To_Be_Public {
26
27    /** User has requested regeneration manually or through activating the module. */
28    const REGENERATE_REASON_USER_REQUEST = 'user_request';
29
30    /** A post was updated/created. */
31    const REGENERATE_REASON_SAVE_POST = 'save_post';
32
33    /** A cornerstone page or the list of cornerstone pages was updated. */
34    const REGENERATE_REASON_CORNERSTONE_UPDATE = 'cornerstone_update';
35
36    /** Existing critical CSS invalidated because of a significant change, e.g. Theme changed. */
37    const REGENERATE_REASON_INVALIDATED = 'invalidated';
38
39    /** Requesting a regeneration because the previous request had failed and this is a followup attempt to regenerate Critical CSS. */
40    const REGENERATE_REASON_FOLLOWUP = 'followup';
41
42    const STYLE_REGENERATION_HOOK = 'jetpack_boost_cloud_css_style_regeneration';
43
44    /**
45     * Critical CSS storage class instance.
46     *
47     * @var Critical_CSS_Storage
48     */
49    protected $storage;
50
51    /**
52     * Critical CSS Provider Paths.
53     *
54     * @var Source_Providers
55     */
56    protected $paths;
57
58    public function __construct() {
59        $this->storage = new Critical_CSS_Storage();
60        $this->paths   = new Source_Providers();
61    }
62
63    public function setup() {
64        add_action( 'wp', array( $this, 'display_critical_css' ) );
65        add_action( 'save_post', array( $this, 'handle_save_post' ), 10, 2 );
66        add_action( 'save_post', array( $this, 'handle_style_save' ), 10, 3 );
67        add_action( self::STYLE_REGENERATION_HOOK, array( $this, 'regenerate_after_style_save' ) );
68        add_action( 'jetpack_boost_critical_css_invalidated', array( $this, 'handle_critical_css_invalidated' ) );
69        add_filter( 'jetpack_boost_total_problem_count', array( $this, 'update_total_problem_count' ) );
70
71        Generator::init();
72        Critical_CSS_Invalidator::init();
73        Cloud_CSS_Followup::init();
74
75        return true;
76    }
77
78    public static function activate() {
79        ( new Regenerate() )->start();
80    }
81
82    /**
83     * Check if the module is ready and already serving critical CSS.
84     *
85     * @return bool
86     */
87    public function is_ready() {
88        return ( new Critical_CSS_State() )->is_generated();
89    }
90
91    /**
92     * Get the action names that will be triggered when the module is ready and serving critical CSS.
93     *
94     * @return string[]
95     */
96    public static function get_change_output_action_names() {
97        return array( 'jetpack_boost_critical_css_invalidated', 'jetpack_boost_critical_css_generated' );
98    }
99
100    public static function is_available() {
101        return true === Premium_Features::has_feature( Premium_Features::CLOUD_CSS );
102    }
103
104    public static function get_slug() {
105        return 'cloud_css';
106    }
107
108    public function get_always_available_endpoints() {
109        return array(
110            new Update_Cloud_CSS(),
111        );
112    }
113
114    public function display_critical_css() {
115
116        // Don't look for Critical CSS in the dashboard.
117        if ( is_admin() ) {
118            return;
119        }
120
121        // Don't show Critical CSS in customizer previews.
122        if ( is_customize_preview() ) {
123            return;
124        }
125
126        // Don't display Critical CSS, if current page load is by the Critical CSS generator.
127        if ( Generator::is_generating_critical_css() ) {
128            return;
129        }
130
131        // Get the Critical CSS to show.
132        $critical_css = $this->paths->get_current_request_css();
133        if ( ! $critical_css ) {
134            $keys    = $this->paths->get_current_request_css_keys();
135            $pending = ( new Critical_CSS_State() )->has_pending_provider( $keys );
136
137            // If Cloud CSS is still generating and the user is logged in, render the status information in a comment.
138            if ( $pending && is_user_logged_in() ) {
139                $display = new Display_Critical_CSS( '/* ' . __( 'Jetpack Boost is currently generating critical css for this page', 'jetpack-boost' ) . ' */' );
140                add_action( 'wp_head', array( $display, 'display_critical_css' ), Display_Critical_CSS::HEAD_PRIORITY );
141            }
142            return;
143        }
144
145        $display = new Display_Critical_CSS( $critical_css, $this->paths->get_current_critical_css_key() );
146        $display->register_hooks();
147    }
148
149    /**
150     * Create a Cloud CSS requests for provider groups.
151     *
152     * Initialize the Cloud CSS request. Provide $post parameter to limit generating to provider groups only associated
153     * with a specific post.
154     */
155    public function generate_cloud_css( $reason, $providers = array() ) {
156        $grouped_urls   = array();
157        $grouped_ratios = array();
158
159        foreach ( $providers as $source ) {
160            $provider                    = $source['key'];
161            $grouped_urls[ $provider ]   = $source['urls'];
162            $grouped_ratios[ $provider ] = $source['success_ratio'];
163        }
164
165        // Send the request to the Cloud.
166        $payload              = array(
167            'providers'     => $grouped_urls,
168            'successRatios' => $grouped_ratios,
169        );
170        $payload['requestId'] = md5(
171            wp_json_encode(
172                $payload,
173                0 // phpcs:ignore Jetpack.Functions.JsonEncodeFlags.ZeroFound -- No `json_encode()` flags because this needs to match whatever is calculating the hash on the other end.
174            ) . time()
175        );
176        $payload['reason']    = $reason;
177        return Boost_API::post( 'cloud-css', $payload );
178    }
179
180    /**
181     * Handle regeneration of Cloud CSS when a post is saved.
182     */
183    public function handle_save_post( $post_id, $post ) {
184        if ( ! $post || ! isset( $post->post_type ) || ! is_post_publicly_viewable( $post ) ) {
185            return;
186        }
187
188        if ( Cornerstone_Utils::is_cornerstone_page( $post_id ) ) {
189            $this->regenerate_cloud_css( self::REGENERATE_REASON_CORNERSTONE_UPDATE, $this->get_all_providers() );
190            return;
191        }
192
193        // This checks against the latest providers list, not the list
194        // stored in the database because newly added posts are always
195        // included in the providers list that will be used to generate
196        // the Cloud CSS.
197        if ( $this->is_post_in_latest_providers_list( $post ) ) {
198            $this->regenerate_cloud_css( self::REGENERATE_REASON_SAVE_POST, $this->get_all_providers( array( $post ) ) );
199        }
200    }
201
202    /**
203     * Schedule a regeneration of every provider after a template or site-wide style is saved.
204     *
205     * @since $$next-version$$
206     *
207     * @param int      $post_id The ID of the saved post.
208     * @param \WP_Post $post    The saved post.
209     * @param bool     $update  Whether this is an update of an existing post.
210     * @return void
211     */
212    public function handle_style_save( $post_id, $post, $update = true ) {
213        $restyles_every_page = in_array( $post->post_type, array( 'wp_template', 'wp_template_part' ), true ) || in_array( $post->post_type, Environment_Change_Detector::STYLE_POST_TYPES, true );
214        if ( 'publish' !== $post->post_status || ! $restyles_every_page ) {
215            return;
216        }
217
218        // Core inserts an empty Global Styles post the first time an editor loads, so only updates are saves.
219        if ( ! $update && 'wp_global_styles' === $post->post_type ) {
220            return;
221        }
222
223        // One Site Editor save writes several of these posts, so wait for the last.
224        wp_clear_scheduled_hook( self::STYLE_REGENERATION_HOOK );
225        wp_schedule_single_event( time() + 5 * MINUTE_IN_SECONDS, self::STYLE_REGENERATION_HOOK );
226    }
227
228    /**
229     * Regenerate every provider, serving the current Cloud CSS until the new one arrives.
230     *
231     * @since $$next-version$$
232     *
233     * @return void
234     */
235    public function regenerate_after_style_save() {
236        // Boost Cloud batches `save_post` requests for hours but runs this one promptly.
237        $this->regenerate_cloud_css( self::REGENERATE_REASON_INVALIDATED, $this->get_all_providers() );
238        Cloud_CSS_Followup::schedule();
239    }
240
241    public function regenerate_cloud_css( $reason, $providers ) {
242        $result = $this->generate_cloud_css( $reason, $providers );
243        if ( is_wp_error( $result ) ) {
244            $state = new Critical_CSS_State();
245            $state->set_error( $result->get_error_message() )->save();
246        } elseif ( self::REGENERATE_REASON_SAVE_POST !== $reason ) {
247            // A user request, invalidation, cornerstone update or follow-up regenerates the whole site, so a pending style one is redundant.
248            wp_clear_scheduled_hook( self::STYLE_REGENERATION_HOOK );
249        }
250        return $result;
251    }
252
253    /**
254     * Check if the post is in the latest providers list.
255     *
256     * @param int|\WP_Post $post The post to check.
257     *
258     * @return bool
259     */
260    public function is_post_in_latest_providers_list( $post ) {
261        $post_link = get_permalink( $post );
262        $providers = $this->get_all_providers();
263
264        foreach ( $providers as $provider ) {
265            if ( in_array( $post_link, $provider['urls'], true ) ) {
266                return true;
267            }
268        }
269
270        return false;
271    }
272
273    /**
274     * Called when stored Critical CSS has been invalidated. Triggers a new Cloud CSS request.
275     */
276    public function handle_critical_css_invalidated() {
277        $this->regenerate_cloud_css( self::REGENERATE_REASON_INVALIDATED, $this->get_all_providers() );
278        Cloud_CSS_Followup::schedule();
279    }
280
281    public function get_all_providers( $context_posts = array() ) {
282        $source_providers = new Source_Providers();
283        return $source_providers->get_provider_sources( $context_posts );
284    }
285
286    public function get_existing_sources() {
287        $state = new Critical_CSS_State();
288        $data  = $state->get();
289        if ( ! empty( $data['providers'] ) ) {
290            $providers = $data['providers'];
291        } else {
292            $providers = $this->get_all_providers();
293        }
294
295        return $providers;
296    }
297
298    /**
299     * Updates the total problem count for Boost if something's
300     * wrong with Cloud CSS.
301     *
302     * @param int $count The current problem count.
303     *
304     * @return int
305     */
306    public function update_total_problem_count( $count ) {
307        return ( new Critical_CSS_State() )->has_errors() ? ++$count : $count;
308    }
309}