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