Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
89.89% covered (warning)
89.89%
169 / 188
16.67% covered (danger)
16.67%
1 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
Scan_Status
90.32% covered (success)
90.32%
168 / 186
16.67% covered (danger)
16.67%
1 / 6
50.09
0.00% covered (danger)
0.00%
0 / 1
 get_status
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
6.07
 get_cached_status
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 get_api_url
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 fetch_from_api
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
5.00
 normalize_api_data
93.08% covered (success)
93.08%
121 / 130
0.00% covered (danger)
0.00%
0 / 1
25.21
 sort_threats
69.23% covered (warning)
69.23%
9 / 13
0.00% covered (danger)
0.00%
0 / 1
8.43
1<?php
2/**
3 * Class to handle the Scan Status of Jetpack Protect
4 *
5 * @phan-suppress PhanDeprecatedFunction -- Maintaining backwards compatibility.
6 *
7 * @package automattic/jetpack-protect-status
8 */
9
10namespace Automattic\Jetpack\Protect_Status;
11
12use Automattic\Jetpack\Connection\Client;
13use Automattic\Jetpack\Connection\Manager as Connection_Manager;
14use Automattic\Jetpack\Plugins_Installer;
15use Automattic\Jetpack\Protect_Models\Extension_Model;
16use Automattic\Jetpack\Protect_Models\Status_Model;
17use Automattic\Jetpack\Protect_Models\Threat_Model;
18use Automattic\Jetpack\Sync\Functions as Sync_Functions;
19use Jetpack_Options;
20use WP_Error;
21
22if ( ! defined( 'ABSPATH' ) ) {
23    exit( 0 );
24}
25
26/**
27 * Class that handles fetching of threats from the Scan API
28 */
29class Scan_Status extends Status {
30
31    /**
32     * Scan endpoint
33     *
34     * @var string
35     */
36    const SCAN_API_BASE = '/sites/%d/scan';
37
38    /**
39     * Name of the option where status is stored
40     *
41     * @var string
42     */
43    const OPTION_NAME = 'jetpack_scan_status';
44
45    /**
46     * Name of the option where the timestamp of the status is stored
47     *
48     * @var string
49     */
50    const OPTION_TIMESTAMP_NAME = 'jetpack_scan_status_timestamp';
51
52    /**
53     * Time in seconds that the cache should last
54     *
55     * @var int
56     */
57    const OPTION_EXPIRES_AFTER = 300; // 5 minutes.
58
59    /**
60     * Gets the current status of the Jetpack Protect checks
61     *
62     * @param bool $refresh_from_wpcom Refresh the local plan and status cache from wpcom.
63     * @return Status_Model
64     */
65    public static function get_status( $refresh_from_wpcom = false ) {
66        if ( self::$status !== null ) {
67            return self::$status;
68        }
69
70        if ( $refresh_from_wpcom || ! self::should_use_cache() || self::is_cache_expired() ) {
71            $status = self::fetch_from_api();
72        } else {
73            $status = self::get_from_options();
74        }
75
76        if ( is_wp_error( $status ) ) {
77            $status = new Status_Model(
78                array(
79                    'error'         => true,
80                    'error_code'    => $status->get_error_code(),
81                    'error_message' => $status->get_error_message(),
82                )
83            );
84        } else {
85            $status = self::normalize_api_data( $status );
86        }
87
88        self::$status = $status;
89        return $status;
90    }
91
92    /**
93     * Gets the last Scan status stored on the site, even if it has expired, without asking WordPress.com.
94     *
95     * @since $$next-version$$
96     *
97     * @return Status_Model|null Null when no status has been stored yet.
98     */
99    public static function get_cached_status() {
100        $scan_data = self::get_from_options();
101        return is_object( $scan_data ) ? self::normalize_api_data( $scan_data ) : null;
102    }
103
104    /**
105     * Gets the Scan API endpoint
106     *
107     * @return WP_Error|string
108     */
109    public static function get_api_url() {
110        $blog_id      = Jetpack_Options::get_option( 'id' );
111        $is_connected = ( new Connection_Manager() )->is_connected();
112
113        if ( ! $blog_id || ! $is_connected ) {
114            return new WP_Error( 'site_not_connected' );
115        }
116
117        $api_url = sprintf( self::SCAN_API_BASE, $blog_id );
118
119        return $api_url;
120    }
121
122    /**
123     * Fetches the status data from the Scan API
124     *
125     * @return WP_Error|array
126     */
127    public static function fetch_from_api() {
128        $api_url = self::get_api_url();
129        if ( is_wp_error( $api_url ) ) {
130            return $api_url;
131        }
132
133        $response = Client::wpcom_json_api_request_as_blog(
134            self::get_api_url(),
135            '2',
136            array(
137                'method'  => 'GET',
138                'timeout' => 30,
139            ),
140            null,
141            'wpcom'
142        );
143
144        $response_code = wp_remote_retrieve_response_code( $response );
145
146        if ( is_wp_error( $response ) || 200 !== $response_code || empty( $response['body'] ) ) {
147            return new WP_Error( 'failed_fetching_status', 'Failed to fetch Scan data from the server', array( 'status' => $response_code ) );
148        }
149
150        $body = json_decode( wp_remote_retrieve_body( $response ) );
151        self::update_status_option( $body );
152        return $body;
153    }
154
155    /**
156     * Normalize API Data
157     *
158     * Formats the payload from the Scan API into an instance of Status_Model.
159     *
160     * @phan-suppress PhanDeprecatedProperty -- Maintaining backwards compatibility.
161     *
162     * @param object $scan_data The data returned by the scan API.
163     *
164     * @return Status_Model
165     */
166    private static function normalize_api_data( $scan_data ) {
167        global $wp_version;
168
169        $installed_plugins = Plugins_Installer::get_plugins();
170        $installed_themes  = Sync_Functions::get_themes();
171
172        $plugins  = array();
173        $themes   = array();
174        $core     = new Extension_Model(
175            array(
176                'name'    => 'WordPress',
177                'slug'    => 'wordpress',
178                'version' => $wp_version,
179                'type'    => 'core',
180                'checked' => true, // to do: default to false once Scan API has manifest
181            )
182        );
183        $files    = array();
184        $database = array();
185
186        $status = new Status_Model(
187            array(
188                'data_source'         => 'scan_api',
189                'status'              => $scan_data->state ?? null,
190                'num_threats'         => 0,
191                'num_themes_threats'  => 0,
192                'num_plugins_threats' => 0,
193                'has_unchecked_items' => false,
194                'current_progress'    => $scan_data->current->progress ?? null,
195            )
196        );
197
198        // Format the "last checked" timestamp.
199        if ( ! empty( $scan_data->most_recent->timestamp ) ) {
200            $date                 = new \DateTime( $scan_data->most_recent->timestamp );
201            $status->last_checked = $date->format( 'Y-m-d H:i:s' );
202        }
203
204        // Ensure all installed plugins and themes are represented in the status.
205        foreach ( $installed_plugins as $path => $installed_plugin ) {
206            $slug   = str_replace( '.php', '', explode( '/', $path )[0] );
207            $plugin = new Extension_Model(
208                array(
209                    'name'    => $installed_plugin['Name'],
210                    'version' => $installed_plugin['Version'],
211                    'slug'    => $slug,
212                    'type'    => 'plugins',
213                    'checked' => true, // to do: default to false once Scan API has manifest
214                )
215            );
216
217            $plugins[ $slug ] = $plugin;
218        }
219        foreach ( $installed_themes as $path => $installed_theme ) {
220            $slug  = str_replace( '.php', '', explode( '/', $path )[0] );
221            $theme = new Extension_Model(
222                array(
223                    'name'    => $installed_theme['Name'],
224                    'version' => $installed_theme['Version'],
225                    'slug'    => $slug,
226                    'type'    => 'themes',
227                    'checked' => true, // to do: default to false once Scan API has manifest
228                )
229            );
230
231            $themes[ $slug ] = $theme;
232        }
233
234        // Merge the threats into the status model.
235        if ( isset( $scan_data->threats ) && is_array( $scan_data->threats ) ) {
236            foreach ( $scan_data->threats as $scan_threat ) {
237                if ( isset( $scan_threat->fixable ) && $scan_threat->fixable ) {
238                    $status->fixable_threat_ids[] = $scan_threat->id;
239                }
240
241                $db_details = null;
242                if ( ! empty( $scan_threat->table ) ) {
243                    $db_details = (object) array_merge(
244                        array(
245                            'table'     => $scan_threat->table,
246                            'pk_column' => $scan_threat->pk_column ?? null,
247                            'pk_value'  => $scan_threat->value ?? null,
248                        ),
249                        ! empty( $scan_threat->details ) ? array( 'details' => $scan_threat->details ) : array()
250                    );
251                }
252
253                $threat = new Threat_Model(
254                    array(
255                        'id'                        => $scan_threat->id ?? null,
256                        'signature'                 => $scan_threat->signature ?? null,
257                        'title'                     => $scan_threat->title ?? null,
258                        'description'               => $scan_threat->description ?? null,
259                        'vulnerability_description' => $scan_threat->vulnerability_description ?? null,
260                        'extension'                 => $scan_threat->extension ?? null,
261                        'fix_description'           => $scan_threat->fix_description ?? null,
262                        'payload_subtitle'          => $scan_threat->payload_subtitle ?? null,
263                        'payload_description'       => $scan_threat->payload_description ?? null,
264                        'first_detected'            => $scan_threat->first_detected ?? null,
265                        'fixed_in'                  => isset( $scan_threat->fixer->fixer ) && 'update' === $scan_threat->fixer->fixer ? $scan_threat->fixer->target : null,
266                        'severity'                  => $scan_threat->severity ?? null,
267                        'fixable'                   => $scan_threat->fixer ?? null,
268                        'status'                    => $scan_threat->status ?? null,
269                        'filename'                  => $scan_threat->filename ?? null,
270                        'context'                   => $scan_threat->context ?? null,
271                        'source'                    => $scan_threat->source ?? null,
272                        'table'                     => $scan_threat->table ?? null,
273                        'details'                   => $db_details,
274                    )
275                );
276
277                // Theme and Plugin Threats
278                if ( ! empty( $scan_threat->extension ) && in_array( $scan_threat->extension->type, array( 'plugin', 'theme' ), true ) ) {
279                    $installed_extension = 'plugin' === $scan_threat->extension->type ? ( $plugins[ $scan_threat->extension->slug ] ?? null ) : ( $themes[ $scan_threat->extension->slug ] ?? null );
280
281                    // If the extension is no longer installed, skip this threat.
282                    // todo: use version_compare()
283                    if ( ! $installed_extension ) {
284                        continue;
285                    }
286
287                    // Push the threat to the appropriate extension.
288                    switch ( $scan_threat->extension->type ) {
289                        case 'plugin':
290                            $plugins[ $scan_threat->extension->slug ]->threats[] = clone $threat;
291                            ++$status->num_plugins_threats;
292                            break;
293                        case 'theme':
294                            $themes[ $scan_threat->extension->slug ]->threats[] = clone $threat;
295                            ++$status->num_themes_threats;
296                            break;
297                        default:
298                            break;
299                    }
300
301                    $threat->extension = new Extension_Model(
302                        array(
303                            'name'    => $scan_threat->extension->name ?? null,
304                            'slug'    => $scan_threat->extension->slug ?? null,
305                            'version' => $scan_threat->extension->version ?? null,
306                            'type'    => $scan_threat->extension->type . 's',
307                            'checked' => $installed_extension->version === $scan_threat->extension->version,
308                        )
309                    );
310                } elseif ( isset( $threat->signature ) && 'Vulnerable.WP.Core' === $threat->signature ) {
311                    // Vulnerable WordPress Core Version Threats
312
313                    // If the core version has changed, skip this threat.
314                    // todo: use version_compare()
315                    if ( $scan_threat->version !== $wp_version ) {
316                        continue;
317                    }
318
319                    $core->threats[] = $threat;
320                } elseif ( ! empty( $threat->filename ) ) {
321                    // File Threats
322                    $files[] = $threat;
323                } elseif ( ! empty( $scan_threat->table ) ) {
324                    // Database Threats
325                    $database[] = $threat;
326                }
327
328                $status->threats[] = $threat;
329                ++$status->num_threats;
330            }
331        }
332
333        $status->threats = static::sort_threats( $status->threats );
334
335        // maintain deprecated properties for backwards compatibility
336        $status->plugins  = array_values( $plugins );
337        $status->themes   = array_values( $themes );
338        $status->core     = $core;
339        $status->files    = $files;
340        $status->database = $database;
341
342        return $status;
343    }
344
345    /**
346     * Sort By Threats
347     *
348     * @param array<Threat_Model> $threats Array of threats to sort.
349     *
350     * @return array<Threat_Model> The sorted $threats array.
351     */
352    protected static function sort_threats( $threats ) {
353        usort(
354            $threats,
355            function ( $a, $b ) {
356                // Order by active status first...
357                if ( $a->status !== $b->status ) {
358                    return 'active' === $a->status ? -1 : 1;
359                }
360
361                // ...then by severity...
362                if ( $a->severity !== $b->severity ) {
363                    return $a->severity > $b->severity ? -1 : 1;
364                }
365
366                // ...then date added.
367                if ( $a->first_detected !== $b->first_detected ) {
368                    return strtotime( $a->first_detected ) < strtotime( $b->first_detected ) ? -1 : 1;
369                }
370
371                return 0;
372            }
373        );
374
375        return $threats;
376    }
377}