Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
39.07% covered (danger)
39.07%
345 / 883
3.57% covered (danger)
3.57%
1 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 4
jetpack_do_after_gravatar_hovercards_activation
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
jetpack_do_after_gravatar_hovercards_deactivation
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Jetpack_Core_API_Module_Toggle_Endpoint
53.25% covered (warning)
53.25%
41 / 77
0.00% covered (danger)
0.00%
0 / 4
55.89
0.00% covered (danger)
0.00%
0 / 1
 process
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 activate_module
55.56% covered (warning)
55.56%
20 / 36
0.00% covered (danger)
0.00%
0 / 1
13.62
 deactivate_module
56.76% covered (warning)
56.76%
21 / 37
0.00% covered (danger)
0.00%
0 / 1
13.18
 can_request
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Jetpack_Core_API_Module_List_Endpoint
41.79% covered (danger)
41.79%
28 / 67
0.00% covered (danger)
0.00%
0 / 4
98.89
0.00% covered (danger)
0.00%
0 / 1
 process
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_modules
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
 activate_modules
56.00% covered (warning)
56.00%
28 / 50
0.00% covered (danger)
0.00%
0 / 1
21.31
 can_request
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
Jetpack_Core_API_Data
55.49% covered (warning)
55.49%
273 / 492
16.67% covered (danger)
16.67%
1 / 6
4608.78
0.00% covered (danger)
0.00%
0 / 1
 process
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 get_module
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
90
 get_all_options
84.78% covered (warning)
84.78%
39 / 46
0.00% covered (danger)
0.00%
0 / 1
22.55
 update_data
54.27% covered (warning)
54.27%
216 / 398
0.00% covered (danger)
0.00%
0 / 1
2801.00
 process_onboarding
n/a
0 / 0
n/a
0 / 0
1
 handle_business_address
n/a
0 / 0
n/a
0 / 0
12
 has_business_address_widget
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 can_request
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
Jetpack_Core_API_Module_Data_Endpoint
0.00% covered (danger)
0.00%
0 / 241
0.00% covered (danger)
0.00%
0 / 12
3906
0.00% covered (danger)
0.00%
0 / 1
 process
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
56
 key_check
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 get_protect_data
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 get_akismet_data
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 check_akismet_key
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
56
 akismet_class_exists
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 akismet_is_active_and_registered
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
 get_stats_data
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
42
 get_monitor_data
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
20
 get_verification_tools_data
0.00% covered (danger)
0.00%
0 / 63
0.00% covered (danger)
0.00%
0 / 1
210
 get_vaultpress_data
