Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
72.60% covered (warning)
72.60%
159 / 219
76.92% covered (warning)
76.92%
20 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1
Backup
72.81% covered (warning)
72.81%
158 / 217
76.92% covered (warning)
76.92%
20 / 26
221.46
0.00% covered (danger)
0.00%
0 / 1
 register_endpoints
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 get_name
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_title
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_description
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_long_description
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_features
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 get_disclaimers
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 get_wpcom_product_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_post_checkout_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_pricing_for_ui
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 permissions_callback
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_site_backup_undo_event
97.50% covered (success)
97.50%
39 / 40
0.00% covered (danger)
0.00%
0 / 1
9
 get_state_from_wpcom
17.65% covered (danger)
17.65%
3 / 17
0.00% covered (danger)
0.00%
0 / 1
8.03
 get_latest_backups
17.65% covered (danger)
17.65%
3 / 17
0.00% covered (danger)
0.00%
0 / 1
8.03
 does_module_need_attention
28.21% covered (danger)
28.21%
11 / 39
0.00% covered (danger)
0.00%
0 / 1
137.90
 is_upgradable_by_bundle
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_post_activation_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_module_active
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_plan_driven
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_manage_url
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
6
 offers_jetpack_dashboard
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 jetpack_can_host_dashboard
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 plan_opens_jetpack_dashboard
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 get_paid_plan_product_slugs
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 has_plan_on_record
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
 get_status
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
1<?php
2/**
3 * Backup product
4 *
5 * @package my-jetpack
6 */
7
8namespace Automattic\Jetpack\My_Jetpack\Products;
9
10use Automattic\Jetpack\Connection\Client;
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Current_Plan;
13use Automattic\Jetpack\My_Jetpack\Hybrid_Product;
14use Automattic\Jetpack\My_Jetpack\Wpcom_Products;
15use Automattic\Jetpack\Redirect;
16use WP_Error;
17
18if ( ! defined( 'ABSPATH' ) ) {
19    exit( 0 );
20}
21
22/**
23 * Class responsible for handling the Backup product
24 */
25class Backup extends Hybrid_Product {
26    public const BACKUP_STATUS_TRANSIENT_KEY = 'my-jetpack-backup-status';
27
28    public const PLAN_REFRESH_MISS_TRANSIENT_KEY = 'my-jetpack-backup-plan-refresh-miss';
29
30    /**
31     * Prefix of the per-site, per-user transient that keeps the undo event, since WPCOM answers as that user
32     *
33     * @var string
34     */
35    public const UNDO_EVENT_TRANSIENT_PREFIX = 'my-jetpack-backup-undo-event-';
36
37    /**
38     * How long, in seconds, the undo event is reused
39     *
40     * @var int
41     */
42    public const UNDO_EVENT_CACHE_DURATION = 5 * MINUTE_IN_SECONDS;
43
44    /**
45     * The product slug
46     *
47     * @var string
48     */
49    public static $slug = 'backup';
50
51    /**
52     * The filename (id) of the plugin associated with this product.
53     *
54     * @var string
55     */
56    public static $plugin_filename = array(
57        'jetpack-backup/jetpack-backup.php',
58        'backup/jetpack-backup.php',
59        'jetpack-backup-dev/jetpack-backup.php',
60    );
61
62    /**
63     * The slug of the plugin associated with this product.
64     *
65     * @var string
66     */
67    public static $plugin_slug = 'jetpack-backup';
68
69    /**
70     * The Jetpack module name
71     *
72     * @var string
73     */
74    public static $module_name = 'backup';
75
76    /**
77     * The category of the product
78     *
79     * @var string
80     */
81    public static $category = 'security';
82
83    /**
84     * Backup has a standalone plugin
85     *
86     * @var bool
87     */
88    public static $has_standalone_plugin = true;
89
90    /**
91     * Whether this product has a free offering
92     *
93     * @var bool
94     */
95    public static $has_free_offering = false;
96
97    /**
98     * Whether this product requires a plan to work at all
99     *
100     * @var bool
101     */
102    public static $requires_plan = true;
103
104    /**
105     * The feature slug that identifies the paid plan
106     *
107     * @var string
108     */
109    public static $feature_identifying_paid_plan = 'backups';
110
111    /**
112     * Backup initialization
113     *
114     * @return void
115     */
116    public static function register_endpoints(): void {
117        parent::register_endpoints();
118        // Get backup undo event
119        register_rest_route(
120            'my-jetpack/v1',
121            '/site/backup/undo-event',
122            array(
123                'methods'             => \WP_REST_Server::READABLE,
124                'callback'            => __CLASS__ . '::get_site_backup_undo_event',
125                'permission_callback' => __CLASS__ . '::permissions_callback',
126            )
127        );
128    }
129
130    /**
131     * Get the product name
132     *
133     * @return string
134     */
135    public static function get_name() {
136        return 'VaultPress Backup';
137    }
138
139    /**
140     * Get the product title
141     *
142     * @return string
143     */
144    public static function get_title() {
145        return 'Jetpack VaultPress Backup';
146    }
147
148    /**
149     * Get the internationalized product description
150     *
151     * @return string
152     */
153    public static function get_description() {
154        return __( 'Real-time backups save every change, and one-click restores get you back online quickly.', 'jetpack-my-jetpack' );
155    }
156
157    /**
158     * Get the internationalized product long description
159     *
160     * @return string
161     */
162    public static function get_long_description() {
163        return __( 'Never lose a word, image, page, or time worrying about your site with automated backups & one-click restores.', 'jetpack-my-jetpack' );
164    }
165
166    /**
167     * Get the internationalized features list
168     *
169     * @return array Backup features list
170     */
171    public static function get_features() {
172        return array(
173            _x( 'Real-time cloud backups', 'Backup Product Feature', 'jetpack-my-jetpack' ),
174            _x( '10GB of backup storage', 'Backup Product Feature', 'jetpack-my-jetpack' ),
175            _x( '30-day archive & activity log*', 'Backup Product Feature', 'jetpack-my-jetpack' ),
176            _x( 'One-click restores', 'Backup Product Feature', 'jetpack-my-jetpack' ),
177        );
178    }
179
180    /**
181     * Get disclaimers corresponding to a feature
182     *
183     * @return array Backup disclaimers list
184     */
185    public static function get_disclaimers() {
186        return array(
187            array(
188                'text'      => _x( '* Subject to your usage and storage limit.', 'Backup Product Disclaimer', 'jetpack-my-jetpack' ),
189                'link_text' => _x( 'Learn more', 'Backup Product Disclaimer', 'jetpack-my-jetpack' ),
190                'url'       => Redirect::get_url( 'jetpack-faq-backup-disclaimer' ),
191            ),
192        );
193    }
194
195    /**
196     * Get the WPCOM product slug used to make the purchase
197     *
198     * @return ?string
199     */
200    public static function get_wpcom_product_slug() {
201        return 'jetpack_backup_t1_yearly';
202    }
203
204    /**
205     * Get the URL where the user should be redirected after checkout
206     */
207    public static function get_post_checkout_url() {
208        return self::get_manage_url();
209    }
210
211    /**
212     * Get the product princing details
213     *
214     * @return array Pricing details
215     */
216    public static function get_pricing_for_ui() {
217        return array_merge(
218            array(
219                'available'          => true,
220                'wpcom_product_slug' => static::get_wpcom_product_slug(),
221            ),
222            Wpcom_Products::get_product_pricing( static::get_wpcom_product_slug() )
223        );
224    }
225
226    /**
227     * Checks if the user has the correct permissions
228     */
229    public static function permissions_callback() {
230        return current_user_can( 'manage_options' );
231    }
232
233    /**
234     * This will fetch the last rewindable event from the Activity Log and
235     * the last rewind_id prior to that.
236     *
237     * @return array|WP_Error|null
238     */
239    public static function get_site_backup_undo_event() {
240        $blog_id       = \Jetpack_Options::get_option( 'id' );
241        $transient_key = self::UNDO_EVENT_TRANSIENT_PREFIX . (int) $blog_id . '-' . get_current_user_id();
242
243        $cached = get_transient( $transient_key );
244        if ( is_array( $cached ) ) {
245            return rest_ensure_response( $cached );
246        }
247
248        $response = Client::wpcom_json_api_request_as_user(
249            '/sites/' . $blog_id . '/activity/rewindable?force=wpcom',
250            'v2',
251            array(),
252            null,
253            'wpcom'
254        );
255
256        if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
257            return null;
258        }
259
260        $body = json_decode( $response['body'], true );
261
262        if ( ! isset( $body['current'] ) ) {
263            return null;
264        }
265
266        // Preparing the response structure
267        $undo_event = array(
268            'last_rewindable_event' => null,
269            'undo_backup_id'        => null,
270        );
271
272        // List of events that will not be considered to be undo.
273        // Basically we should not `undo` a full backup event, but we could
274        // use them to undo any other action like plugin updates.
275        $last_event_exceptions = array(
276            'rewind__backup_only_complete_full',
277            'rewind__backup_only_complete_initial',
278            'rewind__backup_only_complete',
279            'rewind__backup_complete_full',
280            'rewind__backup_complete_initial',
281            'rewind__backup_complete',
282        );
283
284        // Looping through the events to find the last rewindable event and the last backup_id.
285        // The idea is to find the last rewindable event and then the last rewind_id before that.
286        $found_last_event = false;
287        foreach ( $body['current']['orderedItems'] as $event ) {
288            if ( $event['is_rewindable'] ) {
289                if ( ! $found_last_event && ! in_array( $event['name'], $last_event_exceptions, true ) ) {
290                    $undo_event['last_rewindable_event'] = $event;
291                    $found_last_event                    = true;
292                } elseif ( $found_last_event ) {
293                    $undo_event['undo_backup_id'] = $event['rewind_id'];
294                    break;
295                }
296            }
297        }
298
299        set_transient( $transient_key, $undo_event, self::UNDO_EVENT_CACHE_DURATION );
300
301        return rest_ensure_response( $undo_event );
302    }
303
304    /**
305     * Hits the wpcom api to check rewind status.
306     *
307     * @todo Maybe add caching.
308     *
309     * @return object|WP_Error
310     */
311    private static function get_state_from_wpcom() {
312        static $status = null;
313
314        if ( $status !== null ) {
315            return $status;
316        }
317
318        $site_id = \Jetpack_Options::get_option( 'id' );
319
320        $response = Client::wpcom_json_api_request_as_blog(
321            sprintf( '/sites/%d/rewind', $site_id ) . '?force=wpcom',
322            '2',
323            array( 'timeout' => 2 ),
324            null,
325            'wpcom'
326        );
327
328        if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
329            $status = new WP_Error( 'rewind_state_fetch_failed' );
330            return $status;
331        }
332
333        $body   = wp_remote_retrieve_body( $response );
334        $status = json_decode( $body );
335        return $status;
336    }
337
338    /**
339     * Hits the wpcom api to retrieve the last 10 backup records.
340     *
341     * @return object|WP_Error
342     */
343    public static function get_latest_backups() {
344        static $backups = null;
345
346        if ( $backups !== null ) {
347            return $backups;
348        }
349
350        $site_id  = \Jetpack_Options::get_option( 'id' );
351        $response = Client::wpcom_json_api_request_as_blog(
352            sprintf( '/sites/%d/rewind/backups', $site_id ) . '?force=wpcom',
353            '2',
354            array( 'timeout' => 2 ),
355            null,
356            'wpcom'
357        );
358
359        if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
360            $backups = new WP_Error( 'rewind_backups_fetch_failed' );
361            return $backups;
362        }
363
364        $body    = wp_remote_retrieve_body( $response );
365        $backups = json_decode( $body );
366        return $backups;
367    }
368
369    /**
370     * Determines whether the module/plugin/product needs the users attention.
371     * Typically due to some sort of error where user troubleshooting is needed.
372     *
373     * @return boolean|array
374     */
375    public static function does_module_need_attention() {
376        $previous_backup_status = get_transient( self::BACKUP_STATUS_TRANSIENT_KEY );
377
378        // If we have a previous backup status, show it.
379        if ( ! empty( $previous_backup_status ) ) {
380            return $previous_backup_status === 'no_errors' ? false : $previous_backup_status;
381        }
382
383        $backup_failed_status = false;
384        // First check the status of Rewind for failure.
385        $rewind_state = self::get_state_from_wpcom();
386        if ( ! is_wp_error( $rewind_state ) ) {
387            // Special case: 'unavailable' with 'site_new' reason is a normal provisioning state for brand new sites.
388            $is_new_site_provisioning = ( 'unavailable' === $rewind_state->state &&
389                                        'site_new' === ( $rewind_state->reason ?? '' ) );
390
391            if (
392                ! in_array( $rewind_state->state, array( 'active', 'provisioning', 'awaiting_credentials' ), true ) &&
393                ! $is_new_site_provisioning
394            ) {
395                $backup_failed_status = array(
396                    'type' => 'error',
397                    'data' => array(
398                        'source'       => 'rewind',
399                        'status'       => isset( $rewind_state->reason ) && ! empty( $rewind_state->reason ) ? $rewind_state->reason : $rewind_state->state,
400                        'last_updated' => $rewind_state->last_updated,
401                    ),
402                );
403            }
404        }
405        // Next check for a failed last backup.
406        $latest_backups = self::get_latest_backups();
407        if ( ! is_wp_error( $latest_backups ) ) {
408            // Get the last/latest backup record.
409            $last_backup = null;
410            foreach ( $latest_backups as $backup ) {
411                if ( $backup->is_backup ) {
412                    $last_backup = $backup;
413                    break;
414                }
415            }
416
417            if ( $last_backup && isset( $last_backup->status ) ) {
418                if ( $last_backup->status !== 'started' && ! preg_match( '/-will-retry$/', $last_backup->status ) && $last_backup->status !== 'finished' ) {
419                    $backup_failed_status = array(
420                        'type' => 'error',
421                        'data' => array(
422                            'source'       => 'last_backup',
423                            'status'       => $last_backup->status,
424                            'last_updated' => $last_backup->last_updated,
425                        ),
426                    );
427                }
428            }
429        }
430
431        if ( is_array( $backup_failed_status ) ) {
432            set_transient( self::BACKUP_STATUS_TRANSIENT_KEY, $backup_failed_status, 5 * MINUTE_IN_SECONDS );
433        } else {
434            set_transient( self::BACKUP_STATUS_TRANSIENT_KEY, 'no_errors', HOUR_IN_SECONDS );
435        }
436
437        return $backup_failed_status;
438    }
439
440    /**
441     * Return product bundles list
442     * that supports the product.
443     *
444     * @return boolean|array Products bundle list.
445     */
446    public static function is_upgradable_by_bundle() {
447        return array( 'security', 'complete' );
448    }
449
450    /**
451     * Get the URL the user is taken after activating the product
452     *
453     * @return ?string
454     */
455    public static function get_post_activation_url() {
456        return ''; // stay in My Jetpack page or continue the purchase flow if needed.
457    }
458
459    /**
460     * Whether a plugin that can deliver Backup is on, which is all that matters where the plan decides Backup.
461     *
462     * @return bool
463     */
464    public static function is_module_active() {
465        if ( ! static::is_plan_driven() ) {
466            return parent::is_module_active();
467        }
468
469        return static::is_standalone_plugin_active() || static::is_jetpack_plugin_active();
470    }
471
472    /**
473     * Whether the site's plan, not the backup module, decides Backup here.
474     *
475     * An older Jetpack plugin still opens its dashboard only while the module is on.
476     *
477     * @since 6.13.0
478     *
479     * @return bool
480     */
481    public static function is_plan_driven() {
482        return static::is_standalone_plugin_active()
483            || ! class_exists( 'Jetpack', false )
484            || defined( 'Jetpack::BACKUP_FOLLOWS_PLAN' );
485    }
486
487    /**
488     * Get the URL where the user manages the product
489     *
490     * @return ?string
491     */
492    public static function get_manage_url() {
493        // check standalone first
494        if ( static::is_standalone_plugin_active() ) {
495            return admin_url( 'admin.php?page=jetpack-backup' );
496            // otherwise, check for the main Jetpack plugin
497        } elseif ( static::is_jetpack_plugin_active() ) {
498            // The Jetpack plugin hosts the dashboard wherever it initialized the package, or will on
499            // the next request when this one learned of the plan after Jetpack checked for it.
500            if ( did_action( 'jetpack_backup_initialized' ) || ( static::is_plan_driven() && static::plan_opens_jetpack_dashboard() ) ) {
501                return admin_url( 'admin.php?page=jetpack-backup' );
502            }
503
504            return Redirect::get_url( 'my-jetpack-manage-backup' );
505        }
506    }
507
508    /**
509     * Whether the Jetpack plugin offers its bundled Backup dashboard, which Jetpack::configure_backup_package() asks.
510     *
511     * @since 6.13.0
512     *
513     * @return bool
514     */
515    public static function offers_jetpack_dashboard() {
516        return static::jetpack_can_host_dashboard() && static::has_plan_on_record();
517    }
518
519    /**
520     * Whether the Jetpack plugin could host the dashboard here, whatever the plan.
521     *
522     * @return bool
523     */
524    private static function jetpack_can_host_dashboard() {
525        $connection = new Connection_Manager();
526
527        /** This filter is documented in projects/plugins/jetpack/class.jetpack.php */
528        $connected = apply_filters( 'jetpack_is_connection_ready', $connection->is_connected(), $connection );
529
530        // Not on multisite, which the Backup package does not support, or without a connected
531        // owner, since buying and managing backups needs a linked account.
532        if ( is_multisite() || ! $connected || ! $connection->has_connected_owner() ) {
533            return false;
534        }
535
536        /** This filter is documented in projects/plugins/jetpack/class.jetpack.php */
537        return (bool) apply_filters( 'jetpack_backup_dashboard_enabled', true );
538    }
539
540    /**
541     * Whether Manage opens the bundled dashboard, which is registered only once the stored plan includes Backup.
542     *
543     * @return bool
544     */
545    private static function plan_opens_jetpack_dashboard() {
546        if ( ! static::jetpack_can_host_dashboard() ) {
547            return false;
548        }
549
550        if ( static::has_plan_on_record() ) {
551            return true;
552        }
553
554        // Right after checkout WordPress.com knows of the plan before the stored copy does, so
555        // catch that up rather than link to a page the next request would not register.
556        if ( get_transient( self::PLAN_REFRESH_MISS_TRANSIENT_KEY ) || ! static::has_paid_plan_for_product() ) {
557            return false;
558        }
559
560        // Refresh directly: the shared reload may already be spent on another product this request.
561        Current_Plan::refresh_from_wpcom();
562
563        if ( static::has_plan_on_record() ) {
564            return true;
565        }
566
567        // The two can keep disagreeing, so a miss holds off the next refresh.
568        set_transient( self::PLAN_REFRESH_MISS_TRANSIENT_KEY, true, 5 * MINUTE_IN_SECONDS );
569
570        return false;
571    }
572
573    /**
574     * Get the product-slugs of the paid plans for this product.
575     * (Do not include bundle plans, unless it's a bundle plan itself).
576     *
577     * @return array
578     */
579    public static function get_paid_plan_product_slugs() {
580        return array(
581            'jetpack_backup_daily',
582            'jetpack_backup_daily_monthly',
583            'jetpack_backup_realtime',
584            'jetpack_backup_realtime_monthly',
585            'jetpack_backup_t1_yearly',
586            'jetpack_backup_t1_monthly',
587            'jetpack_backup_t1_bi_yearly',
588            'jetpack_backup_t2_yearly',
589            'jetpack_backup_t2_monthly',
590            'jetpack_backup_t0_yearly',
591            'jetpack_backup_t0_monthly',
592        );
593    }
594
595    /**
596     * Whether the site's stored plan or products include Backup, current or expired, without asking WordPress.com.
597     *
598     * @since 6.13.0
599     *
600     * @return bool
601     */
602    public static function has_plan_on_record() {
603        $feature = static::$feature_identifying_paid_plan;
604        $plan    = (array) get_option( Current_Plan::PLAN_OPTION, array() );
605
606        // The stored plan lists the features of every current purchase, standalone products included.
607        if ( in_array( $feature, (array) ( $plan['features']['active'] ?? array() ), true ) ) {
608            return true;
609        }
610
611        // An expired bundle stays the stored plan without listing its features, so match its family by slug.
612        $plan_slug = (string) ( $plan['product_slug'] ?? '' );
613        foreach ( array( 'jetpack_starter_', 'jetpack_security_', 'jetpack_complete', 'jetpack_pro_', 'jetpack_personal', 'jetpack_premium', 'jetpack_business' ) as $prefix ) {
614            if ( str_starts_with( $plan_slug, $prefix ) ) {
615                return true;
616            }
617        }
618
619        foreach ( (array) Current_Plan::get_products() as $product ) {
620            $slug = (string) ( ( (array) $product )['product_slug'] ?? '' );
621
622            foreach ( static::get_paid_plan_product_slugs() as $paid_slug ) {
623                if ( false !== strpos( $slug, $paid_slug ) ) {
624                    return true;
625                }
626            }
627        }
628
629        return false;
630    }
631
632    /**
633     * Override the product status to return INACTIVE when backups are deactivated.
634     *
635     * @return string
636     */
637    public static function get_status() {
638        // Get the default status from parent.
639        $status = parent::get_status();
640
641        // Check if backups are deactivated (not an error, just manually turned off).
642        $needs_attention = static::does_module_need_attention();
643        if (
644            is_array( $needs_attention ) &&
645            isset( $needs_attention['data']['status'] ) &&
646            'backups-deactivated' === $needs_attention['data']['status']
647        ) {
648            // Preserve NEEDS_PLAN status - user must purchase before reactivating.
649            if ( \Automattic\Jetpack\My_Jetpack\Products::STATUS_NEEDS_PLAN === $status ) {
650                return $status;
651            }
652
653            return \Automattic\Jetpack\My_Jetpack\Products::STATUS_INACTIVE;
654        }
655
656        return $status;
657    }
658}