Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.01% covered (success)
91.01%
172 / 189
33.33% covered (danger)
33.33%
2 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
Scan_Status
91.44% covered (success)
91.44%
171 / 187
33.33% covered (danger)
33.33%
2 / 6
49.44
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
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 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.13% covered (success)
93.13%
122 / 131
0.00% covered (danger)
0.00%
0 / 1
25.20
 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 0.9.0
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                'last_scan_failed'    => ! empty( $scan_data->most_recent->error ),
196            )
197        );
198
199        // Format the "last checked" timestamp.
200        if ( ! empty( $scan_data->most_recent->timestamp ) ) {
201            $date                 = new \DateTime( $scan_data->most_recent->timestamp );
202            $status->last_checked = $date->format( 'Y-m-d H:i:s' );
203        }
204
205        // Ensure all installed plugins and themes are represented in the status.
206        foreach ( $installed_plugins as $path => $installed_plugin ) {
207            $slug   = str_replace( '.php', '', explode( '/', $path )[0] );
208            $plugin = new Extension_Model(
209                array(
210                    'name'    => $installed_plugin['Name'],
211                    'version' => $installed_plugin['Version'],
212                    'slug'    => $slug,
213                    'type'    => 'plugins',
214                    'checked' => true, // to do: default to false once Scan API has manifest
215                )
216            );
217
218            $plugins[ $slug ] = $plugin;
219        }
220        foreach ( $installed_themes as $path => $installed_theme ) {
221            $slug  = str_replace( '.php', '', explode( '/', $path )[0] );
222            $theme = new Extension_Model(
223                array(
224                    'name'    => $installed_theme['Name'],
225                    'version' => $installed_theme['Version'],
226                    'slug'    => $slug,
227                    'type'    => 'themes',
228                    'checked' => true, // to do: default to false once Scan API has manifest
229                )
230            );
231
232            $themes[ $slug ] = $theme;
233        }
234
235        // Merge the threats into the status model.
236        if ( isset( $scan_data->threats ) && is_array( $scan_data->threats ) ) {
237            foreach ( $scan_data->threats as $scan_threat ) {
238                if ( isset( $scan_threat->fixable ) && $scan_threat->fixable ) {
239                    $status->fixable_threat_ids[] = $scan_threat->id;
240                }
241
242                $db_details = null;
243                if ( ! empty( $scan_threat->table ) ) {
244                    $db_details = (object) array_merge(
245                        array(
246                            'table'     => $scan_threat->table,
247                            'pk_column' => $scan_threat->pk_column ?? null,
248                            'pk_value'  => $scan_threat->value ?? null,
249                        ),
250                        ! empty( $scan_threat->details ) ? array( 'details' => $scan_threat->details ) : array()
251                    );
252                }
253
254                $threat = new Threat_Model(
255                    array(
256                        'id'                        => $scan_threat->id ?? null,
257                        'signature'                 => $scan_threat->signature ?? null,
258                        'title'                     => $scan_threat->title ?? null,
259                        'description'               => $scan_threat->description ?? null,
260                        'vulnerability_description' => $scan_threat->vulnerability_description ?? null,
261                        'extension'                 => $scan_threat->extension ?? null,
262                        'fix_description'           => $scan_threat->fix_description ?? null,
263                        'payload_subtitle'          => $scan_threat->payload_subtitle ?? null,
264                        'payload_description'       => $scan_threat->payload_description ?? null,
265                        'first_detected'            => $scan_threat->first_detected ?? null,
266                        'fixed_in'                  => isset( $scan_threat->fixer->fixer ) && 'update' === $scan_threat->fixer->fixer ? $scan_threat->fixer->target : null,
267                        'severity'                  => $scan_threat->severity ?? null,
268                        'fixable'                   => $scan_threat->fixer ?? null,
269                        'status'                    => $scan_threat->status ?? null,
270                        'filename'                  => $scan_threat->filename ?? null,
271                        'context'                   => $scan_threat->context ?? null,
272                        'source'                    => $scan_threat->source ?? null,
273                        'table'                     => $scan_threat->table ?? null,
274                        'details'                   => $db_details,
275                    )
276                );
277
278                // Theme and Plugin Threats
279                if ( ! empty( $scan_threat->extension ) && in_array( $scan_threat->extension->type, array( 'plugin', 'theme' ), true ) ) {
280                    $installed_extension = 'plugin' === $scan_threat->extension->type ? ( $plugins[ $scan_threat->extension->slug ] ?? null ) : ( $themes[ $scan_threat->extension->slug ] ?? null );
281
282                    // If the extension is no longer installed, skip this threat.
283                    // todo: use version_compare()
284                    if ( ! $installed_extension ) {
285                        continue;
286                    }
287
288                    // Push the threat to the appropriate extension.
289                    switch ( $scan_threat->extension->type ) {
290                        case 'plugin':
291                            $plugins[ $scan_threat->extension->slug ]->threats[] = clone $threat;
292                            ++$status->num_plugins_threats;
293                            break;
294                        case 'theme':
295                            $themes[ $scan_threat->extension->slug ]->threats[] = clone $threat;
296                            ++$status->num_themes_threats;
297                            break;
298                        default:
299                            break;
300                    }
301
302                    $threat->extension = new Extension_Model(
303                        array(
304                            'name'    => $scan_threat->extension->name ?? null,
305                            'slug'    => $scan_threat->extension->slug ?? null,
306                            'version' => $scan_threat->extension->version ?? null,
307                            'type'    => $scan_threat->extension->type . 's',
308                            'checked' => $installed_extension->version === $scan_threat->extension->version,
309                        )
310                    );
311                } elseif ( isset( $threat->signature ) && 'Vulnerable.WP.Core' === $threat->signature ) {
312                    // Vulnerable WordPress Core Version Threats
313
314                    // If the core version has changed, skip this threat.
315                    // todo: use version_compare()
316                    if ( $scan_threat->version !== $wp_version ) {
317                        continue;
318                    }
319
320                    $core->threats[] = $threat;
321                } elseif ( ! empty( $threat->filename ) ) {
322                    // File Threats
323                    $files[] = $threat;
324                } elseif ( ! empty( $scan_threat->table ) ) {
325                    // Database Threats
326                    $database[] = $threat;
327                }
328
329                $status->threats[] = $threat;
330                ++$status->num_threats;
331            }
332        }
333
334        $status->threats = static::sort_threats( $status->threats );
335
336        // maintain deprecated properties for backwards compatibility
337        $status->plugins  = array_values( $plugins );
338        $status->themes   = array_values( $themes );
339        $status->core     = $core;
340        $status->files    = $files;
341        $status->database = $database;
342
343        return $status;
344    }
345
346    /**
347     * Sort By Threats
348     *
349     * @param array<Threat_Model> $threats Array of threats to sort.
350     *
351     * @return array<Threat_Model> The sorted $threats array.
352     */
353    protected static function sort_threats( $threats ) {
354        usort(
355            $threats,
356            function ( $a, $b ) {
357                // Order by active status first...
358                if ( $a->status !== $b->status ) {
359                    return 'active' === $a->status ? -1 : 1;
360                }
361
362                // ...then by severity...
363                if ( $a->severity !== $b->severity ) {
364                    return $a->severity > $b->severity ? -1 : 1;
365                }
366
367                // ...then date added.
368                if ( $a->first_detected !== $b->first_detected ) {
369                    return strtotime( $a->first_detected ) < strtotime( $b->first_detected ) ? -1 : 1;
370                }
371
372                return 0;
373            }
374        );
375
376        return $threats;
377    }
378}