0.00% covered (danger)
0.00%
0 / 47
0.00% covered (danger)
0.00%
0 / 1
56
 can_request
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Tools to interact with Jetpack modules via API requests.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Connection\REST_Connector;
9use Automattic\Jetpack\Current_Plan as Jetpack_Plan;
10use Automattic\Jetpack\Sharing_Likes\Settings\Sharing_Options;
11use Automattic\Jetpack\Stats\WPCOM_Stats;
12use Automattic\Jetpack\Stats_Admin\Main as Stats_Admin_Main;
13use Automattic\Jetpack\Status;
14use Automattic\Jetpack\Waf\Brute_Force_Protection\Brute_Force_Protection;
15use Automattic\Jetpack\Waf\Brute_Force_Protection\Brute_Force_Protection_Shared_Functions;
16
17if ( ! defined( 'ABSPATH' ) ) {
18    exit( 0 );
19}
20
21/**
22 * This is the base class for every Core API endpoint Jetpack uses.
23 */
24class Jetpack_Core_API_Module_Toggle_Endpoint extends Jetpack_Core_API_XMLRPC_Consumer_Endpoint {
25
26    /**
27     * Check if the module requires the site to be publicly accessible from WPCOM.
28     * If the site meets this requirement, the module is activated. Otherwise an error is returned.
29     *
30     * @since 4.3.0
31     *
32     * @param WP_REST_Request $request {
33     *     Array of parameters received by request.
34     *
35     *     @type string $slug Module slug.
36     *     @type bool   $active should module be activated.
37     * }
38     *
39     * @return WP_REST_Response|WP_Error A REST response if the request was served successfully, otherwise an error.
40     */
41    public function process( $request ) {
42        if ( $request['active'] ) {
43            return $this->activate_module( $request );
44        } else {
45            return $this->deactivate_module( $request );
46        }
47    }
48
49    /**
50     * If it's a valid Jetpack module, activate it.
51     *
52     * @since 4.3.0
53     *
54     * @param string|WP_REST_Request $request It's a WP_REST_Request when called from endpoint /module/<slug>/*
55     *                                        and a string when called from Jetpack_Core_API_Data->update_data.
56     * {
57     *     Array of parameters received by request.
58     *
59     *     @type string $slug Module slug.
60     * }
61     *
62     * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
63     */
64    public function activate_module( $request ) {
65        $module_slug = '';
66
67        if (
68            (
69                is_array( $request )
70                || is_object( $request )
71            )
72            && isset( $request['slug'] )
73        ) {
74            $module_slug = $request['slug'];
75        } else {
76            $module_slug = $request;
77        }
78
79        if ( ! Jetpack::is_module( $module_slug ) ) {
80            return new WP_Error(
81                'not_found',
82                esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ),
83                array( 'status' => 404 )
84            );
85        }
86
87        if ( ! Jetpack_Plan::supports( $module_slug ) ) {
88            return new WP_Error(
89                'not_supported',
90                esc_html__( 'The requested Jetpack module is not supported by your plan.', 'jetpack' ),
91                array( 'status' => 424 )
92            );
93        }
94
95        if ( Jetpack::activate_module( $module_slug, false, false ) ) {
96            if ( ! Jetpack::is_module_active( $module_slug ) ) {
97                return new WP_Error(
98                    'module_forced',
99                    esc_html__( 'The requested Jetpack module is disabled by your host or site administrator, so it stays off.', 'jetpack' ),
100                    array( 'status' => 409 )
101                );
102            }
103
104            return rest_ensure_response(
105                array(
106                    'code'    => 'success',
107                    'message' => esc_html__( 'The requested Jetpack module was activated.', 'jetpack' ),
108                )
109            );
110        }
111
112        return new WP_Error(
113            'activation_failed',
114            esc_html__( 'The requested Jetpack module could not be activated.', 'jetpack' ),
115            array( 'status' => 424 )
116        );
117    }
118
119    /**
120     * If it's a valid Jetpack module, deactivate it.
121     *
122     * @since 4.3.0
123     *
124     * @param string|WP_REST_Request $request It's a WP_REST_Request when called from endpoint /module/<slug>/*
125     *                                        and a string when called from Jetpack_Core_API_Data->update_data.
126     * {
127     *     Array of parameters received by request.
128     *
129     *     @type string $slug Module slug.
130     * }
131     *
132     * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
133     */
134    public function deactivate_module( $request ) {
135        $module_slug = '';
136
137        if (
138            (
139                is_array( $request )
140                || is_object( $request )
141            )
142            && isset( $request['slug'] )
143        ) {
144            $module_slug = $request['slug'];
145        } else {
146            $module_slug = $request;
147        }
148
149        if ( ! Jetpack::is_module( $module_slug ) ) {
150            return new WP_Error(
151                'not_found',
152                esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ),
153                array( 'status' => 404 )
154            );
155        }
156
157        if ( ! Jetpack::is_module_active( $module_slug ) ) {
158            return new WP_Error(
159                'already_inactive',
160                esc_html__( 'The requested Jetpack module was already inactive.', 'jetpack' ),
161                array( 'status' => 409 )
162            );
163        }
164
165        $deactivated = Jetpack::deactivate_module( $module_slug );
166
167        // A module that was never saved as active leaves nothing to change, so check the outcome.
168        if ( Jetpack::is_module_active( $module_slug ) ) {
169            return new WP_Error(
170                'module_forced',
171                esc_html__( 'The requested Jetpack module is enabled by your host or site administrator, so it stays on.', 'jetpack' ),
172                array( 'status' => 409 )
173            );
174        }
175
176        if ( $deactivated ) {
177            return rest_ensure_response(
178                array(
179                    'code'    => 'success',
180                    'message' => esc_html( trim( __( 'The requested Jetpack module was deactivated.', 'jetpack' ) . ' ' . Jetpack::get_module_deactivation_note( $module_slug ) ) ),
181                )
182            );
183        }
184        return new WP_Error(
185            'deactivation_failed',
186            esc_html__( 'The requested Jetpack module could not be deactivated.', 'jetpack' ),
187            array( 'status' => 400 )
188        );
189    }
190
191    /**
192     * Check that the current user has permissions to manage Jetpack modules.
193     *
194     * @since 4.3.0
195     *
196     * @return bool
197     */
198    public function can_request() {
199        return current_user_can( 'jetpack_manage_modules' );
200    }
201}
202
203/**
204 * Interact with multiple modules at once (list or activate).
205 *
206 * // phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound
207 */
208class Jetpack_Core_API_Module_List_Endpoint {
209    // phpcs:enable Generic.Files.OneObjectStructurePerFile.MultipleFound
210
211    /**
212     * A WordPress REST API callback method that accepts a request object and decides what to do with it.
213     *
214     * @param WP_REST_Request $request The request sent to the WP REST API.
215     *
216     * @since 4.3.0
217     *
218     * @return bool|Array|WP_Error a resulting value or object, or an error.
219     */
220    public function process( $request ) {
221        if ( 'GET' === $request->get_method() ) {
222            return $this->get_modules();
223        } else {
224            return static::activate_modules( $request );
225        }
226    }
227
228    /**
229     * Get a list of all Jetpack modules and their information.
230     *
231     * @since 4.3.0
232     *
233     * @return array Array of Jetpack modules.
234     */
235    public function get_modules() {
236        require_once JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php';
237
238        $modules = Jetpack_Admin::init()->get_modules();
239        foreach ( $modules as $slug => $properties ) {
240            $modules[ $slug ]['options'] =
241                Jetpack_Core_Json_Api_Endpoints::prepare_options_for_response( $slug );
242            if (
243                isset( $modules[ $slug ]['requires_connection'] )
244                && $modules[ $slug ]['requires_connection']
245                && ( new Status() )->is_offline_mode()
246            ) {
247                $modules[ $slug ]['activated'] = false;
248            }
249        }
250
251        $modules = Jetpack::get_translated_modules( $modules );
252
253        return Jetpack_Core_Json_Api_Endpoints::prepare_modules_for_response( $modules );
254    }
255
256    /**
257     * Activate a list of valid Jetpack modules.
258     *
259     * @since 4.3.0
260     *
261     * @param WP_REST_Request $request {
262     *     Array of parameters received by request.
263     *
264     *     @type string $slug Module slug.
265     * }
266     *
267     * @return bool|WP_Error True if modules were activated. Otherwise, a WP_Error instance with the corresponding error.
268     */
269    public static function activate_modules( $request ) {
270
271        if (
272            ! isset( $request['modules'] )
273            || ! is_array( $request['modules'] )
274        ) {
275            return new WP_Error(
276                'not_found',
277                esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ),
278                array( 'status' => 404 )
279            );
280        }
281
282        $activated = array();
283        $failed    = array();
284
285        foreach ( $request['modules'] as $module ) {
286            if ( Jetpack::activate_module( $module, false, false ) && Jetpack::is_module_active( $module ) ) {
287                $activated[] = $module;
288            } else {
289                $failed[] = $module;
290            }
291        }
292
293        if ( empty( $failed ) ) {
294            return rest_ensure_response(
295                array(
296                    'code'    => 'success',
297                    'message' => esc_html__( 'All modules activated.', 'jetpack' ),
298                )
299            );
300        }
301
302        $error = '';
303
304        $activated_count = count( $activated );
305        if ( $activated_count > 0 ) {
306            $activated_last = array_pop( $activated );
307            $activated_text = $activated_count > 1 ? sprintf(
308                /* Translators: first variable is a list followed by the last item, which is the second variable. Example: dog, cat and bird. */
309                __( '%1$s and %2$s', 'jetpack' ),
310                implode( ', ', $activated ),
311                $activated_last
312            ) : $activated_last;
313
314            $error = sprintf(
315                /* Translators: the variable is a module name. */
316                _n( 'The module %s was activated.', 'The modules %s were activated.', $activated_count, 'jetpack' ),
317                $activated_text
318            ) . ' ';
319        }
320
321        $failed_count = count( $failed );
322        if ( count( $failed ) > 0 ) {
323            $failed_last = array_pop( $failed );
324            $failed_text = $failed_count > 1 ? sprintf(
325                /* Translators: first variable is a list followed by the last item, which is the second variable. Example: dog, cat and bird. */
326                __( '%1$s and %2$s', 'jetpack' ),
327                implode( ', ', $failed ),
328                $failed_last
329            ) : $failed_last;
330
331            $error = sprintf(
332                /* Translators: the variable is a module name. */
333                _n( 'The module %s failed to be activated.', 'The modules %s failed to be activated.', $failed_count, 'jetpack' ),
334                $failed_text
335            ) . ' ';
336        }
337
338        return new WP_Error(
339            'activation_failed',
340            esc_html( $error ),
341            array( 'status' => 424 )
342        );
343    }
344
345    /**
346     * A WordPress REST API permission callback method that accepts a request object and decides
347     * if the current user has enough privileges to act.
348     *
349     * @since 4.3.0
350     *
351     * @param WP_REST_Request $request The request sent to the WP REST API.
352     *
353     * @return bool does the current user have enough privilege.
354     */
355    public function can_request( $request ) {
356        if ( 'GET' === $request->get_method() ) {
357            return current_user_can( 'jetpack_admin_page' );
358        } else {
359            return current_user_can( 'jetpack_manage_modules' );
360        }
361    }
362}
363
364/**
365 * Class that manages updating of Jetpack module options and general Jetpack settings or retrieving module data.
366 * If no module is specified, all module settings are retrieved/updated.
367 *
368 * @since 4.3.0
369 * @since 4.4.0 Renamed Jetpack_Core_API_Module_Endpoint from to Jetpack_Core_API_Data.
370 *
371 * @author Automattic
372 *
373 * // phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound
374 */
375class Jetpack_Core_API_Data extends Jetpack_Core_API_XMLRPC_Consumer_Endpoint {
376    // phpcs:enable Generic.Files.OneObjectStructurePerFile.MultipleFound
377
378    /**
379     * Process request by returning the module or updating it.
380     * If no module is specified, settings for all modules are assumed.
381     *
382     * @since 4.3.0
383     *
384     * @param WP_REST_Request $request WP API request.
385     *
386     * @return bool|mixed|void|WP_Error
387     */
388    public function process( $request ) {
389        if ( 'GET' === $request->get_method() ) {
390            if ( isset( $request['slug'] ) ) {
391                return $this->get_module( $request );
392            }
393
394            return $this->get_all_options();
395        } else {
396            return $this->update_data( $request );
397        }
398    }
399
400    /**
401     * Get information about a specific and valid Jetpack module.
402     *
403     * @since 4.3.0
404     *
405     * @param WP_REST_Request $request {
406     *     Array of parameters received by request.
407     *
408     *     @type string $slug Module slug.
409     * }
410     *
411     * @return mixed|void|WP_Error
412     */
413    public function get_module( $request ) {
414        if ( Jetpack::is_module( $request['slug'] ) ) {
415
416            $module = Jetpack::get_module( $request['slug'] );
417
418            $module['options'] = Jetpack_Core_Json_Api_Endpoints::prepare_options_for_response( $request['slug'] );
419
420            if (
421                isset( $module['requires_connection'] )
422                && $module['requires_connection']
423                && ( new Status() )->is_offline_mode()
424            ) {
425                $module['activated'] = false;
426            }
427
428            $i18n = jetpack_get_module_i18n( $request['slug'] );
429            if ( $i18n ) {
430                if ( isset( $module['name'] ) ) {
431                    $module['name'] = $i18n['name'];
432                }
433                if ( isset( $module['description'] ) ) {
434                    $module['description']       = $i18n['description'];
435                    $module['short_description'] = $i18n['description'];
436                }
437            }
438            if ( isset( $module['module_tags'] ) ) {
439                $module['module_tags'] = array_map( 'jetpack_get_module_i18n_tag', $module['module_tags'] );
440            }
441
442            return Jetpack_Core_Json_Api_Endpoints::prepare_modules_for_response( $module );
443        }
444
445        return new WP_Error(
446            'not_found',
447            esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ),
448            array( 'status' => 404 )
449        );
450    }
451
452    /**
453     * Get information about all Jetpack module options and settings.
454     *
455     * @since 4.6.0
456     *
457     * @return WP_REST_Response $response
458     */
459    public function get_all_options() {
460        $response = array();
461
462        $modules = Jetpack::get_available_modules();
463        if ( is_array( $modules ) && ! empty( $modules ) ) {
464            foreach ( $modules as $module ) {
465                // Add all module options.
466                $options = Jetpack_Core_Json_Api_Endpoints::prepare_options_for_response( $module );
467                foreach ( $options as $option_name => $option ) {
468                    $response[ $option_name ] = $option['current_value'];
469                }
470
471                // Add the module activation state.
472                $response[ $module ] = Jetpack::is_module_active( $module );
473            }
474        }
475
476        $settings = Jetpack_Core_Json_Api_Endpoints::filter_options_for_response(
477            Jetpack_Core_Json_Api_Endpoints::get_updateable_data_list( 'settings' )
478        );
479
480        if ( ! function_exists( 'is_plugin_active' ) ) {
481            require_once ABSPATH . 'wp-admin/includes/plugin.php';
482        }
483
484        $response['categories'] = get_categories( array( 'get' => 'all' ) );
485
486        foreach ( $settings as $setting => $properties ) {
487            switch ( $setting ) {
488                case 'lang_id':
489                    if ( ! current_user_can( 'install_languages' ) ) {
490                        // The user doesn't have caps to install language packs, so warn the client.
491                        $response[ $setting ] = 'error_cap';
492                        break;
493                    }
494
495                    $value = get_option( 'WPLANG', '' );
496                    if ( empty( $value ) && defined( 'WPLANG' ) ) {
497                        $value = WPLANG;
498                    }
499                    $response[ $setting ] = empty( $value ) ? 'en_US' : $value;
500                    break;
501
502                case 'wordpress_api_key':
503                    // When field is clear, return empty. Otherwise it would return "false".
504                    if ( '' === get_option( 'wordpress_api_key', '' ) ) {
505                        $response[ $setting ] = '';
506                    } else {
507                        if ( ! class_exists( 'Akismet' ) ) {
508                            if ( is_readable( WP_PLUGIN_DIR . '/akismet/class.akismet.php' ) ) {
509                                require_once WP_PLUGIN_DIR . '/akismet/class.akismet.php';
510                            }
511                        }
512                        $response[ $setting ] = class_exists( 'Akismet' ) ? Akismet::get_api_key() : '';
513                    }
514                    break;
515
516                case 'search_auto_config':
517                    // Only writable.
518                    $response[ $setting ] = 1;
519                    break;
520
521                default:
522                    $default              = $settings[ $setting ]['default'] ?? false;
523                    $response[ $setting ] = Jetpack_Core_Json_Api_Endpoints::cast_value( get_option( $setting, $default ), $settings[ $setting ] );
524                    break;
525            }
526        }
527
528        $response['akismet'] = is_plugin_active( 'akismet/akismet.php' );
529
530        require_once JETPACK__PLUGIN_DIR . '/modules/memberships/class-jetpack-memberships.php';
531        if ( class_exists( 'Jetpack_Memberships' ) ) {
532            $response['newsletter_has_active_plan'] = count( Jetpack_Memberships::get_all_newsletter_plan_ids( false ) ) > 0;
533        }
534
535        // Make sure we are returning a consistent type
536        if ( ! class_exists( 'Jetpack_Newsletter_Category_Helper' ) ) {
537            require_once JETPACK__PLUGIN_DIR . '_inc/lib/class-jetpack-newsletter-category-helper.php';
538        }
539        $response['wpcom_newsletter_categories'] = Jetpack_Newsletter_Category_Helper::get_category_ids();
540
541        return rest_ensure_response( $response );
542    }
543
544    /**
545     * If it's a valid Jetpack module and configuration parameters have been sent, update it.
546     *
547     * @since 4.3.0
548     *
549     * @param WP_REST_Request $request {
550     *     Array of parameters received by request.
551     *
552     *     @type string $slug Module slug.
553     * }
554     *
555     * @return bool|WP_REST_Response|WP_Error True or a WP_REST_Response if module was updated. Otherwise, a WP_Error instance with the corresponding error.
556     */
557    public function update_data( $request ) {
558
559        // If it's null, we're trying to update many module options from different modules.
560        if ( $request['slug'] === null ) {
561
562            // Value admitted by Jetpack_Core_Json_Api_Endpoints::get_updateable_data_list that will make it return all module options.
563            // It will not be passed. It's just checked in this method to pass that method a string or array.
564            $request['slug'] = 'any';
565        } else {
566            if ( ! Jetpack::is_module( $request['slug'] ) ) {
567                return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
568            }
569
570            if ( ! Jetpack::is_module_active( $request['slug'] ) ) {
571                return new WP_Error( 'inactive', esc_html__( 'The requested Jetpack module is inactive.', 'jetpack' ), array( 'status' => 409 ) );
572            }
573        }
574
575        /*
576         * Get parameters to update the module.
577         * We cannot simply use $request->get_params() because when we registered this route,
578         * we are adding the entire output of Jetpack_Core_Json_Api_Endpoints::get_updateable_data_list()
579         * to the current request object's params. We are interested in body of the actual request.
580         * This may be JSON:
581         */
582        $params = $request->get_json_params();
583        if ( ! is_array( $params ) ) {
584            // Or it may be standard POST key-value pairs.
585            $params = $request->get_body_params();
586        }
587
588        // Exit if no parameters were passed.
589        if ( ! is_array( $params ) ) {
590            return new WP_Error( 'missing_options', esc_html__( 'Missing options.', 'jetpack' ), array( 'status' => 404 ) );
591        }
592
593        // If $params was set via `get_body_params()` there may be some additional variables in the request that can
594        // cause validation to fail. This method verifies that each param was in fact updated and will throw a `some_updated`
595        // error if unused variables are included in the request.
596        foreach ( array_keys( $params ) as $key ) {
597            if ( is_int( $key ) || 'slug' === $key || 'context' === $key ) {
598                unset( $params[ $key ] );
599            }
600        }
601
602        // Get available module options.
603        $options = Jetpack_Core_Json_Api_Endpoints::get_updateable_data_list(
604            'any' === $request['slug']
605            ? $params
606            : $request['slug']
607        );
608
609        // Prepare to toggle module if needed.
610        $toggle_module = new Jetpack_Core_API_Module_Toggle_Endpoint( new Jetpack_IXR_Client() );
611
612        // Options that are invalid or failed to update.
613        $invalid     = array_keys( array_diff_key( $params, $options ) );
614        $not_updated = array();
615
616        // Remove invalid options.
617        $params = array_intersect_key( $params, $options );
618
619        // Used if response is successful. The message can be overwritten and additional data can be added here.
620        $response = array(
621            'code'    => 'success',
622            'message' => esc_html__( 'The requested Jetpack data updates were successful.', 'jetpack' ),
623        );
624
625        // If there are modules to activate, activate them first so they're ready when their options are set.
626        foreach ( $params as $option => $value ) {
627            if ( 'modules' === $options[ $option ]['jp_group'] ) {
628
629                // Used if there was an error. Can be overwritten with specific error messages.
630                $error = '';
631
632                // Set to true if the module toggling was successful.
633                $updated = false;
634
635                // Check if user can toggle the module.
636                if ( $toggle_module->can_request() ) {
637
638                    // Activate or deactivate the module according to the value passed.
639                    $toggle_result = $value
640                        ? $toggle_module->activate_module( $option )
641                        : $toggle_module->deactivate_module( $option );
642
643                    if (
644                        is_wp_error( $toggle_result )
645                        && 'already_inactive' === $toggle_result->get_error_code()
646                    ) {
647
648                        // If the module is already inactive, we don't fail.
649                        $updated = true;
650                    } elseif ( is_wp_error( $toggle_result ) ) {
651                        $error = $toggle_result->get_error_message();
652                    } else {
653                        $updated = true;
654                    }
655                } else {
656                    $error = REST_Connector::get_user_permissions_error_msg();
657                }
658
659                // The module was not toggled.
660                if ( ! $updated ) {
661                    $not_updated[ $option ] = $error;
662                }
663
664                if ( $updated ) {
665                    // Return the module state.
666                    $response[ $option ] = $value;
667                }
668
669                // Remove module from list so we don't go through it again.
670                unset( $params[ $option ] );
671            }
672        }
673
674        if ( ! class_exists( 'Jetpack_Newsletter_Category_Helper' ) ) {
675            require_once JETPACK__PLUGIN_DIR . '_inc/lib/class-jetpack-newsletter-category-helper.php';
676        }
677
678        foreach ( $params as $option => $value ) {
679
680            // Used if there was an error. Can be overwritten with specific error messages.
681            $error = '';
682
683            // Set to true if the option update was successful.
684            $updated = false;
685
686            // Get option attributes, including the group it belongs to.
687            $option_attrs = $options[ $option ];
688
689            // Everything outside the Post by Email group requires the admin capability.
690            if ( 'post-by-email' !== $option_attrs['jp_group'] && ! current_user_can( 'jetpack_configure_modules' ) ) {
691                $not_updated[ $option ] = REST_Connector::get_user_permissions_error_msg();
692                continue;
693            }
694
695            // If this is a module option and the related module isn't active for any reason, continue with the next one.
696            if ( 'settings' !== $option_attrs['jp_group'] ) {
697                if ( ! Jetpack::is_module( $option_attrs['jp_group'] ) ) {
698                    $not_updated[ $option ] = esc_html__( 'The requested Jetpack module was not found.', 'jetpack' );
699                    continue;
700                }
701
702                if (
703                    'any' !== $request['slug']
704                    && ! Jetpack::is_module_active( $option_attrs['jp_group'] )
705                ) {
706
707                    // We only take note of skipped options when updating one module.
708                    $not_updated[ $option ] = esc_html__( 'The requested Jetpack module is inactive.', 'jetpack' );
709                    continue;
710                }
711            }
712
713            // Properly cast value based on its type defined in endpoint accepted args.
714            $value = Jetpack_Core_Json_Api_Endpoints::cast_value( $value, $option_attrs );
715
716            switch ( $option ) {
717                case 'lang_id':
718                    if ( ! current_user_can( 'install_languages' ) ) {
719                        // We can't affect this setting.
720                        $updated = false;
721                        break;
722                    }
723
724                    if ( 'en_US' === $value || empty( $value ) ) {
725                        delete_option( 'WPLANG' );
726                        $updated = '' === get_option( 'WPLANG', '' );
727                        break;
728                    }
729
730                    if ( ! function_exists( 'request_filesystem_credentials' ) ) {
731                        require_once ABSPATH . 'wp-admin/includes/file.php';
732                    }
733
734                    if ( ! function_exists( 'wp_download_language_pack' ) ) {
735                        require_once ABSPATH . 'wp-admin/includes/translation-install.php';
736                    }
737
738                    // `wp_download_language_pack` only tries to download packs if they're not already available.
739                    $language = wp_download_language_pack( $value );
740                    if ( false === $language ) {
741                        // The language pack download failed.
742                        $updated = false;
743                        break;
744                    }
745                    $updated = get_option( 'WPLANG' ) === $language ? true : update_option( 'WPLANG', $language );
746                    break;
747
748                case 'monitor_receive_notifications':
749                    if ( ! class_exists( 'Jetpack_Monitor' ) ) {
750                        $updated = false;
751                        break;
752                    }
753
754                    $monitor = new Jetpack_Monitor();
755
756                    // If we got true as response, consider it done.
757                    $updated = true === $monitor->update_option_receive_jetpack_monitor_notification( $value );
758                    break;
759
760                case 'post_by_email_address':
761                    if ( ! class_exists( 'Jetpack_Post_By_Email' ) ) {
762                        $updated = false;
763                        break;
764                    }
765
766                    $result = Jetpack_Post_By_Email::init()->process_api_request( $value );
767
768                    // If we got an email address (create or regenerate) or 1 (delete), consider it done.
769                    if ( is_string( $result ) && preg_match( '/[a-z0-9]+@post.wordpress.com/', $result ) ) {
770                        $response[ $option ] = $result;
771                        $updated             = true;
772                    } elseif ( 1 == $result ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
773                        $updated = true;
774                    } elseif ( is_array( $result ) && isset( $result['message'] ) ) {
775                        $error = $result['message'];
776                    }
777                    break;
778
779                case 'jetpack_protect_key':
780                    $brute_force_protection = Brute_Force_Protection::instance();
781                    if ( 'create' === $value ) {
782                        $result = $brute_force_protection->get_protect_key();
783                    } else {
784                        $result = false;
785                    }
786
787                    // If we got one of Protect keys, consider it done.
788                    if ( is_string( $result ) && preg_match( '/[a-z0-9]{40,}/i', $result ) ) {
789                        $response[ $option ] = $result;
790                        $updated             = true;
791                    }
792                    break;
793
794                case 'jetpack_protect_global_whitelist':
795                    _deprecated_argument( 'jetpack/v4/settings', 'jetpack-16.5', esc_html__( 'The jetpack_protect_global_whitelist setting is deprecated. Use jetpack_waf_ip_allow_list instead.', 'jetpack' ) );
796                    $updated = Brute_Force_Protection_Shared_Functions::save_allow_list( explode( PHP_EOL, str_replace( array( ' ', ',' ), array( '', "\n" ), $value ) ) );
797
798                    if ( is_wp_error( $updated ) ) {
799                        $error   = $updated->get_error_message();
800                        $updated = false;
801                    }
802                    break;
803
804                case 'show_headline':
805                case 'show_thumbnails':
806                    $grouped_options_current    = (array) Jetpack_Options::get_option( 'relatedposts' );
807                    $grouped_options            = $grouped_options_current;
808                    $grouped_options[ $option ] = $value;
809
810                    // If option value was the same, consider it done.
811                    $updated = $grouped_options_current !== $grouped_options ? Jetpack_Options::update_option( 'relatedposts', $grouped_options ) : true;
812                    break;
813
814                case 'search_auto_config':
815                    if ( ! $value ) {
816                        // Skip execution if no value is specified.
817                        $updated = true;
818                    } else {
819                        $plan = new Automattic\Jetpack\Search\Plan();
820                        if ( ! $plan->supports_instant_search() ) {
821                            $updated = new WP_Error( 'instant_search_not_supported', 'Instant Search is not supported by this site', array( 'status' => 400 ) );
822                            $error   = $updated->get_error_message();
823                        } elseif ( ! Automattic\Jetpack\Search\Options::is_instant_enabled() ) {
824                            $updated = new WP_Error( 'instant_search_disabled', 'Instant Search is disabled', array( 'status' => 400 ) );
825                            $error   = $updated->get_error_message();
826                        } else {
827                            $blog_id  = Automattic\Jetpack\Search\Helper::get_wpcom_site_id();
828                            $instance = Automattic\Jetpack\Search\Instant_Search::instance( $blog_id );
829                            $instance->auto_config_search();
830                            $updated = true;
831                        }
832                    }
833                    break;
834
835                case 'google':
836                case 'bing':
837                case 'pinterest':
838                case 'yandex':
839                case 'facebook':
840                    $grouped_options_current = (array) get_option( 'verification_services_codes' );
841                    $grouped_options         = $grouped_options_current;
842
843                    $validated_code = jetpack_verification_validate_code( $value );
844                    if ( false === $validated_code ) {
845                        $error = esc_html__( 'The site verification code is invalid.', 'jetpack' );
846                        break;
847                    }
848
849                    $grouped_options[ $option ] = $validated_code;
850
851                    // If option value was the same, consider it done.
852                    $updated = $grouped_options_current !== $grouped_options
853                        ? update_option( 'verification_services_codes', $grouped_options )
854                        : true;
855                    break;
856
857                case Jetpack_SEO_Utils::FRONT_PAGE_META_OPTION:
858                    Jetpack_SEO_Utils::update_front_page_meta_description( $value );
859                    $response[ $option ] = Jetpack_SEO_Utils::get_front_page_meta_description();
860                    // The helper returns an empty string for a successful clear or
861                    // same-value write, so use its authoritative getter for the response
862                    // and treat every valid request reaching this switch as handled.
863                    $updated = true;
864                    break;
865
866                case 'sharing_services':
867                    if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
868                        break;
869                    }
870
871                    $sharer = new Sharing_Service();
872
873                    // If option value was the same, consider it done.
874                    $updated = $value !== $sharer->get_blog_services()
875                        ? $sharer->set_blog_services( $value['visible'], $value['hidden'] )
876                        : true;
877                    break;
878
879                case 'button_style':
880                case 'sharing_label':
881                case 'show':
882                    if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
883                        break;
884                    }
885
886                    if ( method_exists( Sharing_Options::class, 'update' ) ) {
887                        $updated = Sharing_Options::update( array( $option => 'sharing_label' === $option ? wp_slash( $value ) : $value ) );
888                        break;
889                    }
890
891                    $sharer                     = new Sharing_Service();
892                    $grouped_options            = $sharer->get_global_options();
893                    $grouped_options[ $option ] = $value;
894                    $updated                    = $sharer->set_global_options( $grouped_options );
895                    break;
896
897                case 'custom':
898                    if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
899                        break;
900                    }
901
902                    $sharer  = new Sharing_Service();
903                    $updated = $sharer->new_service( stripslashes( $value['sharing_name'] ), stripslashes( $value['sharing_url'] ), stripslashes( $value['sharing_icon'] ) );
904
905                    // Return new custom service.
906                    $response[ $option ] = $updated;
907                    break;
908
909                case 'sharing_delete_service':
910                    if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
911                        break;
912                    }
913
914                    $sharer  = new Sharing_Service();
915                    $updated = $sharer->delete_service( $value );
916                    break;
917
918                case 'jetpack-twitter-cards-site-tag':
919                    $value   = trim( ltrim( wp_strip_all_tags( $value ), '@' ) );
920                    $updated = get_option( $option ) !== $value ? update_option( $option, $value ) : true;
921                    break;
922
923                case 'admin_bar':
924                case 'roles':
925                case 'count_roles':
926                case 'blog_id':
927                case 'do_not_track':
928                case 'version':
929                case 'collapse_nudges':
930                    $grouped_options_current    = (array) get_option( 'stats_options' );
931                    $grouped_options            = $grouped_options_current;
932                    $grouped_options[ $option ] = $value;
933
934                    // If option value was the same, consider it done.
935                    $updated = $grouped_options_current !== $grouped_options
936                        ? update_option( 'stats_options', $grouped_options )
937                        : true;
938                    break;
939
940                case 'enable_odyssey_stats':
941                    $updated = Stats_Admin_Main::update_new_stats_status( $value );
942
943                    break;
944
945                case 'akismet_show_user_comments_approved':
946                    // Save Akismet option '1' or '0' like it's done in akismet/class.akismet-admin.php.
947                    $updated = get_option( $option ) != $value // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual
948                        ? update_option( $option, $value ? '1' : '0' )
949                        : true;
950                    break;
951
952                case 'wordpress_api_key':
953                    if ( ! file_exists( WP_PLUGIN_DIR . '/akismet/class.akismet.php' ) ) {
954                        $error   = esc_html__( 'Please install Akismet.', 'jetpack' );
955                        $updated = false;
956                        break;
957                    }
958
959                    if ( ! defined( 'AKISMET_VERSION' ) ) {
960                        $error   = esc_html__( 'Please activate Akismet.', 'jetpack' );
961                        $updated = false;
962                        break;
963                    }
964
965                    // Allow to clear the API key field.
966                    if ( '' === $value ) {
967                        $updated = get_option( $option ) !== $value
968                            ? update_option( $option, $value )
969                            : true;
970                        break;
971                    }
972
973                    require_once WP_PLUGIN_DIR . '/akismet/class.akismet.php';
974                    require_once WP_PLUGIN_DIR . '/akismet/class.akismet-admin.php';
975
976                    if ( class_exists( 'Akismet_Admin' ) && method_exists( 'Akismet_Admin', 'save_key' ) ) {
977                        if ( Akismet::verify_key( $value ) === 'valid' ) {
978                            $akismet_user = Akismet_Admin::get_akismet_user( $value );
979                            if ( $akismet_user ) {
980                                if ( in_array( $akismet_user->status, array( 'active', 'active-dunning', 'no-sub' ), true ) ) {
981                                    $updated = get_option( $option ) !== $value
982                                        ? update_option( $option, $value )
983                                        : true;
984                                    break;
985                                } else {
986                                    $error = esc_html__( "Akismet user status doesn't allow to update the key", 'jetpack' );
987                                }
988                            } else {
989                                $error = esc_html__( 'Invalid Akismet user', 'jetpack' );
990                            }
991                        } else {
992                            $error = esc_html__( 'Invalid Akismet key', 'jetpack' );
993                        }
994                    } else {
995                        $error = esc_html__( 'Akismet is not installed or active', 'jetpack' );
996                    }
997                    $updated = false;
998                    break;
999
1000                case 'google_analytics_tracking_id':
1001                    $grouped_options_current = (array) get_option( 'jetpack_wga' );
1002                    $grouped_options         = $grouped_options_current;
1003                    $grouped_options['code'] = $value;
1004
1005                    // If option value was the same, consider it done.
1006                    $updated = $grouped_options_current !== $grouped_options
1007                        ? update_option( 'jetpack_wga', $grouped_options )
1008                        : true;
1009                    break;
1010
1011                case 'dismiss_empty_stats_card':
1012                case 'dismiss_dash_backup_getting_started':
1013                case 'dismiss_dash_agencies_learn_more':
1014                    // If option value was the same, consider it done.
1015                    $updated = get_option( $option ) != $value // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual -- ensure we support bools or strings saved by update_option.
1016                        ? update_option( $option, (bool) $value )
1017                        : true;
1018                    break;
1019
1020                case 'jetpack_subscriptions_reply_to':
1021                    // If option value was the same, consider it done.
1022                    require_once JETPACK__PLUGIN_DIR . 'modules/subscriptions/class-settings.php';
1023                    $sub_value = Automattic\Jetpack\Modules\Subscriptions\Settings::is_valid_reply_to( $value )
1024                        ? $value
1025                        : Automattic\Jetpack\Modules\Subscriptions\Settings::$default_reply_to;
1026
1027                        $updated = (string) get_option( $option ) !== (string) $sub_value ? update_option( $option, $sub_value ) : true;
1028                    break;
1029                case 'jetpack_subscriptions_from_name':
1030                    // If option value was the same, consider it done.
1031                    $sub_value = sanitize_text_field( $value );
1032                    $updated   = (string) get_option( $option ) !== (string) $sub_value ? update_option( $option, $sub_value ) : true;
1033                    break;
1034
1035                case 'stb_enabled':
1036                case 'stc_enabled':
1037                case 'sm_enabled':
1038                case 'jetpack_subscribe_overlay_enabled':
1039                case 'jetpack_subscribe_floating_button_enabled':
1040                case 'wpcom_newsletter_categories_enabled':
1041                case 'wpcom_featured_image_in_email':
1042                case 'jetpack_gravatar_in_email':
1043                case 'jetpack_author_in_email':
1044                case 'jetpack_post_date_in_email':
1045                case 'wpcom_subscription_emails_use_excerpt':
1046                case 'jetpack_subscriptions_subscribe_post_end_enabled':
1047                case 'jetpack_subscriptions_login_navigation_enabled':
1048                case 'jetpack_subscriptions_subscribe_navigation_enabled':
1049                    // Convert the false value to 0. This allows the option to be updated if it doesn't exist yet.
1050                    $sub_value = $value ? $value : 0;
1051                    $updated   = (string) get_option( $option ) !== (string) $sub_value ? update_option( $option, $sub_value ) : true;
1052                    break;
1053
1054                case 'jetpack_blocks_disabled':
1055                    $updated = (bool) get_option( $option ) !== (bool) $value ? update_option( $option, (bool) $value ) : true;
1056                    break;
1057
1058                case 'subscription_options':
1059                    if ( ! is_array( $value ) ) {
1060                        break;
1061                    }
1062
1063                    $allowed_keys   = array( 'invitation', 'comment_follow', 'welcome', 'subscribe_modal_heading', 'free_tier_description', 'hide_free_tier' );
1064                    $filtered_value = array_filter(
1065                        $value,
1066                        function ( $key ) use ( $allowed_keys ) {
1067                            return in_array( $key, $allowed_keys, true );
1068                        },
1069                        ARRAY_FILTER_USE_KEY
1070                    );
1071
1072                    if ( empty( $filtered_value ) ) {
1073                        break;
1074                    }
1075
1076                    // `hide_free_tier` is a boolean flag, so pull it out before the HTML
1077                    // sanitization below (which expects strings). Sanitize it with
1078                    // rest_sanitize_boolean() so stringy booleans (e.g. "false", "0")
1079                    // are interpreted correctly rather than being treated as truthy by a
1080                    // plain `! empty()`.
1081                    $has_hide_free_tier = array_key_exists( 'hide_free_tier', $filtered_value );
1082                    $hide_free_tier     = $has_hide_free_tier && rest_sanitize_boolean( $filtered_value['hide_free_tier'] );
1083                    unset( $filtered_value['hide_free_tier'] );
1084
1085                    array_walk_recursive(
1086                        $filtered_value,
1087                        function ( &$value ) {
1088                            $value = wp_kses(
1089                                $value,
1090                                array(
1091                                    'ul'     => array(),
1092                                    'li'     => array(),
1093                                    'p'      => array(),
1094                                    'strong' => array(),
1095                                    'ol'     => array(),
1096                                    'em'     => array(),
1097                                    'a'      => array(
1098                                        'href' => array(),
1099                                    ),
1100                                )
1101                            );
1102                        }
1103                    );
1104
1105                    // Normalize whitespace-only `subscribe_modal_heading` input to empty so
1106                    // the modal template's `empty()` fallback fires. PHP's `empty()` treats
1107                    // `"   "` as non-empty, which would otherwise render a blank heading.
1108                    if ( isset( $filtered_value['subscribe_modal_heading'] ) ) {
1109                        $filtered_value['subscribe_modal_heading'] = trim( $filtered_value['subscribe_modal_heading'] );
1110                    }
1111
1112                    // The free tier description is stored as plain markdown source, so strip
1113                    // all HTML and cap its length to match the paid-tier description field.
1114                    // WordPress core guarantees mb_substr() (polyfilled in wp-includes/compat.php
1115                    // when the mbstring extension is unavailable), so it's safe to use directly.
1116                    // A JSON payload could supply a non-scalar (array/object) for this field,
1117                    // which would fatal in wp_kses()/mb_substr() on PHP 8+, so drop invalid values.
1118                    if ( isset( $filtered_value['free_tier_description'] ) ) {
1119                        if ( is_scalar( $filtered_value['free_tier_description'] ) ) {
1120                            $filtered_value['free_tier_description'] = mb_substr( wp_kses( (string) $filtered_value['free_tier_description'], array() ), 0, 500 );
1121                        } else {
1122                            unset( $filtered_value['free_tier_description'] );
1123                        }
1124                    }
1125
1126                    if ( $has_hide_free_tier ) {
1127                        $filtered_value['hide_free_tier'] = $hide_free_tier;
1128                    }
1129
1130                    $old_subscription_options = get_option( 'subscription_options' );
1131                    if ( ! is_array( $old_subscription_options ) ) {
1132                        $old_subscription_options = array();
1133                    }
1134                    $new_subscription_options = array_merge( $old_subscription_options, $filtered_value );
1135                    $updated                  = true;
1136
1137                    if ( serialize( $old_subscription_options ) === serialize( $new_subscription_options ) ) { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
1138                        break; // This prevents the option update to fail when the values are the same.
1139                    }
1140
1141                    if ( ! update_option( $option, $new_subscription_options ) ) {
1142                        $updated = false;
1143                        $error   = esc_html__( 'Subscription Options failed to process.', 'jetpack' );
1144                    }
1145                    break;
1146
1147                case Jetpack_Newsletter_Category_Helper::NEWSLETTER_CATEGORIES_OPTION:
1148                    if ( ! is_array( $value ) || empty( $value ) ) {
1149                        $updated = true;
1150                        break;
1151                    }
1152
1153                    // If we are already current, do nothing
1154                    $current_value = Jetpack_Newsletter_Category_Helper::get_category_ids();
1155                    if ( $value === $current_value ) {
1156                        $updated = true;
1157                        break;
1158                    }
1159
1160                    if ( Jetpack_Newsletter_Category_Helper::save_category_ids( $value ) ) {
1161                        $updated = true;
1162                    } else {
1163                        $updated = false;
1164                        $error   = esc_html__( 'Newsletter category did not update.', 'jetpack' );
1165                    }
1166
1167                    break;
1168
1169                default:
1170                    // Boolean values are stored as 1 or 0.
1171                    if ( isset( $options[ $option ]['type'] ) && 'boolean' === $options[ $option ]['type'] ) {
1172                        $value = (int) $value;
1173                    }
1174
1175                    // If option value was the same as it's current value, or it's default, consider it done.
1176                    $default = $options[ $option ]['default'] ?? false;
1177                    $updated = get_option( $option, $default ) != $value // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual -- ensure we support scalars or strings saved by update_option.
1178                        ? update_option( $option, $value )
1179                        : true;
1180                    break;
1181            }
1182
1183            // The option was not updated.
1184            if ( ! $updated ) {
1185                $not_updated[ $option ] = $error;
1186            }
1187        }
1188
1189        if ( empty( $invalid ) && empty( $not_updated ) ) {
1190            // The option was updated.
1191            return rest_ensure_response( $response );
1192        } else {
1193            $invalid_count     = count( $invalid );
1194            $not_updated_count = count( $not_updated );
1195            $error             = '';
1196            if ( $invalid_count > 0 ) {
1197                $error = sprintf(
1198                /* Translators: the plural variable is a comma-separated list. Example: dog, cat, bird. */
1199                    _n( 'Invalid option: %s.', 'Invalid options: %s.', $invalid_count, 'jetpack' ),
1200                    implode( ', ', $invalid )
1201                );
1202            }
1203            if ( $not_updated_count > 0 ) {
1204                $not_updated_messages = array();
1205                foreach ( $not_updated as $not_updated_option => $not_updated_message ) {
1206                    if ( ! empty( $not_updated_message ) ) {
1207                        $not_updated_messages[] = sprintf(
1208                            /* Translators: the first variable is a module option or slug, or setting. The second is the error message . */
1209                            __( '%1$s: %2$s', 'jetpack' ),
1210                            $not_updated_option,
1211                            $not_updated_message
1212                        );
1213                    }
1214                }
1215                if ( ! empty( $error ) ) {
1216                    $error .= ' ';
1217                }
1218                if ( ! empty( $not_updated_messages ) ) {
1219                    $error .= ' ' . implode( '. ', $not_updated_messages );
1220                }
1221            }
1222            // There was an error because some options were updated but others were invalid or failed to update.
1223            return new WP_Error( 'some_updated', esc_html( $error ), array( 'status' => 400 ) );
1224        }
1225    }
1226
1227    /**
1228     * Perform tasks in the site based on onboarding choices.
1229     *
1230     * @since 5.4.0
1231     *
1232     * @deprecated since 13.9
1233     *
1234     * @param array $data Onboarding choices made by user.
1235     *
1236     * @return string Result of onboarding processing and, if there is one, an error message.
1237     */
1238    private function process_onboarding( $data ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1239        _deprecated_function( __METHOD__, '13.9' );
1240        return '';
1241    }
1242
1243    /**
1244     * Add or update Business Address widget.
1245     *
1246     * @deprecated since 13.9
1247     *
1248     * @param array $address Array of business address fields.
1249     *
1250     * @return WP_Error|true True if the data was saved correctly.
1251     */
1252    private static function handle_business_address( $address ) {
1253        _deprecated_function( __METHOD__, '13.9' );
1254        $first_sidebar = Jetpack_Widgets::get_first_sidebar();
1255
1256        $widgets_module_active = Jetpack::is_module_active( 'widgets' );
1257        if ( ! $widgets_module_active ) {
1258            $widgets_module_active = Jetpack::activate_module( 'widgets', false, false );
1259        }
1260        if ( ! $widgets_module_active ) {
1261            return new WP_Error( 'module_activation_failed', 'Failed to activate the widgets module.', 400 );
1262        }
1263
1264        if ( $first_sidebar ) {
1265            $title   = isset( $address['name'] ) ? sanitize_text_field( $address['name'] ) : '';
1266            $street  = isset( $address['street'] ) ? sanitize_text_field( $address['street'] ) : '';
1267            $city    = isset( $address['city'] ) ? sanitize_text_field( $address['city'] ) : '';
1268            $state   = isset( $address['state'] ) ? sanitize_text_field( $address['state'] ) : '';
1269            $zip     = isset( $address['zip'] ) ? sanitize_text_field( $address['zip'] ) : '';
1270            $country = isset( $address['country'] ) ? sanitize_text_field( $address['country'] ) : '';
1271
1272            $full_address = implode( ' ', array_filter( array( $street, $city, $state, $zip, $country ) ) );
1273
1274            $widget_options = array(
1275                'title'   => $title,
1276                'address' => $full_address,
1277                'phone'   => '',
1278                'hours'   => '',
1279                'showmap' => false,
1280                'email'   => '',
1281            );
1282
1283            $widget_updated = '';
1284            if ( ! self::has_business_address_widget( $first_sidebar ) ) {
1285                $widget_updated = Jetpack_Widgets::insert_widget_in_sidebar( 'widget_contact_info', $widget_options, $first_sidebar );
1286            } else {
1287                $widget_updated = Jetpack_Widgets::update_widget_in_sidebar( 'widget_contact_info', $widget_options, $first_sidebar );
1288            }
1289            if ( is_wp_error( $widget_updated ) ) {
1290                return new WP_Error( 'widget_update_failed', 'Widget could not be updated.', 400 );
1291            }
1292
1293            $address_save = array(
1294                'name'    => $title,
1295                'street'  => $street,
1296                'city'    => $city,
1297                'state'   => $state,
1298                'zip'     => $zip,
1299                'country' => $country,
1300            );
1301            update_option( 'jpo_business_address', $address_save );
1302            return true;
1303        }
1304
1305        // No sidebar to place the widget.
1306        return new WP_Error( 'sidebar_not_found', 'No sidebar.', 400 );
1307    }
1308
1309    /**
1310     * Check whether "Contact Info & Map" widget is present in a given sidebar.
1311     *
1312     * @param string $sidebar ID of the sidebar to which the widget will be added.
1313     *
1314     * @return bool Whether the widget is present in a given sidebar.
1315     */
1316    private static function has_business_address_widget( $sidebar ) {
1317        $sidebars_widgets = get_option( 'sidebars_widgets', array() );
1318        if ( ! isset( $sidebars_widgets[ $sidebar ] ) ) {
1319            return false;
1320        }
1321        foreach ( $sidebars_widgets[ $sidebar ] as $widget ) {
1322            if ( str_contains( $widget, 'widget_contact_info' ) ) {
1323                return true;
1324            }
1325        }
1326        return false;
1327    }
1328
1329    /**
1330     * Check if user is allowed to perform the update.
1331     *
1332     * @since 4.3.0
1333     *
1334     * @param WP_REST_Request $request The request sent to the WP REST API.
1335     *
1336     * @return bool
1337     */
1338    public function can_request( $request ) {
1339        if ( 'GET' === $request->get_method() ) {
1340            return current_user_can( 'jetpack_admin_page' );
1341        } else {
1342            $module = Jetpack_Core_Json_Api_Endpoints::get_module_requested();
1343            if ( empty( $module ) ) {
1344                $params = $request->get_json_params();
1345                if ( ! is_array( $params ) ) {
1346                    $params = $request->get_body_params();
1347                }
1348                $options = Jetpack_Core_Json_Api_Endpoints::get_updateable_data_list( $params );
1349
1350                // The Post by Email gate applies only when the request contains nothing else.
1351                $groups = array_values( array_unique( array_column( $options, 'jp_group' ) ) );
1352                if ( array( 'post-by-email' ) === $groups ) {
1353                    $module = 'post-by-email';
1354                }
1355            }
1356            // User is trying to create, regenerate or delete its PbE.
1357            if ( 'post-by-email' === $module ) {
1358                return current_user_can( 'edit_posts' ) && current_user_can( 'jetpack_admin_page' );
1359            }
1360            return current_user_can( 'jetpack_configure_modules' );
1361        }
1362    }
1363}
1364
1365/**
1366 * Get detailed data from a specific module.
1367 *
1368 * phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound
1369 */
1370class Jetpack_Core_API_Module_Data_Endpoint {
1371
1372    /**
1373     * Process request and return different data based on the module we are interested in.
1374     *
1375     * @param WP_REST_Request $request WP API request.
1376     *
1377     * @return WP_REST_Response|WP_Error A REST response if the request was served successfully, otherwise an error.
1378     */
1379    public function process( $request ) {
1380        switch ( $request['slug'] ) {
1381            case 'protect':
1382                return $this->get_protect_data();
1383            case 'stats':
1384                return $this->get_stats_data( $request );
1385            case 'akismet':
1386                return $this->get_akismet_data();
1387            case 'monitor':
1388                return $this->get_monitor_data();
1389            case 'verification-tools':
1390                return $this->get_verification_tools_data();
1391            case 'vaultpress':
1392                return $this->get_vaultpress_data();
1393        }
1394    }
1395
1396    /**
1397     * Decide against which service to check the key.
1398     *
1399     * @since 4.8.0
1400     *
1401     * @param WP_REST_Request $request WP API request.
1402     *
1403     * @return bool
1404     */
1405    public function key_check( $request ) {
1406        switch ( $request['service'] ) {
1407            case 'akismet':
1408                $params = $request->get_json_params();
1409                if ( isset( $params['api_key'] ) && ! empty( $params['api_key'] ) ) {
1410                    return $this->check_akismet_key( $params['api_key'] );
1411                }
1412                return $this->check_akismet_key();
1413        }
1414        return false;
1415    }
1416
1417    /**
1418     * Get number of blocked intrusion attempts.
1419     *
1420     * @since 4.3.0
1421     *
1422     * @return mixed|WP_Error Number of blocked attempts if protection is enabled. Otherwise, a WP_Error instance with the corresponding error.
1423     */
1424    public function get_protect_data() {
1425        if ( Jetpack::is_module_active( 'protect' ) ) {
1426            return (int) get_site_option( 'jetpack_protect_blocked_attempts', 0 );
1427        }
1428
1429        return new WP_Error(
1430            'not_active',
1431            esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ),
1432            array( 'status' => 404 )
1433        );
1434    }
1435
1436    /**
1437     * Get number of spam messages blocked by Akismet.
1438     *
1439     * @since 4.3.0
1440     *
1441     * @return int|string Number of spam blocked by Akismet. Otherwise, an error message.
1442     */
1443    public function get_akismet_data() {
1444        $akismet_status = $this->akismet_is_active_and_registered();
1445        if ( ! is_wp_error( $akismet_status ) ) {
1446            return (int) get_option( 'akismet_spam_count', 0 );
1447        } else {
1448            return $akismet_status->get_error_code();
1449        }
1450    }
1451
1452    /**
1453     * Verify the Akismet API key.
1454     *
1455     * @since 4.8.0
1456     *
1457     * @param string $api_key Optional API key to check.
1458     *
1459     * @return array Information about the key. 'validKey' is true if key is valid, false otherwise.
1460     */
1461    public function check_akismet_key( $api_key = '' ) {
1462        $akismet_status = $this->akismet_class_exists();
1463        if ( is_wp_error( $akismet_status ) ) {
1464            return rest_ensure_response(
1465                array(
1466                    'validKey'          => false,
1467                    'invalidKeyCode'    => $akismet_status->get_error_code(),
1468                    'invalidKeyMessage' => $akismet_status->get_error_message(),
1469                )
1470            );
1471        }
1472
1473        $key_status = Akismet::check_key_status( empty( $api_key ) ? Akismet::get_api_key() : $api_key );
1474
1475        if ( ! $key_status || 'invalid' === $key_status || 'failed' === $key_status ) {
1476            return rest_ensure_response(
1477                array(
1478                    'validKey'          => false,
1479                    'invalidKeyCode'    => 'invalid_key',
1480                    'invalidKeyMessage' => esc_html__( 'Invalid Akismet key. Please contact support.', 'jetpack' ),
1481                )
1482            );
1483        }
1484
1485        return rest_ensure_response(
1486            array(
1487                'validKey' => isset( $key_status[1] ) && 'valid' === $key_status[1],
1488            )
1489        );
1490    }
1491
1492    /**
1493     * Check if Akismet class file exists and if class is loaded.
1494     *
1495     * @since 4.8.0
1496     *
1497     * @return bool|WP_Error Returns true if class file exists and class is loaded, WP_Error otherwise.
1498     */
1499    private function akismet_class_exists() {
1500        if ( ! file_exists( WP_PLUGIN_DIR . '/akismet/class.akismet.php' ) ) {
1501            return new WP_Error( 'not_installed', esc_html__( 'Please install Akismet.', 'jetpack' ), array( 'status' => 400 ) );
1502        }
1503
1504        if ( ! class_exists( 'Akismet' ) ) {
1505            return new WP_Error( 'not_active', esc_html__( 'Please activate Akismet.', 'jetpack' ), array( 'status' => 400 ) );
1506        }
1507
1508        return true;
1509    }
1510
1511    /**
1512     * Is Akismet registered and active?
1513     *
1514     * @since 4.3.0
1515     *
1516     * @return bool|WP_Error True if Akismet is active and registered. Otherwise, a WP_Error instance with the corresponding error.
1517     */
1518    private function akismet_is_active_and_registered() {
1519        $akismet_exists = $this->akismet_class_exists();
1520        if ( is_wp_error( $akismet_exists ) ) {
1521            return $akismet_exists;
1522        }
1523
1524        // What about if Akismet is put in a sub-directory or maybe in mu-plugins?
1525        require_once WP_PLUGIN_DIR . '/akismet/class.akismet.php';
1526        require_once WP_PLUGIN_DIR . '/akismet/class.akismet-admin.php';
1527        $akismet_key = Akismet::verify_key( Akismet::get_api_key() );
1528
1529        if ( ! $akismet_key || 'invalid' === $akismet_key || 'failed' === $akismet_key ) {
1530            return new WP_Error( 'invalid_key', esc_html__( 'Invalid Akismet key. Please contact support.', 'jetpack' ), array( 'status' => 400 ) );
1531        }
1532
1533        return true;
1534    }
1535
1536    /**
1537     * Get stats data for this site
1538     *
1539     * @since 4.1.0
1540     *
1541     * @param WP_REST_Request $request {
1542     *     Array of parameters received by request.
1543     *
1544     *     @type string $date Date range to restrict results to.
1545     * }
1546     *
1547     * @return WP_Error|WP_HTTP_Response|WP_REST_Response Stats information relayed from WordPress.com.
1548     */
1549    public function get_stats_data( WP_REST_Request $request ) {
1550        // Get parameters to fetch Stats data.
1551        $range = $request->get_param( 'range' );
1552
1553        // If no parameters were passed.
1554        if (
1555            empty( $range )
1556            || ! in_array( $range, array( 'day', 'week', 'month' ), true )
1557        ) {
1558            $range = 'day';
1559        }
1560
1561        $wpcom_stats = new WPCOM_Stats();
1562        switch ( $range ) {
1563
1564            // This is always called first on page load.
1565            case 'day':
1566                $initial_stats = $wpcom_stats->convert_stats_array_to_object( $wpcom_stats->get_stats() );
1567                return rest_ensure_response(
1568                    array(
1569                        'general' => $initial_stats,
1570
1571                        // Build data for 'day' as if it was $wpcom_stats ->get_visits( array( 'unit' => 'day, 'quantity' => 30).
1572                        'day'     => $initial_stats->visits ?? array(),
1573                    )
1574                );
1575            case 'week':
1576                return rest_ensure_response(
1577                    array(
1578                        'week' => $wpcom_stats->convert_stats_array_to_object(
1579                            $wpcom_stats->get_visits(
1580                                array(
1581                                    'unit'     => 'week',
1582                                    'quantity' => 14,
1583                                )
1584                            )
1585                        ),
1586                    )
1587                );
1588            case 'month':
1589                return rest_ensure_response(
1590                    array(
1591                        'month' => $wpcom_stats->convert_stats_array_to_object(
1592                            $wpcom_stats->get_visits(
1593                                array(
1594                                    'unit'     => 'month',
1595                                    'quantity' => 12,
1596                                )
1597                            )
1598                        ),
1599                    )
1600                );
1601        }
1602    }
1603
1604    /**
1605     * Get date of last downtime.
1606     *
1607     * @since 4.3.0
1608     *
1609     * @return mixed|WP_Error Number of days since last downtime. Otherwise, a WP_Error instance with the corresponding error.
1610     */
1611    public function get_monitor_data() {
1612        if ( ! Jetpack::is_module_active( 'monitor' ) ) {
1613            return new WP_Error(
1614                'not_active',
1615                esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ),
1616                array( 'status' => 404 )
1617            );
1618        }
1619
1620        $monitor       = new Jetpack_Monitor();
1621        $last_downtime = $monitor->monitor_get_last_downtime();
1622        if ( is_wp_error( $last_downtime ) ) {
1623            return $last_downtime;
1624        } elseif ( false === strtotime( $last_downtime ) ) {
1625            return rest_ensure_response(
1626                array(
1627                    'code' => 'success',
1628                    'date' => null,
1629                )
1630            );
1631        } else {
1632            return rest_ensure_response(
1633                array(
1634                    'code' => 'success',
1635                    'date' => human_time_diff( strtotime( $last_downtime ), strtotime( 'now' ) ),
1636                )
1637            );
1638        }
1639    }
1640
1641    /**
1642     * Get services that this site is verified with.
1643     *
1644     * @since 4.3.0
1645     *
1646     * @return mixed|WP_Error List of services that verified this site. Otherwise, a WP_Error instance with the corresponding error.
1647     */
1648    public function get_verification_tools_data() {
1649        if ( ! Jetpack::is_module_active( 'verification-tools' ) ) {
1650            return new WP_Error(
1651                'not_active',
1652                esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ),
1653                array( 'status' => 404 )
1654            );
1655        }
1656
1657        $verification_services_codes = get_option( 'verification_services_codes' );
1658        if (
1659            ! is_array( $verification_services_codes )
1660            || empty( $verification_services_codes )
1661        ) {
1662            return new WP_Error(
1663                'empty',
1664                esc_html__( 'Site not verified with any service.', 'jetpack' ),
1665                array( 'status' => 404 )
1666            );
1667        }
1668
1669        $services = array();
1670        foreach ( jetpack_verification_services() as $name => $service ) {
1671            if ( is_array( $service ) && ! empty( $verification_services_codes[ $name ] ) ) {
1672                switch ( $name ) {
1673                    case 'google':
1674                        $services[] = 'Google';
1675                        break;
1676                    case 'bing':
1677                        $services[] = 'Bing';
1678                        break;
1679                    case 'pinterest':
1680                        $services[] = 'Pinterest';
1681                        break;
1682                    case 'yandex':
1683                        $services[] = 'Yandex';
1684                        break;
1685                    case 'facebook':
1686                        $services[] = 'Facebook';
1687                        break;
1688                }
1689            }
1690        }
1691
1692        if ( empty( $services ) ) {
1693            return new WP_Error(
1694                'empty',
1695                esc_html__( 'Site not verified with any service.', 'jetpack' ),
1696                array( 'status' => 404 )
1697            );
1698        }
1699
1700        if ( 2 > count( $services ) ) {
1701            $message = esc_html(
1702                sprintf(
1703                    /* translators: %s is a service name like Google, Bing, Pinterest, etc. */
1704                    __( 'Your site is verified with %s.', 'jetpack' ),
1705                    $services[0]
1706                )
1707            );
1708        } else {
1709            $copy_services = $services;
1710            $last          = count( $copy_services ) - 1;
1711            $last_service  = $copy_services[ $last ];
1712            unset( $copy_services[ $last ] );
1713            $message = esc_html(
1714                sprintf(
1715                    /* translators: %1$s is a comma-separated list of services, and %2$s is a single service name like Google, Bing, Pinterest, etc. */
1716                    __( 'Your site is verified with %1$s and %2$s.', 'jetpack' ),
1717                    implode( ', ', $copy_services ),
1718                    $last_service
1719                )
1720            );
1721        }
1722
1723        return rest_ensure_response(
1724            array(
1725                'code'     => 'success',
1726                'message'  => $message,
1727                'services' => $services,
1728            )
1729        );
1730    }
1731
1732    /**
1733     * Get VaultPress site data including, among other things, the date of the last backup if it was completed.
1734     *
1735     * @since 4.3.0
1736     *
1737     * @return mixed|WP_Error VaultPress site data. Otherwise, a WP_Error instance with the corresponding error.
1738     */
1739    public function get_vaultpress_data() {
1740        if ( ! class_exists( 'VaultPress' ) ) {
1741            return new WP_Error(
1742                'not_active',
1743                esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ),
1744                array( 'status' => 404 )
1745            );
1746        }
1747
1748        $vaultpress = new VaultPress();
1749        if ( ! $vaultpress->is_registered() ) {
1750            return rest_ensure_response(
1751                array(
1752                    'code'    => 'not_registered',
1753                    'message' => esc_html__( 'You need to register for VaultPress.', 'jetpack' ),
1754                )
1755            );
1756        }
1757
1758        $data = json_decode( base64_decode( $vaultpress->contact_service( 'plugin_data' ) ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
1759        if ( false === $data ) {
1760            return rest_ensure_response(
1761                array(
1762                    'code'    => 'not_registered',
1763                    'message' => esc_html__( 'Could not connect to VaultPress.', 'jetpack' ),
1764                )
1765            );
1766        } elseif ( is_wp_error( $data ) || ! isset( $data->backups->last_backup ) ) {
1767            return $data;
1768        } elseif ( empty( $data->backups->last_backup ) ) {
1769            return rest_ensure_response(
1770                array(
1771                    'code'    => 'success',
1772                    'message' => esc_html__( 'VaultPress is active and will back up your site soon.', 'jetpack' ),
1773                    'data'    => $data,
1774                )
1775            );
1776        } else {
1777            return rest_ensure_response(
1778                array(
1779                    'code'    => 'success',
1780                    'message' => esc_html(
1781                        sprintf(
1782                            /* translators: placeholder is a unit of time (1 hour, 5 days, ...) */
1783                            esc_html__( 'Your site was successfully backed up %s ago.', 'jetpack' ),
1784                            human_time_diff(
1785                                $data->backups->last_backup,
1786                                current_time( 'timestamp' ) // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested -- We cannot switch to time() or another "unix" timestamp option as long as $data->backups->last_backup uses WP timestamps.
1787                            )
1788                        )
1789                    ),
1790                    'data'    => $data,
1791                )
1792            );
1793        }
1794    }
1795
1796    /**
1797     * A WordPress REST API permission callback method that accepts a request object and
1798     * decides if the current user has enough privileges to act.
1799     *
1800     * @since 4.3.0
1801     *
1802     * @return bool does a current user have enough privileges.
1803     */
1804    public function can_request() {
1805        return current_user_can( 'jetpack_admin_page' );
1806    }
1807}
1808
1809// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move these functions to some other file.
1810
1811/**
1812 * Actions performed only when Gravatar Hovercards is activated through the endpoint call.
1813 *
1814 * @since 4.3.1
1815 */
1816function jetpack_do_after_gravatar_hovercards_activation() {
1817
1818    // When Gravatar Hovercards is activated, enable them automatically.
1819    update_option( 'gravatar_disable_hovercards', 'enabled' );
1820}
1821add_action( 'jetpack_activate_module_gravatar-hovercards', 'jetpack_do_after_gravatar_hovercards_activation' );
1822
1823/**
1824 * Actions performed only when Gravatar Hovercards is activated through the endpoint call.
1825 *
1826 * @since 4.3.1
1827 */
1828function jetpack_do_after_gravatar_hovercards_deactivation() {
1829
1830    // When Gravatar Hovercards is deactivated, disable them automatically.
1831    update_option( 'gravatar_disable_hovercards', 'disabled' );
1832}
1833add_action( 'jetpack_deactivate_module_gravatar-hovercards', 'jetpack_do_after_gravatar_hovercards_deactivation' );