Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
17.28% covered (danger)
17.28%
14 / 81
23.53% covered (danger)
23.53%
4 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
Cloud_CSS
17.28% covered (danger)
17.28%
14 / 81
23.53% covered (danger)
23.53%
4 / 17
688.23
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
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 activate
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 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
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
6
 handle_save_post
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
42
 regenerate_cloud_css
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 is_post_in_latest_providers_list
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 handle_critical_css_invalidated
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_all_providers
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 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\Premium_Features;
21use Automattic\Jetpack_Boost\REST_API\Contracts\Has_Always_Available_Endpoints;
22use Automattic\Jetpack_Boost\REST_API\Endpoints\Update_Cloud_CSS;
23
24class Cloud_CSS implements Feature, Has_Activate, Has_Always_Available_Endpoints, Changes_Output_After_Activation, Optimization, Needs_To_Be_Ready, Needs_Website_To_Be_Public {
25
26    /** User has requested regeneration manually or through activating the module. */
27    const REGENERATE_REASON_USER_REQUEST = 'user_request';
28
29    /** A post was updated/created. */
30    const REGENERATE_REASON_SAVE_POST = 'save_post';
31
32    /** A cornerstone page or the list of cornerstone pages was updated. */
33    const REGENERATE_REASON_CORNERSTONE_UPDATE = 'cornerstone_update';
34
35    /** Existing critical CSS invalidated because of a significant change, e.g. Theme changed. */
36    const REGENERATE_REASON_INVALIDATED = 'invalidated';
37
38    /** Requesting a regeneration because the previous request had failed and this is a followup attempt to regenerate Critical CSS. */
39    const REGENERATE_REASON_FOLLOWUP = 'followup';
40
41    /**
42     * Critical CSS storage class instance.
43     *
44     * @var Critical_CSS_Storage
45     */
46    protected $storage;
47
48    /**
49     * Critical CSS Provider Paths.
50     *
51     * @var Source_Providers
52     */
53    protected $paths;
54
55    public function __construct() {
56        $this->storage = new Critical_CSS_Storage();
57        $this->paths   = new Source_Providers();
58    }
59
60    public function setup() {
61        add_action( 'wp', array( $this, 'display_critical_css' ) );
62        add_action( 'save_post', array( $this, 'handle_save_post' ), 10, 2 );
63        add_action( 'jetpack_boost_critical_css_invalidated', array( $this, 'handle_critical_css_invalidated' ) );
64        add_filter( 'jetpack_boost_total_problem_count', array( $this, 'update_total_problem_count' ) );
65
66        Generator::init();
67        Critical_CSS_Invalidator::init();
68        Cloud_CSS_Followup::init();
69
70        return true;
71    }
72
73    public static function activate() {
74        ( new Regenerate() )->start();
75    }
76
77    /**
78     * Check if the module is ready and already serving critical CSS.
79     *
80     * @return bool
81     */
82    public function is_ready() {
83        return ( new Critical_CSS_State() )->is_generated();
84    }
85
86    /**
87     * Get the action names that will be triggered when the module is ready and serving critical CSS.
88     *
89     * @return string[]
90     */
91    public static function get_change_output_action_names() {
92        return array( 'jetpack_boost_critical_css_invalidated', 'jetpack_boost_critical_css_generated' );
93    }
94
95    public static function is_available() {
96        return true === Premium_Features::has_feature( Premium_Features::CLOUD_CSS );
97    }
98
99    public static function get_slug() {
100        return 'cloud_css';
101    }
102
103    public function get_always_available_endpoints() {
104        return array(
105            new Update_Cloud_CSS(),
106        );
107    }
108
109    public function display_critical_css() {
110
111        // Don't look for Critical CSS in the dashboard.
112        if ( is_admin() ) {
113            return;
114        }
115
116        // Don't show Critical CSS in customizer previews.
117        if ( is_customize_preview() ) {
118            return;
119        }
120
121        // Don't display Critical CSS, if current page load is by the Critical CSS generator.
122        if ( Generator::is_generating_critical_css() ) {
123            return;
124        }
125
126        // Get the Critical CSS to show.
127        $critical_css = $this->paths->get_current_request_css();
128        if ( ! $critical_css ) {
129            $keys    = $this->paths->get_current_request_css_keys();
130            $pending = ( new Critical_CSS_State() )->has_pending_provider( $keys );
131
132            // If Cloud CSS is still generating and the user is logged in, render the status information in a comment.
133            if ( $pending && is_user_logged_in() ) {
134                $display = new Display_Critical_CSS( '/* ' . __( 'Jetpack Boost is currently generating critical css for this page', 'jetpack-boost' ) . ' */' );
135                add_action( 'wp_head', array( $display, 'display_critical_css' ), Display_Critical_CSS::HEAD_PRIORITY );
136            }
137            return;
138        }
139
140        $display = new Display_Critical_CSS( $critical_css, $this->paths->get_current_critical_css_key() );
141        $display->register_hooks();
142    }
143
144    /**
145     * Create a Cloud CSS requests for provider groups.
146     *
147     * Initialize the Cloud CSS request. Provide $post parameter to limit generating to provider groups only associated
148     * with a specific post.
149     */
150    public function generate_cloud_css( $reason, $providers = array() ) {
151        $grouped_urls   = array();
152        $grouped_ratios = array();
153
154        foreach ( $providers as $source ) {
155            $provider                    = $source['key'];
156            $grouped_urls[ $provider ]   = $source['urls'];
157            $grouped_ratios[ $provider ] = $source['success_ratio'];
158        }
159
160        // Send the request to the Cloud.
161        $payload              = array(
162            'providers'     => $grouped_urls,
163            'successRatios' => $grouped_ratios,
164        );
165        $payload['requestId'] = md5(
166            wp_json_encode(
167                $payload,
168                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.
169            ) . time()
170        );
171        $payload['reason']    = $reason;
172        return Boost_API::post( 'cloud-css', $payload );
173    }
174
175    /**
176     * Handle regeneration of Cloud CSS when a post is saved.
177     */
178    public function handle_save_post( $post_id, $post ) {
179        if ( ! $post || ! isset( $post->post_type ) || ! is_post_publicly_viewable( $post ) ) {
180            return;
181        }
182
183        if ( Cornerstone_Utils::is_cornerstone_page( $post_id ) ) {
184            $this->regenerate_cloud_css( self::REGENERATE_REASON_CORNERSTONE_UPDATE, $this->get_all_providers() );
185            return;
186        }
187
188        // This checks against the latest providers list, not the list
189        // stored in the database because newly added posts are always
190        // included in the providers list that will be used to generate
191        // the Cloud CSS.
192        if ( $this->is_post_in_latest_providers_list( $post ) ) {
193            $this->regenerate_cloud_css( self::REGENERATE_REASON_SAVE_POST, $this->get_all_providers( array( $post ) ) );
194        }
195    }
196
197    public function regenerate_cloud_css( $reason, $providers ) {
198        $result = $this->generate_cloud_css( $reason, $providers );
199        if ( is_wp_error( $result ) ) {
200            $state = new Critical_CSS_State();
201            $state->set_error( $result->get_error_message() )->save();
202        }
203        return $result;
204    }
205
206    /**
207     * Check if the post is in the latest providers list.
208     *
209     * @param int|\WP_Post $post The post to check.
210     *
211     * @return bool
212     */
213    public function is_post_in_latest_providers_list( $post ) {
214        $post_link = get_permalink( $post );
215        $providers = $this->get_all_providers();
216
217        foreach ( $providers as $provider ) {
218            if ( in_array( $post_link, $provider['urls'], true ) ) {
219                return true;
220            }
221        }
222
223        return false;
224    }
225
226    /**
227     * Called when stored Critical CSS has been invalidated. Triggers a new Cloud CSS request.
228     */
229    public function handle_critical_css_invalidated() {
230        $this->regenerate_cloud_css( self::REGENERATE_REASON_INVALIDATED, $this->get_all_providers() );
231        Cloud_CSS_Followup::schedule();
232    }
233
234    public function get_all_providers( $context_posts = array() ) {
235        $source_providers = new Source_Providers();
236        return $source_providers->get_provider_sources( $context_posts );
237    }
238
239    public function get_existing_sources() {
240        $state = new Critical_CSS_State();
241        $data  = $state->get();
242        if ( ! empty( $data['providers'] ) ) {
243            $providers = $data['providers'];
244        } else {
245            $providers = $this->get_all_providers();
246        }
247
248        return $providers;
249    }
250
251    /**
252     * Updates the total problem count for Boost if something's
253     * wrong with Cloud CSS.
254     *
255     * @param int $count The current problem count.
256     *
257     * @return int
258     */
259    public function update_total_problem_count( $count ) {
260        return ( new Critical_CSS_State() )->has_errors() ? ++$count : $count;
261    }
262}