Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
37.91% covered (danger)
37.91%
334 / 881
3.45% covered (danger)
3.45%
1 / 29
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_do_after_markdown_activation
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
53.48% covered (warning)
53.48%
261 / 488
16.67% covered (danger)
16.67%
1 / 6
5228.27
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
51.78% covered (warning)
51.78%
204 / 394
0.00% covered (danger)
0.00%
0 / 1
3256.21
 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__( 'The requested Jetpack module was deactivated.', 'jetpack' ),
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                        return delete_option( 'WPLANG' );
726                    }
727
728                    if ( ! function_exists( 'request_filesystem_credentials' ) ) {
729                        require_once ABSPATH . 'wp-admin/includes/file.php';
730                    }
731
732                    if ( ! function_exists( 'wp_download_language_pack' ) ) {
733                        require_once ABSPATH . 'wp-admin/includes/translation-install.php';
734                    }
735
736                    // `wp_download_language_pack` only tries to download packs if they're not already available.
737                    $language = wp_download_language_pack( $value );
738                    if ( false === $language ) {
739                        // The language pack download failed.
740                        $updated = false;
741                        break;
742                    }
743                    $updated = get_option( 'WPLANG' ) === $language ? true : update_option( 'WPLANG', $language );
744                    break;
745
746                case 'monitor_receive_notifications':
747                    if ( ! class_exists( 'Jetpack_Monitor' ) ) {
748                        $updated = false;
749                        break;
750                    }
751
752                    $monitor = new Jetpack_Monitor();
753
754                    // If we got true as response, consider it done.
755                    $updated = true === $monitor->update_option_receive_jetpack_monitor_notification( $value );
756                    break;
757
758                case 'post_by_email_address':
759                    if ( ! class_exists( 'Jetpack_Post_By_Email' ) ) {
760                        $updated = false;
761                        break;
762                    }
763
764                    $result = Jetpack_Post_By_Email::init()->process_api_request( $value );
765
766                    // If we got an email address (create or regenerate) or 1 (delete), consider it done.
767                    if ( is_string( $result ) && preg_match( '/[a-z0-9]+@post.wordpress.com/', $result ) ) {
768                        $response[ $option ] = $result;
769                        $updated             = true;
770                    } elseif ( 1 == $result ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
771                        $updated = true;
772                    } elseif ( is_array( $result ) && isset( $result['message'] ) ) {
773                        $error = $result['message'];
774                    }
775                    break;
776
777                case 'jetpack_protect_key':
778                    $brute_force_protection = Brute_Force_Protection::instance();
779                    if ( 'create' === $value ) {
780                        $result = $brute_force_protection->get_protect_key();
781                    } else {
782                        $result = false;
783                    }
784
785                    // If we got one of Protect keys, consider it done.
786                    if ( is_string( $result ) && preg_match( '/[a-z0-9]{40,}/i', $result ) ) {
787                        $response[ $option ] = $result;
788                        $updated             = true;
789                    }
790                    break;
791
792                case 'jetpack_protect_global_whitelist':
793                    $updated = Brute_Force_Protection_Shared_Functions::save_allow_list( explode( PHP_EOL, str_replace( array( ' ', ',' ), array( '', "\n" ), $value ) ) );
794
795                    if ( is_wp_error( $updated ) ) {
796                        $error = $updated->get_error_message();
797                    }
798                    break;
799
800                case 'show_headline':
801                case 'show_thumbnails':
802                    $grouped_options_current    = (array) Jetpack_Options::get_option( 'relatedposts' );
803                    $grouped_options            = $grouped_options_current;
804                    $grouped_options[ $option ] = $value;
805
806                    // If option value was the same, consider it done.
807                    $updated = $grouped_options_current !== $grouped_options ? Jetpack_Options::update_option( 'relatedposts', $grouped_options ) : true;
808                    break;
809
810                case 'search_auto_config':
811                    if ( ! $value ) {
812                        // Skip execution if no value is specified.
813                        $updated = true;
814                    } else {
815                        $plan = new Automattic\Jetpack\Search\Plan();
816                        if ( ! $plan->supports_instant_search() ) {
817                            $updated = new WP_Error( 'instant_search_not_supported', 'Instant Search is not supported by this site', array( 'status' => 400 ) );
818                            $error   = $updated->get_error_message();
819                        } elseif ( ! Automattic\Jetpack\Search\Options::is_instant_enabled() ) {
820                            $updated = new WP_Error( 'instant_search_disabled', 'Instant Search is disabled', array( 'status' => 400 ) );
821                            $error   = $updated->get_error_message();
822                        } else {
823                            $blog_id  = Automattic\Jetpack\Search\Helper::get_wpcom_site_id();
824                            $instance = Automattic\Jetpack\Search\Instant_Search::instance( $blog_id );
825                            $instance->auto_config_search();
826                            $updated = true;
827                        }
828                    }
829                    break;
830
831                case 'google':
832                case 'bing':
833                case 'pinterest':
834                case 'yandex':
835                case 'facebook':
836                    $grouped_options_current = (array) get_option( 'verification_services_codes' );
837                    $grouped_options         = $grouped_options_current;
838
839                    $validated_code = jetpack_verification_validate_code( $value );
840                    if ( false === $validated_code ) {
841                        $error = esc_html__( 'The site verification code is invalid.', 'jetpack' );
842                        break;
843                    }
844
845                    $grouped_options[ $option ] = $validated_code;
846
847                    // If option value was the same, consider it done.
848                    $updated = $grouped_options_current !== $grouped_options
849                        ? update_option( 'verification_services_codes', $grouped_options )
850                        : true;
851                    break;
852
853                case Jetpack_SEO_Utils::FRONT_PAGE_META_OPTION:
854                    Jetpack_SEO_Utils::update_front_page_meta_description( $value );
855                    $response[ $option ] = Jetpack_SEO_Utils::get_front_page_meta_description();
856                    // The helper returns an empty string for a successful clear or
857                    // same-value write, so use its authoritative getter for the response
858                    // and treat every valid request reaching this switch as handled.
859                    $updated = true;
860                    break;
861
862                case 'sharing_services':
863                    if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
864                        break;
865                    }
866
867                    $sharer = new Sharing_Service();
868
869                    // If option value was the same, consider it done.
870                    $updated = $value !== $sharer->get_blog_services()
871                        ? $sharer->set_blog_services( $value['visible'], $value['hidden'] )
872                        : true;
873                    break;
874
875                case 'button_style':
876                case 'sharing_label':
877                case 'show':
878                    if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
879                        break;
880                    }
881
882                    if ( method_exists( Sharing_Options::class, 'update' ) ) {
883                        $updated = Sharing_Options::update( array( $option => 'sharing_label' === $option ? wp_slash( $value ) : $value ) );
884                        break;
885                    }
886
887                    $sharer                     = new Sharing_Service();
888                    $grouped_options            = $sharer->get_global_options();
889                    $grouped_options[ $option ] = $value;
890                    $updated                    = $sharer->set_global_options( $grouped_options );
891                    break;
892
893                case 'custom':
894                    if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
895                        break;
896                    }
897
898                    $sharer  = new Sharing_Service();
899                    $updated = $sharer->new_service( stripslashes( $value['sharing_name'] ), stripslashes( $value['sharing_url'] ), stripslashes( $value['sharing_icon'] ) );
900
901                    // Return new custom service.
902                    $response[ $option ] = $updated;
903                    break;
904
905                case 'sharing_delete_service':
906                    if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
907                        break;
908                    }
909
910                    $sharer  = new Sharing_Service();
911                    $updated = $sharer->delete_service( $value );
912                    break;
913
914                case 'jetpack-twitter-cards-site-tag':
915                    $value   = trim( ltrim( wp_strip_all_tags( $value ), '@' ) );
916                    $updated = get_option( $option ) !== $value ? update_option( $option, $value ) : true;
917                    break;
918
919                case 'admin_bar':
920                case 'roles':
921                case 'count_roles':
922                case 'blog_id':
923                case 'do_not_track':
924                case 'version':
925                case 'collapse_nudges':
926                    $grouped_options_current    = (array) get_option( 'stats_options' );
927                    $grouped_options            = $grouped_options_current;
928                    $grouped_options[ $option ] = $value;
929
930                    // If option value was the same, consider it done.
931                    $updated = $grouped_options_current !== $grouped_options
932                        ? update_option( 'stats_options', $grouped_options )
933                        : true;
934                    break;
935
936                case 'enable_odyssey_stats':
937                    $updated = Stats_Admin_Main::update_new_stats_status( $value );
938
939                    break;
940
941                case 'akismet_show_user_comments_approved':
942                    // Save Akismet option '1' or '0' like it's done in akismet/class.akismet-admin.php.
943                    $updated = get_option( $option ) != $value // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual
944                        ? update_option( $option, $value ? '1' : '0' )
945                        : true;
946                    break;
947
948                case 'wordpress_api_key':
949                    if ( ! file_exists( WP_PLUGIN_DIR . '/akismet/class.akismet.php' ) ) {
950                        $error   = esc_html__( 'Please install Akismet.', 'jetpack' );
951                        $updated = false;
952                        break;
953                    }
954
955                    if ( ! defined( 'AKISMET_VERSION' ) ) {
956                        $error   = esc_html__( 'Please activate Akismet.', 'jetpack' );
957                        $updated = false;
958                        break;
959                    }
960
961                    // Allow to clear the API key field.
962                    if ( '' === $value ) {
963                        $updated = get_option( $option ) !== $value
964                            ? update_option( $option, $value )
965                            : true;
966                        break;
967                    }
968
969                    require_once WP_PLUGIN_DIR . '/akismet/class.akismet.php';
970                    require_once WP_PLUGIN_DIR . '/akismet/class.akismet-admin.php';
971
972                    if ( class_exists( 'Akismet_Admin' ) && method_exists( 'Akismet_Admin', 'save_key' ) ) {
973                        if ( Akismet::verify_key( $value ) === 'valid' ) {
974                            $akismet_user = Akismet_Admin::get_akismet_user( $value );
975                            if ( $akismet_user ) {
976                                if ( in_array( $akismet_user->status, array( 'active', 'active-dunning', 'no-sub' ), true ) ) {
977                                    $updated = get_option( $option ) !== $value
978                                        ? update_option( $option, $value )
979                                        : true;
980                                    break;
981                                } else {
982                                    $error = esc_html__( "Akismet user status doesn't allow to update the key", 'jetpack' );
983                                }
984                            } else {
985                                $error = esc_html__( 'Invalid Akismet user', 'jetpack' );
986                            }
987                        } else {
988                            $error = esc_html__( 'Invalid Akismet key', 'jetpack' );
989                        }
990                    } else {
991                        $error = esc_html__( 'Akismet is not installed or active', 'jetpack' );
992                    }
993                    $updated = false;
994                    break;
995
996                case 'google_analytics_tracking_id':
997                    $grouped_options_current = (array) get_option( 'jetpack_wga' );
998                    $grouped_options         = $grouped_options_current;
999                    $grouped_options['code'] = $value;
1000
1001                    // If option value was the same, consider it done.
1002                    $updated = $grouped_options_current !== $grouped_options
1003                        ? update_option( 'jetpack_wga', $grouped_options )
1004                        : true;
1005                    break;
1006
1007                case 'dismiss_empty_stats_card':
1008                case 'dismiss_dash_backup_getting_started':
1009                case 'dismiss_dash_agencies_learn_more':
1010                    // If option value was the same, consider it done.
1011                    $updated = get_option( $option ) != $value // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual -- ensure we support bools or strings saved by update_option.
1012                        ? update_option( $option, (bool) $value )
1013                        : true;
1014                    break;
1015
1016                case 'jetpack_subscriptions_reply_to':
1017                    // If option value was the same, consider it done.
1018                    require_once JETPACK__PLUGIN_DIR . 'modules/subscriptions/class-settings.php';
1019                    $sub_value = Automattic\Jetpack\Modules\Subscriptions\Settings::is_valid_reply_to( $value )
1020                        ? $value
1021                        : Automattic\Jetpack\Modules\Subscriptions\Settings::$default_reply_to;
1022
1023                        $updated = (string) get_option( $option ) !== (string) $sub_value ? update_option( $option, $sub_value ) : true;
1024                    break;
1025                case 'jetpack_subscriptions_from_name':
1026                    // If option value was the same, consider it done.
1027                    $sub_value = sanitize_text_field( $value );
1028                    $updated   = (string) get_option( $option ) !== (string) $sub_value ? update_option( $option, $sub_value ) : true;
1029                    break;
1030
1031                case 'stb_enabled':
1032                case 'stc_enabled':
1033                case 'sm_enabled':
1034                case 'jetpack_subscribe_overlay_enabled':
1035                case 'jetpack_subscribe_floating_button_enabled':
1036                case 'wpcom_newsletter_categories_enabled':
1037                case 'wpcom_featured_image_in_email':
1038                case 'jetpack_gravatar_in_email':
1039                case 'jetpack_author_in_email':
1040                case 'jetpack_post_date_in_email':
1041                case 'wpcom_subscription_emails_use_excerpt':
1042                case 'jetpack_subscriptions_subscribe_post_end_enabled':
1043                case 'jetpack_subscriptions_login_navigation_enabled':
1044                case 'jetpack_subscriptions_subscribe_navigation_enabled':
1045                    // Convert the false value to 0. This allows the option to be updated if it doesn't exist yet.
1046                    $sub_value = $value ? $value : 0;
1047                    $updated   = (string) get_option( $option ) !== (string) $sub_value ? update_option( $option, $sub_value ) : true;
1048                    break;
1049
1050                case 'jetpack_blocks_disabled':
1051                    $updated = (bool) get_option( $option ) !== (bool) $value ? update_option( $option, (bool) $value ) : true;
1052                    break;
1053
1054                case 'subscription_options':
1055                    if ( ! is_array( $value ) ) {
1056                        break;
1057                    }
1058
1059                    $allowed_keys   = array( 'invitation', 'comment_follow', 'welcome', 'subscribe_modal_heading', 'free_tier_description', 'hide_free_tier' );
1060                    $filtered_value = array_filter(
1061                        $value,
1062                        function ( $key ) use ( $allowed_keys ) {
1063                            return in_array( $key, $allowed_keys, true );
1064                        },
1065                        ARRAY_FILTER_USE_KEY
1066                    );
1067
1068                    if ( empty( $filtered_value ) ) {
1069                        break;
1070                    }
1071
1072                    // `hide_free_tier` is a boolean flag, so pull it out before the HTML
1073                    // sanitization below (which expects strings). Sanitize it with
1074                    // rest_sanitize_boolean() so stringy booleans (e.g. "false", "0")
1075                    // are interpreted correctly rather than being treated as truthy by a
1076                    // plain `! empty()`.
1077                    $has_hide_free_tier = array_key_exists( 'hide_free_tier', $filtered_value );
1078                    $hide_free_tier     = $has_hide_free_tier && rest_sanitize_boolean( $filtered_value['hide_free_tier'] );
1079                    unset( $filtered_value['hide_free_tier'] );
1080
1081                    array_walk_recursive(
1082                        $filtered_value,
1083                        function ( &$value ) {
1084                            $value = wp_kses(
1085                                $value,
1086                                array(
1087                                    'ul'     => array(),
1088                                    'li'     => array(),
1089                                    'p'      => array(),
1090                                    'strong' => array(),
1091                                    'ol'     => array(),
1092                                    'em'     => array(),
1093                                    'a'      => array(
1094                                        'href' => array(),
1095                                    ),
1096                                )
1097                            );
1098                        }
1099                    );
1100
1101                    // Normalize whitespace-only `subscribe_modal_heading` input to empty so
1102                    // the modal template's `empty()` fallback fires. PHP's `empty()` treats
1103                    // `"   "` as non-empty, which would otherwise render a blank heading.
1104                    if ( isset( $filtered_value['subscribe_modal_heading'] ) ) {
1105                        $filtered_value['subscribe_modal_heading'] = trim( $filtered_value['subscribe_modal_heading'] );
1106                    }
1107
1108                    // The free tier description is stored as plain markdown source, so strip
1109                    // all HTML and cap its length to match the paid-tier description field.
1110                    // WordPress core guarantees mb_substr() (polyfilled in wp-includes/compat.php
1111                    // when the mbstring extension is unavailable), so it's safe to use directly.
1112                    // A JSON payload could supply a non-scalar (array/object) for this field,
1113                    // which would fatal in wp_kses()/mb_substr() on PHP 8+, so drop invalid values.
1114                    if ( isset( $filtered_value['free_tier_description'] ) ) {
1115                        if ( is_scalar( $filtered_value['free_tier_description'] ) ) {
1116                            $filtered_value['free_tier_description'] = mb_substr( wp_kses( (string) $filtered_value['free_tier_description'], array() ), 0, 500 );
1117                        } else {
1118                            unset( $filtered_value['free_tier_description'] );
1119                        }
1120                    }
1121
1122                    if ( $has_hide_free_tier ) {
1123                        $filtered_value['hide_free_tier'] = $hide_free_tier;
1124                    }
1125
1126                    $old_subscription_options = get_option( 'subscription_options' );
1127                    if ( ! is_array( $old_subscription_options ) ) {
1128                        $old_subscription_options = array();
1129                    }
1130                    $new_subscription_options = array_merge( $old_subscription_options, $filtered_value );
1131                    $updated                  = true;
1132
1133                    if ( serialize( $old_subscription_options ) === serialize( $new_subscription_options ) ) { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
1134                        break; // This prevents the option update to fail when the values are the same.
1135                    }
1136
1137                    if ( ! update_option( $option, $new_subscription_options ) ) {
1138                        $updated = false;
1139                        $error   = esc_html__( 'Subscription Options failed to process.', 'jetpack' );
1140                    }
1141                    break;
1142
1143                case Jetpack_Newsletter_Category_Helper::NEWSLETTER_CATEGORIES_OPTION:
1144                    if ( ! is_array( $value ) || empty( $value ) ) {
1145                        $updated = true;
1146                        break;
1147                    }
1148
1149                    // If we are already current, do nothing
1150                    $current_value = Jetpack_Newsletter_Category_Helper::get_category_ids();
1151                    if ( $value === $current_value ) {
1152                        $updated = true;
1153                        break;
1154                    }
1155
1156                    if ( Jetpack_Newsletter_Category_Helper::save_category_ids( $value ) ) {
1157                        $updated = true;
1158                    } else {
1159                        $updated = false;
1160                        $error   = esc_html__( 'Newsletter category did not update.', 'jetpack' );
1161                    }
1162
1163                    break;
1164
1165                default:
1166                    // Boolean values are stored as 1 or 0.
1167                    if ( isset( $options[ $option ]['type'] ) && 'boolean' === $options[ $option ]['type'] ) {
1168                        $value = (int) $value;
1169                    }
1170
1171                    // If option value was the same as it's current value, or it's default, consider it done.
1172                    $default = $options[ $option ]['default'] ?? false;
1173                    $updated = get_option( $option, $default ) != $value // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual -- ensure we support scalars or strings saved by update_option.
1174                        ? update_option( $option, $value )
1175                        : true;
1176                    break;
1177            }
1178
1179            // The option was not updated.
1180            if ( ! $updated ) {
1181                $not_updated[ $option ] = $error;
1182            }
1183        }
1184
1185        if ( empty( $invalid ) && empty( $not_updated ) ) {
1186            // The option was updated.
1187            return rest_ensure_response( $response );
1188        } else {
1189            $invalid_count     = count( $invalid );
1190            $not_updated_count = count( $not_updated );
1191            $error             = '';
1192            if ( $invalid_count > 0 ) {
1193                $error = sprintf(
1194                /* Translators: the plural variable is a comma-separated list. Example: dog, cat, bird. */
1195                    _n( 'Invalid option: %s.', 'Invalid options: %s.', $invalid_count, 'jetpack' ),
1196                    implode( ', ', $invalid )
1197                );
1198            }
1199            if ( $not_updated_count > 0 ) {
1200                $not_updated_messages = array();
1201                foreach ( $not_updated as $not_updated_option => $not_updated_message ) {
1202                    if ( ! empty( $not_updated_message ) ) {
1203                        $not_updated_messages[] = sprintf(
1204                            /* Translators: the first variable is a module option or slug, or setting. The second is the error message . */
1205                            __( '%1$s: %2$s', 'jetpack' ),
1206                            $not_updated_option,
1207                            $not_updated_message
1208                        );
1209                    }
1210                }
1211                if ( ! empty( $error ) ) {
1212                    $error .= ' ';
1213                }
1214                if ( ! empty( $not_updated_messages ) ) {
1215                    $error .= ' ' . implode( '. ', $not_updated_messages );
1216                }
1217            }
1218            // There was an error because some options were updated but others were invalid or failed to update.
1219            return new WP_Error( 'some_updated', esc_html( $error ), array( 'status' => 400 ) );
1220        }
1221    }
1222
1223    /**
1224     * Perform tasks in the site based on onboarding choices.
1225     *
1226     * @since 5.4.0
1227     *
1228     * @deprecated since 13.9
1229     *
1230     * @param array $data Onboarding choices made by user.
1231     *
1232     * @return string Result of onboarding processing and, if there is one, an error message.
1233     */
1234    private function process_onboarding( $data ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1235        _deprecated_function( __METHOD__, '13.9' );
1236        return '';
1237    }
1238
1239    /**
1240     * Add or update Business Address widget.
1241     *
1242     * @deprecated since 13.9
1243     *
1244     * @param array $address Array of business address fields.
1245     *
1246     * @return WP_Error|true True if the data was saved correctly.
1247     */
1248    private static function handle_business_address( $address ) {
1249        _deprecated_function( __METHOD__, '13.9' );
1250        $first_sidebar = Jetpack_Widgets::get_first_sidebar();
1251
1252        $widgets_module_active = Jetpack::is_module_active( 'widgets' );
1253        if ( ! $widgets_module_active ) {
1254            $widgets_module_active = Jetpack::activate_module( 'widgets', false, false );
1255        }
1256        if ( ! $widgets_module_active ) {
1257            return new WP_Error( 'module_activation_failed', 'Failed to activate the widgets module.', 400 );
1258        }
1259
1260        if ( $first_sidebar ) {
1261            $title   = isset( $address['name'] ) ? sanitize_text_field( $address['name'] ) : '';
1262            $street  = isset( $address['street'] ) ? sanitize_text_field( $address['street'] ) : '';
1263            $city    = isset( $address['city'] ) ? sanitize_text_field( $address['city'] ) : '';
1264            $state   = isset( $address['state'] ) ? sanitize_text_field( $address['state'] ) : '';
1265            $zip     = isset( $address['zip'] ) ? sanitize_text_field( $address['zip'] ) : '';
1266            $country = isset( $address['country'] ) ? sanitize_text_field( $address['country'] ) : '';
1267
1268            $full_address = implode( ' ', array_filter( array( $street, $city, $state, $zip, $country ) ) );
1269
1270            $widget_options = array(
1271                'title'   => $title,
1272                'address' => $full_address,
1273                'phone'   => '',
1274                'hours'   => '',
1275                'showmap' => false,
1276                'email'   => '',
1277            );
1278
1279            $widget_updated = '';
1280            if ( ! self::has_business_address_widget( $first_sidebar ) ) {
1281                $widget_updated = Jetpack_Widgets::insert_widget_in_sidebar( 'widget_contact_info', $widget_options, $first_sidebar );
1282            } else {
1283                $widget_updated = Jetpack_Widgets::update_widget_in_sidebar( 'widget_contact_info', $widget_options, $first_sidebar );
1284            }
1285            if ( is_wp_error( $widget_updated ) ) {
1286                return new WP_Error( 'widget_update_failed', 'Widget could not be updated.', 400 );
1287            }
1288
1289            $address_save = array(
1290                'name'    => $title,
1291                'street'  => $street,
1292                'city'    => $city,
1293                'state'   => $state,
1294                'zip'     => $zip,
1295                'country' => $country,
1296            );
1297            update_option( 'jpo_business_address', $address_save );
1298            return true;
1299        }
1300
1301        // No sidebar to place the widget.
1302        return new WP_Error( 'sidebar_not_found', 'No sidebar.', 400 );
1303    }
1304
1305    /**
1306     * Check whether "Contact Info & Map" widget is present in a given sidebar.
1307     *
1308     * @param string $sidebar ID of the sidebar to which the widget will be added.
1309     *
1310     * @return bool Whether the widget is present in a given sidebar.
1311     */
1312    private static function has_business_address_widget( $sidebar ) {
1313        $sidebars_widgets = get_option( 'sidebars_widgets', array() );
1314        if ( ! isset( $sidebars_widgets[ $sidebar ] ) ) {
1315            return false;
1316        }
1317        foreach ( $sidebars_widgets[ $sidebar ] as $widget ) {
1318            if ( str_contains( $widget, 'widget_contact_info' ) ) {
1319                return true;
1320            }
1321        }
1322        return false;
1323    }
1324
1325    /**
1326     * Check if user is allowed to perform the update.
1327     *
1328     * @since 4.3.0
1329     *
1330     * @param WP_REST_Request $request The request sent to the WP REST API.
1331     *
1332     * @return bool
1333     */
1334    public function can_request( $request ) {
1335        if ( 'GET' === $request->get_method() ) {
1336            return current_user_can( 'jetpack_admin_page' );
1337        } else {
1338            $module = Jetpack_Core_Json_Api_Endpoints::get_module_requested();
1339            if ( empty( $module ) ) {
1340                $params = $request->get_json_params();
1341                if ( ! is_array( $params ) ) {
1342                    $params = $request->get_body_params();
1343                }
1344                $options = Jetpack_Core_Json_Api_Endpoints::get_updateable_data_list( $params );
1345
1346                // The Post by Email gate applies only when the request contains nothing else.
1347                $groups = array_values( array_unique( array_column( $options, 'jp_group' ) ) );
1348                if ( array( 'post-by-email' ) === $groups ) {
1349                    $module = 'post-by-email';
1350                }
1351            }
1352            // User is trying to create, regenerate or delete its PbE.
1353            if ( 'post-by-email' === $module ) {
1354                return current_user_can( 'edit_posts' ) && current_user_can( 'jetpack_admin_page' );
1355            }
1356            return current_user_can( 'jetpack_configure_modules' );
1357        }
1358    }
1359}
1360
1361/**
1362 * Get detailed data from a specific module.
1363 *
1364 * phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound
1365 */
1366class Jetpack_Core_API_Module_Data_Endpoint {
1367
1368    /**
1369     * Process request and return different data based on the module we are interested in.
1370     *
1371     * @param WP_REST_Request $request WP API request.
1372     *
1373     * @return WP_REST_Response|WP_Error A REST response if the request was served successfully, otherwise an error.
1374     */
1375    public function process( $request ) {
1376        switch ( $request['slug'] ) {
1377            case 'protect':
1378                return $this->get_protect_data();
1379            case 'stats':
1380                return $this->get_stats_data( $request );
1381            case 'akismet':
1382                return $this->get_akismet_data();
1383            case 'monitor':
1384                return $this->get_monitor_data();
1385            case 'verification-tools':
1386                return $this->get_verification_tools_data();
1387            case 'vaultpress':
1388                return $this->get_vaultpress_data();
1389        }
1390    }
1391
1392    /**
1393     * Decide against which service to check the key.
1394     *
1395     * @since 4.8.0
1396     *
1397     * @param WP_REST_Request $request WP API request.
1398     *
1399     * @return bool
1400     */
1401    public function key_check( $request ) {
1402        switch ( $request['service'] ) {
1403            case 'akismet':
1404                $params = $request->get_json_params();
1405                if ( isset( $params['api_key'] ) && ! empty( $params['api_key'] ) ) {
1406                    return $this->check_akismet_key( $params['api_key'] );
1407                }
1408                return $this->check_akismet_key();
1409        }
1410        return false;
1411    }
1412
1413    /**
1414     * Get number of blocked intrusion attempts.
1415     *
1416     * @since 4.3.0
1417     *
1418     * @return mixed|WP_Error Number of blocked attempts if protection is enabled. Otherwise, a WP_Error instance with the corresponding error.
1419     */
1420    public function get_protect_data() {
1421        if ( Jetpack::is_module_active( 'protect' ) ) {
1422            return (int) get_site_option( 'jetpack_protect_blocked_attempts', 0 );
1423        }
1424
1425        return new WP_Error(
1426            'not_active',
1427            esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ),
1428            array( 'status' => 404 )
1429        );
1430    }
1431
1432    /**
1433     * Get number of spam messages blocked by Akismet.
1434     *
1435     * @since 4.3.0
1436     *
1437     * @return int|string Number of spam blocked by Akismet. Otherwise, an error message.
1438     */
1439    public function get_akismet_data() {
1440        $akismet_status = $this->akismet_is_active_and_registered();
1441        if ( ! is_wp_error( $akismet_status ) ) {
1442            return (int) get_option( 'akismet_spam_count', 0 );
1443        } else {
1444            return $akismet_status->get_error_code();
1445        }
1446    }
1447
1448    /**
1449     * Verify the Akismet API key.
1450     *
1451     * @since 4.8.0
1452     *
1453     * @param string $api_key Optional API key to check.
1454     *
1455     * @return array Information about the key. 'validKey' is true if key is valid, false otherwise.
1456     */
1457    public function check_akismet_key( $api_key = '' ) {
1458        $akismet_status = $this->akismet_class_exists();
1459        if ( is_wp_error( $akismet_status ) ) {
1460            return rest_ensure_response(
1461                array(
1462                    'validKey'          => false,
1463                    'invalidKeyCode'    => $akismet_status->get_error_code(),
1464                    'invalidKeyMessage' => $akismet_status->get_error_message(),
1465                )
1466            );
1467        }
1468
1469        $key_status = Akismet::check_key_status( empty( $api_key ) ? Akismet::get_api_key() : $api_key );
1470
1471        if ( ! $key_status || 'invalid' === $key_status || 'failed' === $key_status ) {
1472            return rest_ensure_response(
1473                array(
1474                    'validKey'          => false,
1475                    'invalidKeyCode'    => 'invalid_key',
1476                    'invalidKeyMessage' => esc_html__( 'Invalid Akismet key. Please contact support.', 'jetpack' ),
1477                )
1478            );
1479        }
1480
1481        return rest_ensure_response(
1482            array(
1483                'validKey' => isset( $key_status[1] ) && 'valid' === $key_status[1],
1484            )
1485        );
1486    }
1487
1488    /**
1489     * Check if Akismet class file exists and if class is loaded.
1490     *
1491     * @since 4.8.0
1492     *
1493     * @return bool|WP_Error Returns true if class file exists and class is loaded, WP_Error otherwise.
1494     */
1495    private function akismet_class_exists() {
1496        if ( ! file_exists( WP_PLUGIN_DIR . '/akismet/class.akismet.php' ) ) {
1497            return new WP_Error( 'not_installed', esc_html__( 'Please install Akismet.', 'jetpack' ), array( 'status' => 400 ) );
1498        }
1499
1500        if ( ! class_exists( 'Akismet' ) ) {
1501            return new WP_Error( 'not_active', esc_html__( 'Please activate Akismet.', 'jetpack' ), array( 'status' => 400 ) );
1502        }
1503
1504        return true;
1505    }
1506
1507    /**
1508     * Is Akismet registered and active?
1509     *
1510     * @since 4.3.0
1511     *
1512     * @return bool|WP_Error True if Akismet is active and registered. Otherwise, a WP_Error instance with the corresponding error.
1513     */
1514    private function akismet_is_active_and_registered() {
1515        $akismet_exists = $this->akismet_class_exists();
1516        if ( is_wp_error( $akismet_exists ) ) {
1517            return $akismet_exists;
1518        }
1519
1520        // What about if Akismet is put in a sub-directory or maybe in mu-plugins?
1521        require_once WP_PLUGIN_DIR . '/akismet/class.akismet.php';
1522        require_once WP_PLUGIN_DIR . '/akismet/class.akismet-admin.php';
1523        $akismet_key = Akismet::verify_key( Akismet::get_api_key() );
1524
1525        if ( ! $akismet_key || 'invalid' === $akismet_key || 'failed' === $akismet_key ) {
1526            return new WP_Error( 'invalid_key', esc_html__( 'Invalid Akismet key. Please contact support.', 'jetpack' ), array( 'status' => 400 ) );
1527        }
1528
1529        return true;
1530    }
1531
1532    /**
1533     * Get stats data for this site
1534     *
1535     * @since 4.1.0
1536     *
1537     * @param WP_REST_Request $request {
1538     *     Array of parameters received by request.
1539     *
1540     *     @type string $date Date range to restrict results to.
1541     * }
1542     *
1543     * @return WP_Error|WP_HTTP_Response|WP_REST_Response Stats information relayed from WordPress.com.
1544     */
1545    public function get_stats_data( WP_REST_Request $request ) {
1546        // Get parameters to fetch Stats data.
1547        $range = $request->get_param( 'range' );
1548
1549        // If no parameters were passed.
1550        if (
1551            empty( $range )
1552            || ! in_array( $range, array( 'day', 'week', 'month' ), true )
1553        ) {
1554            $range = 'day';
1555        }
1556
1557        $wpcom_stats = new WPCOM_Stats();
1558        switch ( $range ) {
1559
1560            // This is always called first on page load.
1561            case 'day':
1562                $initial_stats = $wpcom_stats->convert_stats_array_to_object( $wpcom_stats->get_stats() );
1563                return rest_ensure_response(
1564                    array(
1565                        'general' => $initial_stats,
1566
1567                        // Build data for 'day' as if it was $wpcom_stats ->get_visits( array( 'unit' => 'day, 'quantity' => 30).
1568                        'day'     => $initial_stats->visits ?? array(),
1569                    )
1570                );
1571            case 'week':
1572                return rest_ensure_response(
1573                    array(
1574                        'week' => $wpcom_stats->convert_stats_array_to_object(
1575                            $wpcom_stats->get_visits(
1576                                array(
1577                                    'unit'     => 'week',
1578                                    'quantity' => 14,
1579                                )
1580                            )
1581                        ),
1582                    )
1583                );
1584            case 'month':
1585                return rest_ensure_response(
1586                    array(
1587                        'month' => $wpcom_stats->convert_stats_array_to_object(
1588                            $wpcom_stats->get_visits(
1589                                array(
1590                                    'unit'     => 'month',
1591                                    'quantity' => 12,
1592                                )
1593                            )
1594                        ),
1595                    )
1596                );
1597        }
1598    }
1599
1600    /**
1601     * Get date of last downtime.
1602     *
1603     * @since 4.3.0
1604     *
1605     * @return mixed|WP_Error Number of days since last downtime. Otherwise, a WP_Error instance with the corresponding error.
1606     */
1607    public function get_monitor_data() {
1608        if ( ! Jetpack::is_module_active( 'monitor' ) ) {
1609            return new WP_Error(
1610                'not_active',
1611                esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ),
1612                array( 'status' => 404 )
1613            );
1614        }
1615
1616        $monitor       = new Jetpack_Monitor();
1617        $last_downtime = $monitor->monitor_get_last_downtime();
1618        if ( is_wp_error( $last_downtime ) ) {
1619            return $last_downtime;
1620        } elseif ( false === strtotime( $last_downtime ) ) {
1621            return rest_ensure_response(
1622                array(
1623                    'code' => 'success',
1624                    'date' => null,
1625                )
1626            );
1627        } else {
1628            return rest_ensure_response(
1629                array(
1630                    'code' => 'success',
1631                    'date' => human_time_diff( strtotime( $last_downtime ), strtotime( 'now' ) ),
1632                )
1633            );
1634        }
1635    }
1636
1637    /**
1638     * Get services that this site is verified with.
1639     *
1640     * @since 4.3.0
1641     *
1642     * @return mixed|WP_Error List of services that verified this site. Otherwise, a WP_Error instance with the corresponding error.
1643     */
1644    public function get_verification_tools_data() {
1645        if ( ! Jetpack::is_module_active( 'verification-tools' ) ) {
1646            return new WP_Error(
1647                'not_active',
1648                esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ),
1649                array( 'status' => 404 )
1650            );
1651        }
1652
1653        $verification_services_codes = get_option( 'verification_services_codes' );
1654        if (
1655            ! is_array( $verification_services_codes )
1656            || empty( $verification_services_codes )
1657        ) {
1658            return new WP_Error(
1659                'empty',
1660                esc_html__( 'Site not verified with any service.', 'jetpack' ),
1661                array( 'status' => 404 )
1662            );
1663        }
1664
1665        $services = array();
1666        foreach ( jetpack_verification_services() as $name => $service ) {
1667            if ( is_array( $service ) && ! empty( $verification_services_codes[ $name ] ) ) {
1668                switch ( $name ) {
1669                    case 'google':
1670                        $services[] = 'Google';
1671                        break;
1672                    case 'bing':
1673                        $services[] = 'Bing';
1674                        break;
1675                    case 'pinterest':
1676                        $services[] = 'Pinterest';
1677                        break;
1678                    case 'yandex':
1679                        $services[] = 'Yandex';
1680                        break;
1681                    case 'facebook':
1682                        $services[] = 'Facebook';
1683                        break;
1684                }
1685            }
1686        }
1687
1688        if ( empty( $services ) ) {
1689            return new WP_Error(
1690                'empty',
1691                esc_html__( 'Site not verified with any service.', 'jetpack' ),
1692                array( 'status' => 404 )
1693            );
1694        }
1695
1696        if ( 2 > count( $services ) ) {
1697            $message = esc_html(
1698                sprintf(
1699                    /* translators: %s is a service name like Google, Bing, Pinterest, etc. */
1700                    __( 'Your site is verified with %s.', 'jetpack' ),
1701                    $services[0]
1702                )
1703            );
1704        } else {
1705            $copy_services = $services;
1706            $last          = count( $copy_services ) - 1;
1707            $last_service  = $copy_services[ $last ];
1708            unset( $copy_services[ $last ] );
1709            $message = esc_html(
1710                sprintf(
1711                    /* translators: %1$s is a comma-separated list of services, and %2$s is a single service name like Google, Bing, Pinterest, etc. */
1712                    __( 'Your site is verified with %1$s and %2$s.', 'jetpack' ),
1713                    implode( ', ', $copy_services ),
1714                    $last_service
1715                )
1716            );
1717        }
1718
1719        return rest_ensure_response(
1720            array(
1721                'code'     => 'success',
1722                'message'  => $message,
1723                'services' => $services,
1724            )
1725        );
1726    }
1727
1728    /**
1729     * Get VaultPress site data including, among other things, the date of the last backup if it was completed.
1730     *
1731     * @since 4.3.0
1732     *
1733     * @return mixed|WP_Error VaultPress site data. Otherwise, a WP_Error instance with the corresponding error.
1734     */
1735    public function get_vaultpress_data() {
1736        if ( ! class_exists( 'VaultPress' ) ) {
1737            return new WP_Error(
1738                'not_active',
1739                esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ),
1740                array( 'status' => 404 )
1741            );
1742        }
1743
1744        $vaultpress = new VaultPress();
1745        if ( ! $vaultpress->is_registered() ) {
1746            return rest_ensure_response(
1747                array(
1748                    'code'    => 'not_registered',
1749                    'message' => esc_html__( 'You need to register for VaultPress.', 'jetpack' ),
1750                )
1751            );
1752        }
1753
1754        $data = json_decode( base64_decode( $vaultpress->contact_service( 'plugin_data' ) ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
1755        if ( false === $data ) {
1756            return rest_ensure_response(
1757                array(
1758                    'code'    => 'not_registered',
1759                    'message' => esc_html__( 'Could not connect to VaultPress.', 'jetpack' ),
1760                )
1761            );
1762        } elseif ( is_wp_error( $data ) || ! isset( $data->backups->last_backup ) ) {
1763            return $data;
1764        } elseif ( empty( $data->backups->last_backup ) ) {
1765            return rest_ensure_response(
1766                array(
1767                    'code'    => 'success',
1768                    'message' => esc_html__( 'VaultPress is active and will back up your site soon.', 'jetpack' ),
1769                    'data'    => $data,
1770                )
1771            );
1772        } else {
1773            return rest_ensure_response(
1774                array(
1775                    'code'    => 'success',
1776                    'message' => esc_html(
1777                        sprintf(
1778                            /* translators: placeholder is a unit of time (1 hour, 5 days, ...) */
1779                            esc_html__( 'Your site was successfully backed up %s ago.', 'jetpack' ),
1780                            human_time_diff(
1781                                $data->backups->last_backup,
1782                                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.
1783                            )
1784                        )
1785                    ),
1786                    'data'    => $data,
1787                )
1788            );
1789        }
1790    }
1791
1792    /**
1793     * A WordPress REST API permission callback method that accepts a request object and
1794     * decides if the current user has enough privileges to act.
1795     *
1796     * @since 4.3.0
1797     *
1798     * @return bool does a current user have enough privileges.
1799     */
1800    public function can_request() {
1801        return current_user_can( 'jetpack_admin_page' );
1802    }
1803}
1804
1805// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move these functions to some other file.
1806
1807/**
1808 * Actions performed only when Gravatar Hovercards is activated through the endpoint call.
1809 *
1810 * @since 4.3.1
1811 */
1812function jetpack_do_after_gravatar_hovercards_activation() {
1813
1814    // When Gravatar Hovercards is activated, enable them automatically.
1815    update_option( 'gravatar_disable_hovercards', 'enabled' );
1816}
1817add_action( 'jetpack_activate_module_gravatar-hovercards', 'jetpack_do_after_gravatar_hovercards_activation' );
1818
1819/**
1820 * Actions performed only when Gravatar Hovercards is activated through the endpoint call.
1821 *
1822 * @since 4.3.1
1823 */
1824function jetpack_do_after_gravatar_hovercards_deactivation() {
1825
1826    // When Gravatar Hovercards is deactivated, disable them automatically.
1827    update_option( 'gravatar_disable_hovercards', 'disabled' );
1828}
1829add_action( 'jetpack_deactivate_module_gravatar-hovercards', 'jetpack_do_after_gravatar_hovercards_deactivation' );
1830
1831/**
1832 * Actions performed only when Markdown is activated through the endpoint call.
1833 *
1834 * @since 4.7.0
1835 */
1836function jetpack_do_after_markdown_activation() {
1837
1838    // When Markdown is activated, enable support for post editing automatically.
1839    update_option( 'wpcom_publish_posts_with_markdown', true );
1840}
1841add_action( 'jetpack_activate_module_markdown', 'jetpack_do_after_markdown_activation' );