Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
49.40% covered (danger)
49.40%
450 / 911
17.65% covered (danger)
17.65%
3 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_JSON_API_Site_Settings_Endpoint
57.92% covered (warning)
57.92%
450 / 777
17.65% covered (danger)
17.65%
3 / 17
6209.59
0.00% covered (danger)
0.00%
0 / 1
 callback
62.50% covered (warning)
62.50%
10 / 16
0.00% covered (danger)
0.00%
0 / 1
11.38
 wpcom_restapi_copy_theme_plugin_actions
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 jetpack_relatedposts_supported
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 get_category_details
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_cast_option_value_or_null
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_settings_response
90.87% covered (success)
90.87%
189 / 208
0.00% covered (danger)
0.00%
0 / 1
36.99
 get_wpcom_gifting_subscription_default
15.38% covered (danger)
15.38%
2 / 13
0.00% covered (danger)
0.00%
0 / 1
58.07
 get_subscription_options_in_user_locale
63.64% covered (warning)
63.64%
7 / 11
0.00% covered (danger)
0.00%
0 / 1
3.43
 get_all_site_mcp_abilities
44.44% covered (danger)
44.44%
4 / 9
0.00% covered (danger)
0.00%
0 / 1
2.69
 get_mcp_abilities_metadata
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
2.15
 get_site_mcp_abilities
90.00% covered (success)
90.00%
18 / 20
0.00% covered (danger)
0.00%
0 / 1
5.03
 set_site_mcp_abilities
68.42% covered (warning)
68.42%
13 / 19
0.00% covered (danger)
0.00%
0 / 1
7.13
 get_locale
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 update_settings
41.90% covered (danger)
41.90%
181 / 432
0.00% covered (danger)
0.00%
0 / 1
7575.99
 get_subscriptions_reply_to_option
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 is_valid_page_id
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 get_highlander_comment_form_prompt_option
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Manage settings via the WordPress.com REST API.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Waf\Brute_Force_Protection\Brute_Force_Protection_Shared_Functions;
9
10if ( ! defined( 'ABSPATH' ) ) {
11    exit( 0 );
12}
13
14require_once dirname( __DIR__ ) . '/modules/verification-tools/verification-tools-utils.php';
15
16new WPCOM_JSON_API_Site_Settings_Endpoint(
17    array(
18        'description'      => 'Get detailed settings information about a site.',
19        'group'            => '__do_not_document',
20        'stat'             => 'sites:X',
21        'max_version'      => '1.1',
22        'new_version'      => '1.2',
23        'method'           => 'GET',
24        'path'             => '/sites/%s/settings',
25        'path_labels'      => array(
26            '$site' => '(int|string) Site ID or domain',
27        ),
28
29        'query_parameters' => array(
30            'context' => false,
31        ),
32
33        'response_format'  => WPCOM_JSON_API_Site_Settings_Endpoint::$site_format,
34
35        'example_request'  => 'https://public-api.wordpress.com/rest/v1/sites/en.blog.wordpress.com/settings',
36    )
37);
38
39new WPCOM_JSON_API_Site_Settings_Endpoint(
40    array(
41        'description'         => 'Update settings for a site.',
42        'group'               => '__do_not_document',
43        'stat'                => 'sites:X',
44        'max_version'         => '1.1',
45        'new_version'         => '1.2',
46        'method'              => 'POST',
47        'path'                => '/sites/%s/settings',
48        'a_new_very_long_key' => 'blabla',
49        'path_labels'         => array(
50            '$site' => '(int|string) Site ID or domain',
51        ),
52
53        'request_format'      => array(
54            'migration_source_site_domain'              => '(string) The source site URL, from the migration flow',
55            'in_site_migration_flow'                    => '(string) The migration flow the site is in',
56            'blogname'                                  => '(string) Blog name',
57            'blogdescription'                           => '(string) Blog description',
58            'default_pingback_flag'                     => '(bool) Notify blogs linked from article?',
59            'default_ping_status'                       => '(bool) Allow link notifications from other blogs?',
60            'default_comment_status'                    => '(bool) Allow comments on new articles?',
61            'blog_public'                               => '(string) Site visibility; -1: private, 0: discourage search engines, 1: allow search engines',
62            'wpcom_data_sharing_opt_out'                => '(bool) Did the site opt out of sharing public content with third parties and research partners?',
63            'jetpack_sync_non_public_post_stati'        => '(bool) allow sync of post and pages with non-public posts stati',
64            'jetpack_relatedposts_enabled'              => '(bool) Enable related posts?',
65            'jetpack_relatedposts_show_context'         => '(bool) Show post\'s tags and category in related posts?',
66            'jetpack_relatedposts_show_date'            => '(bool) Show date in related posts?',
67            'jetpack_relatedposts_show_headline'        => '(bool) Show headline in related posts?',
68            'jetpack_relatedposts_show_thumbnails'      => '(bool) Show thumbnails in related posts?',
69            'jetpack_protect_whitelist'                 => '(array) List of IP addresses to always allow',
70            'instant_search_enabled'                    => '(bool) Enable the new Jetpack Instant Search interface',
71            'jetpack_search_enabled'                    => '(bool) Enable Jetpack Search',
72            'jetpack_search_supported'                  => '(bool) Jetpack Search is supported',
73            'infinite_scroll'                           => '(bool) Support infinite scroll of posts?',
74            'default_category'                          => '(int) Default post category',
75            'default_post_format'                       => '(string) Default post format',
76            'require_name_email'                        => '(bool) Require comment authors to fill out name and email?',
77            'comment_registration'                      => '(bool) Require users to be registered and logged in to comment?',
78            'close_comments_for_old_posts'              => '(bool) Automatically close comments on old posts?',
79            'close_comments_days_old'                   => '(int) Age at which to close comments',
80            'thread_comments'                           => '(bool) Enable threaded comments?',
81            'thread_comments_depth'                     => '(int) Depth to thread comments',
82            'page_comments'                             => '(bool) Break comments into pages?',
83            'comments_per_page'                         => '(int) Number of comments to display per page',
84            'default_comments_page'                     => '(string) newest|oldest Which page of comments to display first',
85            'comment_order'                             => '(string) asc|desc Order to display comments within page',
86            'comments_notify'                           => '(bool) Email me when someone comments?',
87            'moderation_notify'                         => '(bool) Email me when a comment is helf for moderation?',
88            'social_notifications_like'                 => '(bool) Email me when someone likes my post?',
89            'social_notifications_reblog'               => '(bool) Email me when someone reblogs my post?',
90            'social_notifications_subscribe'            => '(bool) Email me when someone subscribes to my blog?',
91            'comment_moderation'                        => '(bool) Moderate comments for manual approval?',
92            'comment_previously_approved'               => '(bool) Moderate comments unless author has a previously-approved comment?',
93            'comment_max_links'                         => '(int) Moderate comments that contain X or more links',
94            'moderation_keys'                           => '(string) Words or phrases that trigger comment moderation, one per line',
95            'disallowed_keys'                           => '(string) Words or phrases that mark comment spam, one per line',
96            'lang_id'                                   => '(int) ID for language blog is written in',
97            'wga'                                       => '(array) Google Analytics Settings',
98            'disabled_likes'                            => '(bool) Are likes globally disabled (they can still be turned on per post)?',
99            'disabled_reblogs'                          => '(bool) Are reblogs disabled on posts?',
100            'jetpack_comment_likes_enabled'             => '(bool) Are comment likes enabled for all comments?',
101            'sharing_button_style'                      => '(string) Style to use for sharing buttons (icon-text, icon, text, or official)',
102            'sharing_label'                             => '(string) Label to use for sharing buttons, e.g. "Share this:"',
103            'sharing_show'                              => '(string|array:string) Post type or array of types where sharing buttons are to be displayed',
104            'sharing_open_links'                        => '(string) Link target for sharing buttons (same or new)',
105            'twitter_via'                               => '(string) Twitter username to include in tweets when people share using the Twitter button',
106            'jetpack-twitter-cards-site-tag'            => '(string) The Twitter username of the owner of the site\'s domain.',
107            'eventbrite_api_token'                      => '(int) The Keyring token ID for an Eventbrite token to associate with the site',
108            'timezone_string'                           => '(string) PHP-compatible timezone string like \'UTC-5\'',
109            'gmt_offset'                                => '(int) Site offset from UTC in hours',
110            'date_format'                               => '(string) PHP Date-compatible date format',
111            'time_format'                               => '(string) PHP Date-compatible time format',
112            'start_of_week'                             => '(int) Starting day of week (0 = Sunday, 6 = Saturday)',
113            'jetpack_testimonial'                       => '(bool) Whether testimonial custom post type is enabled for the site',
114            'jetpack_testimonial_posts_per_page'        => '(int) Number of testimonials to show per page',
115            'jetpack_portfolio'                         => '(bool) Whether portfolio custom post type is enabled for the site',
116            'jetpack_portfolio_posts_per_page'          => '(int) Number of portfolio projects to show per page',
117            Jetpack_SEO_Utils::FRONT_PAGE_META_OPTION   => '(string) The seo meta description for the site.',
118            Jetpack_SEO_Titles::TITLE_FORMATS_OPTION    => '(array) SEO meta title formats. Allowed keys: front_page, posts, pages, groups, archives',
119            'verification_services_codes'               => '(array) Website verification codes. Allowed keys: google, pinterest, bing, yandex, facebook',
120            'markdown_supported'                        => '(bool) Whether markdown is supported for this site',
121            'wpcom_publish_posts_with_markdown'         => '(bool) Whether markdown is enabled for posts',
122            'wpcom_publish_comments_with_markdown'      => '(bool) Whether markdown is enabled for comments',
123            'site_icon'                                 => '(int) Media attachment ID to use as site icon. Set to zero or an otherwise empty value to clear',
124            'api_cache'                                 => '(bool) Turn on/off the Jetpack JSON API cache',
125            'posts_per_page'                            => '(int) Number of posts to show on blog pages',
126            'posts_per_rss'                             => '(int) Number of posts to show in the RSS feed',
127            'rss_use_excerpt'                           => '(bool) Whether the RSS feed will use post excerpts',
128            'launchpad_screen'                          => '(string) Whether or not launchpad is presented and what size it will be',
129            'sm_enabled'                                => '(bool) Whether the newsletter subscribe modal is enabled',
130            'jetpack_subscribe_overlay_enabled'         => '(bool) Whether the newsletter subscribe overlay is enabled',
131            'jetpack_subscribe_floating_button_enabled' => '(bool) Whether the newsletter floating subscribe button is enabled',
132            'jetpack_subscriptions_subscribe_post_end_enabled' => '(bool) Whether the Subscribe block at the end of each post placement is enabled',
133            'jetpack_subscriptions_login_navigation_enabled' => '(bool) Whether the Subscriber Login block navigation placement is enabled',
134            'jetpack_subscriptions_subscribe_navigation_enabled' => '(Bool) Whether the Subscribe block navigation placement is enabled',
135            'wpcom_ai_site_prompt'                      => '(string) User input in the AI site prompt',
136            'jetpack_waf_automatic_rules'               => '(bool) Whether the WAF should enforce automatic firewall rules',
137            'jetpack_waf_ip_allow_list'                 => '(string) List of IP addresses to always allow',
138            'jetpack_waf_ip_allow_list_enabled'         => '(bool) Whether the IP allow list is enabled',
139            'jetpack_waf_ip_block_list'                 => '(string) List of IP addresses the WAF should always block',
140            'jetpack_waf_ip_block_list_enabled'         => '(bool) Whether the IP block list is enabled',
141            'jetpack_waf_share_data'                    => '(bool) Whether the WAF should share basic data with Jetpack',
142            'jetpack_waf_share_debug_data'              => '(bool) Whether the WAF should share debug data with Jetpack',
143            'jetpack_waf_automatic_rules_last_updated_timestamp' => '(int) Timestamp of the last time the automatic rules were updated',
144            'mcp_abilities'                             => '(array) List of MCP Abilities',
145        ),
146
147        'response_format'     => array(
148            'updated' => '(array)',
149        ),
150
151        'example_request'     => 'https://public-api.wordpress.com/rest/v1/sites/en.blog.wordpress.com/settings',
152    )
153);
154
155/**
156 * Manage Site settings endpoint.
157 *
158 * @phan-constructor-used-for-side-effects
159 */
160class WPCOM_JSON_API_Site_Settings_Endpoint extends WPCOM_JSON_API_Endpoint {
161
162    /**
163     * Site format.
164     *
165     * @var array
166     */
167    public static $site_format = array(
168        'ID'             => '(int) Site ID',
169        'name'           => '(string) Title of site',
170        'description'    => '(string) Tagline or description of site',
171        'URL'            => '(string) Full URL to the site',
172        'lang'           => '(string) Primary language code of the site',
173        'locale_variant' => '(string) Locale variant code for the site, if set',
174        'settings'       => '(array) An array of options/settings for the blog. Only viewable by users with post editing rights to the site.',
175    );
176
177    /**
178     * Endpoint response
179     *
180     * GET /sites/%s/settings
181     * POST /sites/%s/settings
182     *
183     * @param string $path    Path.
184     * @param int    $blog_id Blog ID.
185     */
186    public function callback( $path = '', $blog_id = 0 ) {
187        $blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
188        if ( is_wp_error( $blog_id ) ) {
189            return $blog_id;
190        }
191
192        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
193            // Source & include the infinite scroll compatibility files prior to loading theme functions.
194            add_filter( 'restapi_theme_action_copy_dirs', array( 'WPCOM_JSON_API_Site_Settings_Endpoint', 'wpcom_restapi_copy_theme_plugin_actions' ) );
195            $this->load_theme_functions();
196        }
197
198        if ( ! is_user_logged_in() ) {
199            return new WP_Error( 'Unauthorized', 'You must be logged-in to manage settings.', 401 );
200        } elseif ( ! current_user_can( 'manage_options' ) ) {
201            return new WP_Error( 'Forbidden', 'You do not have the capability to manage settings for this site.', 403 );
202        }
203
204        if ( 'GET' === $this->api->method ) {
205            /**
206             * Fires on each GET request to a specific endpoint.
207             *
208             * @module json-api
209             *
210             * @since 3.2.0
211             *
212             * @param string sites.
213             */
214            do_action( 'wpcom_json_api_objects', 'sites' );
215            return $this->get_settings_response();
216        } elseif ( 'POST' === $this->api->method ) {
217            return $this->update_settings();
218        } else {
219            return new WP_Error( 'bad_request', 'An unsupported request method was used.' );
220        }
221    }
222
223    /**
224     * Includes additional theme-specific files to be included in REST API theme
225     * context loading action copying.
226     *
227     * @see WPCOM_JSON_API_Endpoint#load_theme_functions
228     * @see the_neverending_home_page_theme_support
229     *
230     * @param array $copy_dirs Array of files to be included in theme context.
231     */
232    public static function wpcom_restapi_copy_theme_plugin_actions( $copy_dirs ) {
233        $theme_name        = get_stylesheet();
234        $default_file_name = WP_CONTENT_DIR . "/mu-plugins/infinity/themes/{$theme_name}.php";
235
236        /**
237         * Filter the path to the Infinite Scroll compatibility file.
238         *
239         * @module infinite-scroll
240         *
241         * @since 2.0.0
242         *
243         * @param string $str IS compatibility file path.
244         * @param string $theme_name Theme name.
245         */
246        $customization_file = apply_filters( 'infinite_scroll_customization_file', $default_file_name, $theme_name );
247
248        if ( is_readable( $customization_file ) ) {
249            require_once $customization_file;
250            $copy_dirs[] = $customization_file;
251        }
252
253        return $copy_dirs;
254    }
255
256    /**
257     * Determines whether jetpack_relatedposts is supported
258     *
259     * @return bool
260     */
261    public function jetpack_relatedposts_supported() {
262        $wpcom_related_posts_theme_blacklist = array(
263            'Expound',
264            'Traveler',
265            'Opti',
266            'Currents',
267        );
268        return ( ! in_array( wp_get_theme()->get( 'Name' ), $wpcom_related_posts_theme_blacklist, true ) );
269    }
270
271    /**
272     * Returns category details
273     *
274     * @param WP_Term $category Category object.
275     *
276     * @return array
277     */
278    public function get_category_details( $category ) {
279        return array(
280            'value' => $category->term_id,
281            'name'  => $category->name,
282        );
283    }
284
285    /**
286     * Returns an option value as the result of the callable being applied to
287     * it if a value is set, otherwise null.
288     *
289     * @param string   $option_name   Option name.
290     * @param callable $cast_callable Callable to invoke on option value.
291     *
292     * @return int|null Numeric option value or null.
293     */
294    protected function get_cast_option_value_or_null( $option_name, $cast_callable ) {
295        $option_value = get_option( $option_name, null );
296        if ( $option_value === null ) {
297            return $option_value;
298        }
299
300        return call_user_func( $cast_callable, $option_value );
301    }
302
303    /**
304     * Collects the necessary information to return for a get settings response.
305     *
306     * @return array
307     */
308    public function get_settings_response() {
309        $response = array();
310
311        // Allow update in later versions.
312        /**
313         * Filter the structure of site settings to return.
314         *
315         * @module json-api
316         *
317         * @since 3.9.3
318         *
319         * @param array $site_format Data structure.
320         */
321        $response_format = apply_filters( 'site_settings_site_format', self::$site_format );
322
323        $blog_id = (int) $this->api->get_blog_id_for_output();
324        $site    = $this->get_platform()->get_site( $blog_id );
325
326        foreach ( array_keys( $response_format ) as $key ) {
327
328            // refactoring to change lang parameter to locale in 1.2.
329            $lang_or_locale = $this->get_locale( $key );
330            if ( $lang_or_locale ) {
331                $response[ $key ] = $lang_or_locale;
332                continue;
333            }
334
335            switch ( $key ) {
336                case 'ID':
337                    $response[ $key ] = $blog_id;
338                    break;
339                case 'name':
340                    $name             = get_bloginfo( 'name' );
341                    $response[ $key ] = is_string( $name ) ? htmlspecialchars_decode( $name, ENT_QUOTES ) : '';
342                    break;
343                case 'description':
344                    $description      = get_bloginfo( 'description' );
345                    $response[ $key ] = is_string( $description ) ? htmlspecialchars_decode( $description, ENT_QUOTES ) : '';
346                    break;
347                case 'URL':
348                    $response[ $key ] = (string) home_url();
349                    break;
350                case 'locale_variant':
351                    if ( function_exists( 'wpcom_l10n_get_blog_locale_variant' ) ) {
352                        $blog_locale_variant = wpcom_l10n_get_blog_locale_variant();
353                        if ( $blog_locale_variant ) {
354                            $response[ $key ] = $blog_locale_variant;
355                        }
356                    }
357                    break;
358                case 'settings':
359                    $jetpack_relatedposts_options = Jetpack_Options::get_option( 'relatedposts', array() );
360                    // If the option's enabled key is NOT SET, it is considered enabled by the plugin.
361                    if ( ! isset( $jetpack_relatedposts_options['enabled'] ) ) {
362                        $jetpack_relatedposts_options['enabled'] = true;
363                    }
364
365                    $jetpack_relatedposts_options['enabled'] =
366                        $jetpack_relatedposts_options['enabled']
367                        && $site->is_module_active( 'related-posts' );
368
369                    $jetpack_search_supported = false;
370                    if ( function_exists( 'wpcom_is_jetpack_search_supported' ) ) {
371                        $jetpack_search_supported = wpcom_is_jetpack_search_supported( $blog_id );
372                    }
373
374                    $jetpack_search_active =
375                        $jetpack_search_supported
376                        && $site->is_module_active( 'search' );
377
378                    // array_values() is necessary to ensure the array starts at index 0.
379                    $post_categories = array_values(
380                        array_map(
381                            array( $this, 'get_category_details' ),
382                            get_categories( array( 'hide_empty' => false ) )
383                        )
384                    );
385
386                    // Make sure we are returning a consistent type
387                    if ( ! class_exists( 'Jetpack_Newsletter_Category_Helper' ) ) {
388                        require_once JETPACK__PLUGIN_DIR . '_inc/lib/class-jetpack-newsletter-category-helper.php';
389                    }
390                    $newsletter_category_ids = Jetpack_Newsletter_Category_Helper::get_category_ids();
391
392                    $api_cache = $site->is_jetpack() ? (bool) get_option( 'jetpack_api_cache_enabled' ) : true;
393
394                    // Get Sites MCP settings
395                    $mcp_abilities = $this->get_site_mcp_abilities();
396
397                    $response[ $key ] = array(
398                        // also exists as "options".
399                        'admin_url'                        => get_admin_url(),
400                        'default_ping_status'              => 'closed' !== get_option( 'default_ping_status' ),
401                        'default_comment_status'           => 'closed' !== get_option( 'default_comment_status' ),
402
403                        // new stuff starts here.
404                        'instant_search_enabled'           => (bool) get_option( 'instant_search_enabled' ),
405                        'blog_public'                      => (int) get_option( 'blog_public' ),
406                        'wpcom_data_sharing_opt_out'       => (bool) get_option( 'wpcom_data_sharing_opt_out' ),
407                        'jetpack_sync_non_public_post_stati' => (bool) Jetpack_Options::get_option( 'sync_non_public_post_stati' ),
408                        'jetpack_relatedposts_allowed'     => (bool) $this->jetpack_relatedposts_supported(),
409                        'jetpack_relatedposts_enabled'     => (bool) $jetpack_relatedposts_options['enabled'],
410                        'jetpack_relatedposts_show_context' => ! empty( $jetpack_relatedposts_options['show_context'] ),
411                        'jetpack_relatedposts_show_date'   => ! empty( $jetpack_relatedposts_options['show_date'] ),
412                        'jetpack_relatedposts_show_headline' => ! empty( $jetpack_relatedposts_options['show_headline'] ),
413                        'jetpack_relatedposts_show_thumbnails' => ! empty( $jetpack_relatedposts_options['show_thumbnails'] ),
414                        'jetpack_search_enabled'           => $jetpack_search_active,
415                        'jetpack_search_supported'         => (bool) $jetpack_search_supported,
416                        'default_category'                 => (int) get_option( 'default_category' ),
417                        'post_categories'                  => (array) $post_categories,
418                        'default_post_format'              => get_option( 'default_post_format' ),
419                        'default_pingback_flag'            => (bool) get_option( 'default_pingback_flag' ),
420                        'require_name_email'               => (bool) get_option( 'require_name_email' ),
421                        'comment_registration'             => (bool) get_option( 'comment_registration' ),
422                        'close_comments_for_old_posts'     => (bool) get_option( 'close_comments_for_old_posts' ),
423                        'close_comments_days_old'          => (int) get_option( 'close_comments_days_old' ),
424                        'thread_comments'                  => (bool) get_option( 'thread_comments' ),
425                        'thread_comments_depth'            => (int) get_option( 'thread_comments_depth' ),
426                        'page_comments'                    => (bool) get_option( 'page_comments' ),
427                        'comments_per_page'                => (int) get_option( 'comments_per_page' ),
428                        'default_comments_page'            => get_option( 'default_comments_page' ),
429                        'comment_order'                    => get_option( 'comment_order' ),
430                        'comments_notify'                  => (bool) get_option( 'comments_notify' ),
431                        'moderation_notify'                => (bool) get_option( 'moderation_notify' ),
432                        'social_notifications_like'        => ( 'on' === get_option( 'social_notifications_like' ) ),
433                        'social_notifications_reblog'      => ( 'on' === get_option( 'social_notifications_reblog' ) ),
434                        'social_notifications_subscribe'   => ( 'on' === get_option( 'social_notifications_subscribe' ) ),
435                        'comment_moderation'               => (bool) get_option( 'comment_moderation' ),
436                        'comment_whitelist'                => (bool) get_option( 'comment_previously_approved' ),
437                        'comment_previously_approved'      => (bool) get_option( 'comment_previously_approved' ),
438                        'comment_max_links'                => (int) get_option( 'comment_max_links' ),
439                        'moderation_keys'                  => get_option( 'moderation_keys' ),
440                        'blacklist_keys'                   => get_option( 'disallowed_keys' ),
441                        'disallowed_keys'                  => get_option( 'disallowed_keys' ),
442                        'lang_id'                          => defined( 'IS_WPCOM' ) && IS_WPCOM
443                        ? get_lang_id_by_code( wpcom_l10n_get_blog_locale_variant( $blog_id, true ) )
444                        : get_option( 'lang_id' ),
445                        'site_vertical_id'                 => (string) get_option( 'site_vertical_id' ),
446                        'jetpack_cloudflare_analytics'     => get_option( 'jetpack_cloudflare_analytics' ),
447                        'disabled_likes'                   => (bool) get_option( 'disabled_likes' ),
448                        'disabled_reblogs'                 => (bool) get_option( 'disabled_reblogs' ),
449                        'jetpack_comment_likes_enabled'    => (bool) get_option( 'jetpack_comment_likes_enabled', false ),
450                        'twitter_via'                      => (string) get_option( 'twitter_via' ),
451                        'jetpack-twitter-cards-site-tag'   => (string) get_option( 'jetpack-twitter-cards-site-tag' ),
452                        'eventbrite_api_token'             => $this->get_cast_option_value_or_null( 'eventbrite_api_token', 'intval' ),
453                        'gmt_offset'                       => get_option( 'gmt_offset' ),
454                        'timezone_string'                  => get_option( 'timezone_string' ),
455                        'date_format'                      => get_option( 'date_format' ),
456                        'time_format'                      => get_option( 'time_format' ),
457                        'start_of_week'                    => get_option( 'start_of_week' ),
458                        'woocommerce_onboarding_profile'   => (array) get_option( 'woocommerce_onboarding_profile', array() ),
459                        'woocommerce_store_address'        => (string) get_option( 'woocommerce_store_address' ),
460                        'woocommerce_store_address_2'      => (string) get_option( 'woocommerce_store_address_2' ),
461                        'woocommerce_store_city'           => (string) get_option( 'woocommerce_store_city' ),
462                        'woocommerce_default_country'      => (string) get_option( 'woocommerce_default_country' ),
463                        'woocommerce_store_postcode'       => (string) get_option( 'woocommerce_store_postcode' ),
464                        'jetpack_testimonial'              => (bool) get_option( 'jetpack_testimonial', '0' ),
465                        'jetpack_testimonial_posts_per_page' => (int) get_option( 'jetpack_testimonial_posts_per_page', '10' ),
466                        'jetpack_portfolio'                => (bool) get_option( 'jetpack_portfolio', '0' ),
467                        'jetpack_portfolio_posts_per_page' => (int) get_option( 'jetpack_portfolio_posts_per_page', '10' ),
468                        'markdown_supported'               => true,
469                        'site_icon'                        => $this->get_cast_option_value_or_null( 'site_icon', 'intval' ),
470                        Jetpack_SEO_Utils::FRONT_PAGE_META_OPTION => get_option( Jetpack_SEO_Utils::FRONT_PAGE_META_OPTION, '' ),
471                        Jetpack_SEO_Titles::TITLE_FORMATS_OPTION => get_option( Jetpack_SEO_Titles::TITLE_FORMATS_OPTION, array() ),
472                        'verification_services_codes'      => get_option( 'verification_services_codes', null ),
473                        'api_cache'                        => $api_cache,
474                        'posts_per_page'                   => (int) get_option( 'posts_per_page' ),
475                        'posts_per_rss'                    => (int) get_option( 'posts_per_rss' ),
476                        'rss_use_excerpt'                  => (bool) get_option( 'rss_use_excerpt' ),
477                        'launchpad_screen'                 => (string) get_option( 'launchpad_screen' ),
478                        'wpcom_newsletter_send_default'    => (bool) get_option( 'wpcom_newsletter_send_default', true ),
479                        'wpcom_featured_image_in_email'    => ( function () use ( $site ) {
480                            if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
481                                $registered_date = method_exists( $site, 'get_registered_date' ) ? $site->get_registered_date() : '';
482                                // Compare to May 2, 2025 (ISO 8601 format)
483                                if ( $registered_date && $registered_date !== '0000-00-00T00:00:00+00:00' && strtotime( $registered_date ) >= strtotime( '2025-05-02T00:00:00+00:00' ) ) {
484                                    return (bool) get_option( 'wpcom_featured_image_in_email', true );
485                                }
486                            }
487                            // For all other sites, use the saved value or default to false for legacy behavior.
488                            return (bool) get_option( 'wpcom_featured_image_in_email', false );
489                        } )(),
490                        'jetpack_gravatar_in_email'        => (bool) get_option( 'jetpack_gravatar_in_email', true ),
491                        'jetpack_author_in_email'          => (bool) get_option( 'jetpack_author_in_email', true ),
492                        'jetpack_post_date_in_email'       => (bool) get_option( 'jetpack_post_date_in_email', true ),
493                        'wpcom_newsletter_categories'      => $newsletter_category_ids,
494                        'wpcom_newsletter_categories_enabled' => (bool) get_option( 'wpcom_newsletter_categories_enabled' ),
495                        'sm_enabled'                       => (bool) get_option( 'sm_enabled' ),
496                        'jetpack_subscribe_overlay_enabled' => (bool) get_option( 'jetpack_subscribe_overlay_enabled' ),
497                        'jetpack_subscribe_floating_button_enabled' => (bool) get_option( 'jetpack_subscribe_floating_button_enabled' ),
498                        'jetpack_subscriptions_subscribe_post_end_enabled' => (bool) get_option( 'jetpack_subscriptions_subscribe_post_end_enabled' ),
499                        'jetpack_subscriptions_login_navigation_enabled' => (bool) get_option( 'jetpack_subscriptions_login_navigation_enabled' ),
500                        'jetpack_subscriptions_subscribe_navigation_enabled' => (bool) get_option( 'jetpack_subscriptions_subscribe_navigation_enabled' ),
501                        'wpcom_gifting_subscription'       => (bool) get_option( 'wpcom_gifting_subscription', $this->get_wpcom_gifting_subscription_default() ),
502                        'wpcom_reader_views_enabled'       => (bool) get_option( 'wpcom_reader_views_enabled', true ),
503                        'wpcom_subscription_emails_use_excerpt' => (bool) get_option( 'wpcom_subscription_emails_use_excerpt' ),
504                        'jetpack_subscriptions_reply_to'   => (string) $this->get_subscriptions_reply_to_option(),
505                        'jetpack_subscriptions_from_name'  => (string) get_option( 'jetpack_subscriptions_from_name' ),
506                        'show_on_front'                    => (string) get_option( 'show_on_front' ),
507                        'page_on_front'                    => (string) get_option( 'page_on_front' ),
508                        'page_for_posts'                   => (string) get_option( 'page_for_posts' ),
509                        'subscription_options'             => $this->get_subscription_options_in_user_locale(),
510                        'supports_free_tier_customization' => true,
511                        'jetpack_verbum_subscription_modal' => (bool) get_option( 'jetpack_verbum_subscription_modal', true ),
512                        'enable_verbum_commenting'         => (bool) get_option( 'enable_verbum_commenting', true ),
513                        'enable_blocks_comments'           => (bool) get_option( 'enable_blocks_comments', true ),
514                        'highlander_comment_form_prompt'   => $this->get_highlander_comment_form_prompt_option(),
515                        'jetpack_comment_form_color_scheme' => (string) get_option( 'jetpack_comment_form_color_scheme' ),
516                        'in_site_migration_flow'           => (string) get_option( 'in_site_migration_flow', '' ),
517                        'migration_source_site_domain'     => (string) get_option( 'migration_source_site_domain' ),
518                        'jetpack_waf_automatic_rules'      => (bool) get_option( 'jetpack_waf_automatic_rules' ),
519                        'jetpack_waf_ip_allow_list'        => (string) get_option( 'jetpack_waf_ip_allow_list' ),
520                        'jetpack_waf_ip_allow_list_enabled' => (bool) get_option( 'jetpack_waf_ip_allow_list_enabled' ),
521                        'jetpack_waf_ip_block_list'        => (string) get_option( 'jetpack_waf_ip_block_list' ),
522                        'jetpack_waf_ip_block_list_enabled' => (bool) get_option( 'jetpack_waf_ip_block_list_enabled' ),
523                        'jetpack_waf_share_data'           => (bool) get_option( 'jetpack_waf_share_data' ),
524                        'jetpack_waf_share_debug_data'     => (bool) get_option( 'jetpack_waf_share_debug_data' ),
525                        'jetpack_waf_automatic_rules_last_updated_timestamp' => (int) get_option( 'jetpack_waf_automatic_rules_last_updated_timestamp' ),
526                        'is_fully_managed_agency_site'     => (bool) get_option( 'is_fully_managed_agency_site' ),
527                        'wpcom_hide_action_bar'            => (bool) get_option( 'wpcom_hide_action_bar' ),
528                        'mcp_abilities'                    => $mcp_abilities,
529                    );
530
531                    require_once JETPACK__PLUGIN_DIR . '/modules/memberships/class-jetpack-memberships.php';
532                    if ( class_exists( 'Jetpack_Memberships' ) ) {
533                        $response[ $key ]['newsletter_has_active_plan'] = count( Jetpack_Memberships::get_all_newsletter_plan_ids( false ) ) > 0;
534                        // Read-only/derived: the free tier's markdown description rendered to
535                        // safe HTML, colocated with subscription_options so it's
536                        // read-after-write consistent. Not part of the writable
537                        // subscription_options bag (which would round-trip and persist it).
538                        $response[ $key ]['free_tier_description_rendered'] = Jetpack_Memberships::render_tier_description_html(
539                            ( (array) get_option( 'subscription_options' ) )['free_tier_description'] ?? ''
540                        );
541                    }
542
543                    if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
544                        $response[ $key ]['wpcom_publish_posts_with_markdown']    = (bool) WPCom_Markdown::get_instance()->is_posting_enabled();
545                        $response[ $key ]['wpcom_publish_comments_with_markdown'] = (bool) WPCom_Markdown::get_instance()->is_commenting_enabled();
546
547                        // WPCOM-specific Infinite Scroll Settings.
548                        if ( is_callable( array( 'The_Neverending_Home_Page', 'get_settings' ) ) ) {
549                            /**
550                             * Clear the cached copy of widget info so it's pulled fresh from blog options.
551                             * It was primed during the initial load under the __REST API site__'s context.
552                             *
553                             * @see wp_get_sidebars_widgets https://core.trac.wordpress.org/browser/trunk/src/wp-includes/widgets.php?rev=42374#L931
554                             */
555                            $GLOBALS['_wp_sidebars_widgets'] = array(); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
556
557                            $infinite_scroll_settings            = The_Neverending_Home_Page::get_settings();
558                            $response[ $key ]['infinite_scroll'] = get_option( 'infinite_scroll', true ) && 'scroll' === $infinite_scroll_settings->type;
559                            if ( $infinite_scroll_settings->footer_widgets || 'click' === $infinite_scroll_settings->requested_type ) {
560                                // The blog has footer widgets -- infinite scroll is blocked.
561                                $response[ $key ]['infinite_scroll_blocked'] = 'footer';
562                            } else {
563                                $response[ $key ]['infinite_scroll_blocked'] = false;
564                            }
565                        }
566                    }
567
568                    // allow future versions of this endpoint to support additional settings keys.
569                    /**
570                     * Filter the current site setting in the returned response.
571                     *
572                     * @module json-api
573                     *
574                     * @since 3.9.3
575                     * @since 13.6 Added the API object parameter.
576                     *
577                     * @param mixed $response_item A single site setting.
578                     * @param WPCOM_JSON_API_Site_Settings_Endpoint $this The API object.
579                     */
580                    $response[ $key ] = apply_filters( 'site_settings_endpoint_get', $response[ $key ], $this );
581
582                    if ( class_exists( 'Sharing_Service' ) ) {
583                        $ss                                       = new Sharing_Service();
584                        $sharing                                  = $ss->get_global_options();
585                        $response[ $key ]['sharing_button_style'] = (string) $sharing['button_style'];
586                        $response[ $key ]['sharing_label']        = (string) $sharing['sharing_label'];
587                        $response[ $key ]['sharing_show']         = (array) $sharing['show'];
588                        $response[ $key ]['sharing_open_links']   = (string) $sharing['open_links'];
589                    }
590
591                    $response[ $key ]['jetpack_protect_whitelist'] = Brute_Force_Protection_Shared_Functions::format_allow_list();
592
593                    if ( ! current_user_can( 'edit_posts' ) ) {
594                        unset( $response[ $key ] );
595                    }
596                    break;
597            }
598        }
599        return $response;
600    }
601
602    /**
603     * Get the default value for the wpcom_gifting_subscription option.
604     * The default value is the inverse of the plan's auto_renew setting.
605     *
606     * @return bool
607     */
608    protected function get_wpcom_gifting_subscription_default() {
609        if ( function_exists( 'wpcom_get_site_purchases' ) && function_exists( 'wpcom_purchase_has_feature' ) ) {
610            $purchases = wpcom_get_site_purchases();
611
612            foreach ( $purchases as $purchase ) {
613                if ( wpcom_purchase_has_feature( $purchase, \WPCOM_Features::SUBSCRIPTION_GIFTING ) ) {
614                    /*
615                     * We set default value as false when expiration date not match the following:
616                     * - 54 days before the annual plan expiration.
617                     * - 5 days before the monthly plan expiration.
618                     * This is to match the gifting banner logic.
619                     */
620                    $days_of_warning          = str_contains( $purchase->product_slug, 'monthly' ) ? 5 : 54;
621                    $seconds_until_expiration = strtotime( $purchase->expiry_date ) - time();
622                    if ( $seconds_until_expiration >= $days_of_warning * DAY_IN_SECONDS ) {
623                        return false;
624                    }
625
626                    // We set default to the inverse of auto-renew.
627                    if ( isset( $purchase->auto_renew ) ) {
628                        return ! $purchase->auto_renew;
629                    } elseif ( isset( $purchase->user_allows_auto_renew ) ) {
630                        return ! $purchase->user_allows_auto_renew;
631                    }
632                }
633            }
634        }
635        return false;
636    }
637
638    /**
639     * Reads `subscription_options` with the current user's locale active, to
640     * ensure that the defaults would be translated when displaying to the user
641     * or comparing the options before saving.
642     *
643     * @return array The `subscription_options` value, defaults included.
644     */
645    private function get_subscription_options_in_user_locale() {
646        $switched_locale = false;
647
648        if ( function_exists( 'wpcom_switch_to_user_locale' ) ) {
649            // Compare the locales before/after switch to decide if we should switch back
650            $locale_before = determine_locale();
651            wpcom_switch_to_user_locale();
652            $switched_locale = determine_locale() !== $locale_before;
653        }
654
655        // Resolve the defaults the same way get_option() does for a missing row (via the
656        // `default_option_*` filter with $passed_default = false), then let any stored
657        // sub-keys take precedence. Passing an array default keeps get_option() from
658        // re-populating the defaults, so a partial row stays partial before the merge.
659        $default_subscription_options = (array) apply_filters( 'default_option_subscription_options', array(), 'subscription_options', false );
660        $stored_subscription_options  = (array) get_option( 'subscription_options', array() );
661        $subscription_options         = array_merge( $default_subscription_options, $stored_subscription_options );
662
663        if ( $switched_locale ) {
664            restore_previous_locale();
665        }
666
667        return $subscription_options;
668    }
669
670    /**
671     * Get list of all site level MCP abilities.
672     *
673     * @return array
674     */
675    private function get_all_site_mcp_abilities(): array {
676        $all_abilities         = array();
677        $ability_registry_file = WP_CONTENT_DIR . '/mu-plugins/wpcom-mcp/includes/AbilitiesRegistry/Registry/AbilityRegistry.php';
678        if ( file_exists( $ability_registry_file ) ) {
679            require_once $ability_registry_file;
680            // @phan-suppress-next-line PhanUndeclaredClassMethod
681            $abilities_resources = Automattic\WpcomMcp\AbilitiesRegistry\Registry\AbilityRegistry::get_resources_for_server( 'site-level' );
682            // @phan-suppress-next-line PhanUndeclaredClassMethod
683            $abilities_tools = Automattic\WpcomMcp\AbilitiesRegistry\Registry\AbilityRegistry::get_tools_for_server( 'site-level' );
684            // @phan-suppress-next-line PhanUndeclaredClassMethod
685            $abilities_prompts = Automattic\WpcomMcp\AbilitiesRegistry\Registry\AbilityRegistry::get_prompts_for_server( 'site-level' );
686            $all_abilities     = array_merge( $abilities_resources, $abilities_tools, $abilities_prompts );
687        }
688        return apply_filters( 'jetpack_site_mcp_abilities', $all_abilities );
689    }
690
691    /**
692     * Get ability meta from config.
693     *
694     * @param string $ability_name Ability name, i.e. wpcom-mcp/posts-search.
695     *
696     * @return array
697     */
698    private function get_mcp_abilities_metadata( string $ability_name ): array {
699        $ability_meta          = array();
700        $ability_registry_file = WP_CONTENT_DIR . '/mu-plugins/wpcom-mcp/includes/AbilitiesRegistry/Registry/AbilityRegistry.php';
701        if ( file_exists( $ability_registry_file ) ) {
702            require_once $ability_registry_file;
703            // @phan-suppress-next-line PhanUndeclaredClassMethod
704            $ability_meta = Automattic\WpcomMcp\AbilitiesRegistry\Registry\AbilityRegistry::get_metadata( $ability_name );
705        }
706        return apply_filters( 'jetpack_site_mcp_ability_meta', $ability_meta, $ability_name );
707    }
708
709    /**
710     * Get MCP abilities for the current site.
711     *
712     * @return array
713     */
714    public function get_site_mcp_abilities(): array {
715        $current_mcp_abilities = get_option( 'mcp_abilities', array() );
716        if ( ! is_array( $current_mcp_abilities ) ) {
717            $current_mcp_abilities = array();
718        }
719
720        $all_abilities = $this->get_all_site_mcp_abilities();
721        if ( empty( $all_abilities ) ) {
722            return array();
723        }
724
725        $computed_abilities = array();
726        foreach ( $all_abilities as $ability_name ) {
727            // Get base metadata first
728            $ability_meta = $this->get_mcp_abilities_metadata( $ability_name );
729            if ( ! empty( $ability_meta ) ) {
730                // Use stored value or fall back to metadata default
731                $enabled = $current_mcp_abilities[ $ability_name ] ?? $ability_meta['enabled'] ?? false;
732
733                $computed_abilities[ $ability_name ] = array(
734                    'name'        => $ability_name,
735                    'title'       => $ability_meta['title'] ?? '',
736                    'description' => $ability_meta['description'] ?? '',
737                    'category'    => $ability_meta['category'] ?? '',
738                    'type'        => $ability_meta['type'] ?? '',
739                    'enabled'     => (bool) $enabled,
740                );
741            }
742        }
743        return $computed_abilities;
744    }
745
746    /**
747     * Sets the MCP abilities for the current site.
748     *
749     * @param mixed $value MCP abilities array.
750     *
751     * @return true|WP_Error
752     */
753    public function set_site_mcp_abilities( $value ) {
754        // Validate input format
755        if ( ! is_array( $value ) ) {
756            return new WP_Error( 'invalid_format', __( 'Site MCP abilities must be an array', 'jetpack' ) );
757        }
758
759        $all_abilities = $this->get_all_site_mcp_abilities();
760
761        // Filter ability names that don't exist
762        $value = array_filter(
763            $value,
764            function ( $ability_name ) use ( $all_abilities ) {
765                return in_array( $ability_name, $all_abilities, true );
766            },
767            ARRAY_FILTER_USE_KEY
768        );
769
770        // Validate each ability exists and value is boolean-like
771        foreach ( $value as $ability_name => $enabled ) {
772            if ( ! is_string( $ability_name ) || ( ! WPCOM_JSON_API::is_truthy( $enabled ) && ! WPCOM_JSON_API::is_falsy( $enabled ) ) ) {
773                $error_message = sprintf(
774                    // Translators: %s is an MCP ability name
775                    __( 'Invalid ability: %s', 'jetpack' ),
776                    $ability_name
777                );
778                return new WP_Error( 'invalid_ability', $error_message );
779            }
780        }
781
782        update_option( 'mcp_abilities', $value );
783
784        return true;
785    }
786
787    /**
788     * Get locale.
789     *
790     * @param string $key Language.
791     */
792    protected function get_locale( $key ) {
793        if ( 'lang' === $key ) {
794            if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
795                return (string) get_blog_lang_code();
796            } else {
797                return get_locale();
798            }
799        }
800
801        return false;
802    }
803
804    /**
805     * Updates site settings for authorized users
806     *
807     * @return array|WP_Error
808     */
809    public function update_settings() {
810        /*
811         * $this->input() retrieves posted arguments whitelisted and casted to the $request_format
812         * specs that get passed in when this class is instantiated
813         */
814        $input            = $this->input();
815        $unfiltered_input = $this->input( false, false );
816        /**
817         * Filters the settings to be updated on the site.
818         *
819         * @module json-api
820         *
821         * @since 3.6.0
822         * @since 6.1.1 Added $unfiltered_input parameter.
823         *
824         * @param array $input              Associative array of site settings to be updated.
825         *                                  Cast and filtered based on documentation.
826         * @param array $unfiltered_input   Associative array of site settings to be updated.
827         *                                  Neither cast nor filtered. Contains raw input.
828         */
829        $input = apply_filters( 'rest_api_update_site_settings', $input, $unfiltered_input );
830
831        $blog_id = get_current_blog_id();
832
833        $jetpack_relatedposts_options = array();
834        $sharing_options              = array();
835        $updated                      = array();
836
837        if ( ! class_exists( 'Jetpack_Newsletter_Category_Helper' ) ) {
838            require_once JETPACK__PLUGIN_DIR . '_inc/lib/class-jetpack-newsletter-category-helper.php';
839        }
840
841        foreach ( $input as $key => $value ) {
842
843            if ( ! is_array( $value ) ) {
844                $value = trim( $value );
845            }
846
847            // preserve the raw value before unslashing the value. The slashes need to be preserved for date and time formats.
848            $raw_value = $value;
849            $value     = wp_unslash( $value );
850
851            switch ( $key ) {
852
853                case 'default_ping_status':
854                case 'default_comment_status':
855                    // settings are stored as closed|open.
856                    $coerce_value = ( $value ) ? 'open' : 'closed';
857                    if ( update_option( $key, $coerce_value ) ) {
858                        $updated[ $key ] = $value;
859                    }
860                    break;
861                case 'launchpad_screen':
862                    if ( in_array( $value, array( 'full', 'off', 'minimized' ), true ) ) {
863                        if ( update_option( $key, $value ) ) {
864                            $updated[ $key ] = $value;
865                        }
866                    }
867                    break;
868                case 'jetpack_protect_whitelist':
869                    if ( class_exists( 'Brute_Force_Protection_Shared_Functions' ) ) {
870                        $result = Brute_Force_Protection_Shared_Functions::save_allow_list( $value );
871                        if ( is_wp_error( $result ) ) {
872                            return $result;
873                        }
874                        $updated[ $key ] = Brute_Force_Protection_Shared_Functions::format_allow_list();
875                    }
876                    break;
877                case 'jetpack_sync_non_public_post_stati':
878                    Jetpack_Options::update_option( 'sync_non_public_post_stati', $value );
879                    break;
880                case 'jetpack_search_enabled':
881                    if ( $value ) {
882                        Jetpack::activate_module( $blog_id, 'search' );
883                    } else {
884                        // @phan-suppress-next-line PhanParamTooMany -- Phan doesn't know about the WP.com variant of the Jetpack class.
885                        Jetpack::deactivate_module( $blog_id, 'search' );
886                    }
887                    $updated[ $key ] = (bool) $value;
888                    break;
889                case 'jetpack_relatedposts_enabled':
890                case 'jetpack_relatedposts_show_context':
891                case 'jetpack_relatedposts_show_date':
892                case 'jetpack_relatedposts_show_thumbnails':
893                case 'jetpack_relatedposts_show_headline':
894                    if ( ! $this->jetpack_relatedposts_supported() ) {
895                        break;
896                    }
897                    if ( 'jetpack_relatedposts_enabled' === $key ) {
898                        if ( $value ) {
899                            Jetpack::activate_module( $blog_id, 'related-posts' );
900                        } else {
901                            // @phan-suppress-next-line PhanParamTooMany -- Phan doesn't know about the WP.com variant of the Jetpack class.
902                            Jetpack::deactivate_module( $blog_id, 'related-posts' );
903                        }
904                    }
905                    $just_the_key                                  = substr( $key, 21 );
906                    $jetpack_relatedposts_options[ $just_the_key ] = $value;
907                    break;
908
909                case 'social_notifications_like':
910                case 'social_notifications_reblog':
911                case 'social_notifications_subscribe':
912                    // settings are stored as on|off.
913                    $coerce_value = ( $value ) ? 'on' : 'off';
914                    if ( update_option( $key, $coerce_value ) ) {
915                        $updated[ $key ] = $value;
916                    }
917                    break;
918
919                case 'cloudflare_analytics':
920                    if ( ! isset( $value['code'] ) || ! preg_match( '/^$|^[a-fA-F0-9]+$/i', $value['code'] ) ) {
921                        return new WP_Error( 'invalid_code', __( 'Invalid Cloudflare Analytics ID', 'jetpack' ) );
922                    }
923
924                    if ( update_option( $key, $value ) ) {
925                        $updated[ $key ] = $value;
926                    }
927                    break;
928
929                case 'jetpack_testimonial':
930                case 'jetpack_portfolio':
931                case 'jetpack_comment_likes_enabled':
932                case 'wpcom_reader_views_enabled':
933                case 'jetpack_verbum_subscription_modal':
934                    // settings are stored as 1|0.
935                    $coerce_value = (int) $value;
936                    if ( update_option( $key, $coerce_value ) ) {
937                        $updated[ $key ] = (bool) $value;
938                    }
939                    break;
940
941                case 'jetpack_testimonial_posts_per_page':
942                case 'jetpack_portfolio_posts_per_page':
943                    // settings are stored as numeric.
944                    $coerce_value = (int) $value;
945                    if ( update_option( $key, $coerce_value ) ) {
946                        $updated[ $key ] = $coerce_value;
947                    }
948                    break;
949
950                // Sharing options.
951                case 'sharing_button_style':
952                case 'sharing_show':
953                case 'sharing_open_links':
954                    $sharing_options[ preg_replace( '/^sharing_/', '', $key ) ] = $value;
955                    break;
956                case 'sharing_label':
957                    $sharing_options[ $key ] = $value;
958                    break;
959
960                // Keyring token option.
961                case 'eventbrite_api_token':
962                    // These options can only be updated for sites hosted on WordPress.com.
963                    if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
964                        if ( empty( $value ) || WPCOM_JSON_API::is_falsy( $value ) ) {
965                            if ( delete_option( $key ) ) {
966                                $updated[ $key ] = null;
967                            }
968                        } elseif ( update_option( $key, $value ) ) {
969                            $updated[ $key ] = (int) $value;
970                        }
971                    }
972                    break;
973
974                case 'api_cache':
975                    if ( empty( $value ) || WPCOM_JSON_API::is_falsy( $value ) ) {
976                        if ( delete_option( 'jetpack_api_cache_enabled' ) ) {
977                            $updated[ $key ] = false;
978                        }
979                    } elseif ( update_option( 'jetpack_api_cache_enabled', true ) ) {
980                        $updated[ $key ] = true;
981                    }
982                    break;
983
984                case 'timezone_string':
985                    /*
986                     * Map UTC+- timezones to gmt_offsets and set timezone_string to empty
987                     * https://github.com/WordPress/WordPress/blob/4.4.2/wp-admin/options.php#L175
988                     */
989                    if ( ! empty( $value ) && preg_match( '/^UTC[+-]/', $value ) ) {
990                        $gmt_offset = preg_replace( '/UTC\+?/', '', $value );
991                        if ( update_option( 'gmt_offset', $gmt_offset ) ) {
992                            $updated['gmt_offset'] = $gmt_offset;
993                        }
994
995                        $value = '';
996                    }
997
998                    /*
999                     * Always set timezone_string either with the given value or with an
1000                     * empty string
1001                     */
1002                    if ( update_option( $key, $value ) ) {
1003                        $updated[ $key ] = $value;
1004                    }
1005                    break;
1006
1007                case 'subscription_options':
1008                    if ( ! is_array( $value ) ) {
1009                        break;
1010                    }
1011
1012                    $allowed_keys   = array( 'invitation', 'comment_follow', 'welcome', 'subscribe_modal_heading', 'free_tier_description', 'hide_free_tier' );
1013                    $filtered_value = array_filter(
1014                        $value,
1015                        function ( $key ) use ( $allowed_keys ) {
1016                            return in_array( $key, $allowed_keys, true );
1017                        },
1018                        ARRAY_FILTER_USE_KEY
1019                    );
1020
1021                    if ( empty( $filtered_value ) ) {
1022                        break;
1023                    }
1024
1025                    // `hide_free_tier` is a boolean flag, so pull it out before the HTML
1026                    // sanitization below (which expects strings). Parse it with is_truthy()
1027                    // so stringy booleans (e.g. "false", "0") are interpreted correctly
1028                    // rather than being treated as truthy by a plain `! empty()`.
1029                    $has_hide_free_tier = array_key_exists( 'hide_free_tier', $filtered_value );
1030                    $hide_free_tier     = $has_hide_free_tier && WPCOM_JSON_API::is_truthy( $filtered_value['hide_free_tier'] );
1031                    unset( $filtered_value['hide_free_tier'] );
1032
1033                    array_walk_recursive(
1034                        $filtered_value,
1035                        function ( &$value ) {
1036                            $value = wp_kses(
1037                                $value,
1038                                array(
1039                                    'a' => array(
1040                                        'href' => array(),
1041                                    ),
1042                                )
1043                            );
1044                        }
1045                    );
1046
1047                    // Normalize whitespace-only `subscribe_modal_heading` input to empty so
1048                    // the modal template's `empty()` fallback fires. PHP's `empty()` treats
1049                    // `"   "` as non-empty, which would otherwise render a blank heading.
1050                    if ( isset( $filtered_value['subscribe_modal_heading'] ) ) {
1051                        $filtered_value['subscribe_modal_heading'] = trim( $filtered_value['subscribe_modal_heading'] );
1052                    }
1053
1054                    // The free tier description is stored as plain markdown source, so strip
1055                    // all HTML and cap its length to match the paid-tier description field.
1056                    // WordPress core guarantees mb_substr() (polyfilled in wp-includes/compat.php
1057                    // when the mbstring extension is unavailable), so it's safe to use directly.
1058                    // A JSON payload could supply a non-scalar (array/object) for this field,
1059                    // which would fatal in wp_kses()/mb_substr() on PHP 8+, so drop invalid values.
1060                    if ( isset( $filtered_value['free_tier_description'] ) ) {
1061                        if ( is_scalar( $filtered_value['free_tier_description'] ) ) {
1062                            $filtered_value['free_tier_description'] = mb_substr( wp_kses( (string) $filtered_value['free_tier_description'], array() ), 0, 500 );
1063                        } else {
1064                            unset( $filtered_value['free_tier_description'] );
1065                        }
1066                    }
1067
1068                    if ( $has_hide_free_tier ) {
1069                        $filtered_value['hide_free_tier'] = $hide_free_tier;
1070                    }
1071
1072                    // Clients that render the settings form tend to post the whole
1073                    // `subscription_options` bag back, including sub-keys the user never
1074                    // touched. This could result in a translated value inadvertently
1075                    // saved in the database.
1076                    // Get the value from db or the default options populated by filter.
1077                    $current_subscription_options = $this->get_subscription_options_in_user_locale();
1078                    $changed_subscription_options = array();
1079
1080                    foreach ( $filtered_value as $subscription_option_key => $subscription_option_value ) {
1081                        $current_subscription_option = $current_subscription_options[ $subscription_option_key ] ?? null;
1082
1083                        // The incoming value has already been through wp_kses() above, and
1084                        // wp_kses() is not guaranteed to be byte-preserving â€” it rewrites
1085                        // attribute quoting, and differently across WordPress versions. Put the
1086                        // current value through the same pass so the comparison reflects a real
1087                        // edit rather than a sanitizer rewrite; without this, a default carrying
1088                        // markup (`invitation`) never compares equal and is persisted on every
1089                        // save. Safe to apply to an already-sanitized value: the pass is
1090                        // idempotent.
1091                        if ( is_string( $current_subscription_option ) ) {
1092                            $current_subscription_option = wp_kses(
1093                                $current_subscription_option,
1094                                array(
1095                                    'a' => array(
1096                                        'href' => array(),
1097                                    ),
1098                                )
1099                            );
1100                        }
1101
1102                        // A sub-key the site has never stored reads as unset everywhere this
1103                        // option is consumed, so an empty incoming value for it is not a change.
1104                        if (
1105                            null === $current_subscription_option
1106                            && ( '' === $subscription_option_value || false === $subscription_option_value )
1107                        ) {
1108                            continue;
1109                        }
1110
1111                        if ( $current_subscription_option === $subscription_option_value ) {
1112                            continue;
1113                        }
1114
1115                        $changed_subscription_options[ $subscription_option_key ] = $subscription_option_value;
1116                    }
1117
1118                    if ( empty( $changed_subscription_options ) ) {
1119                        break;
1120                    }
1121
1122                    // Get the value from the database or an empty array.
1123                    $old_subscription_options = get_option( 'subscription_options', array() );
1124                    $new_subscription_options = array_merge( $old_subscription_options, $changed_subscription_options );
1125
1126                    if ( update_option( $key, $new_subscription_options ) ) {
1127                        $updated[ $key ] = $changed_subscription_options;
1128                    }
1129                    break;
1130
1131                case 'woocommerce_onboarding_profile':
1132                    // Allow boolean values but sanitize_text_field everything else.
1133                    $sanitized_value = (array) $value;
1134                    array_walk_recursive(
1135                        $sanitized_value,
1136                        function ( &$value ) {
1137                            if ( ! is_bool( $value ) ) {
1138                                $value = sanitize_text_field( $value );
1139                            }
1140                        }
1141                    );
1142                    if ( update_option( $key, $sanitized_value ) ) {
1143                        $updated[ $key ] = $sanitized_value;
1144                    }
1145                    break;
1146
1147                case 'woocommerce_store_address':
1148                case 'woocommerce_store_address_2':
1149                case 'woocommerce_store_city':
1150                case 'woocommerce_default_country':
1151                case 'woocommerce_store_postcode':
1152                    $sanitized_value = sanitize_text_field( $value );
1153                    if ( update_option( $key, $sanitized_value ) ) {
1154                        $updated[ $key ] = $sanitized_value;
1155                    }
1156                    break;
1157
1158                case 'date_format':
1159                case 'time_format':
1160                    // settings are stored as strings.
1161                    // raw_value is used to help preserve any escaped characters that might exist in the formatted string.
1162                    $sanitized_value = sanitize_text_field( $raw_value );
1163                    if ( update_option( $key, $sanitized_value ) ) {
1164                        $updated[ $key ] = $sanitized_value;
1165                    }
1166                    break;
1167
1168                case 'start_of_week':
1169                    // setting is stored as int in 0-6 range (days of week).
1170                    $coerce_value = (int) $value;
1171                    $limit_value  = ( $coerce_value >= 0 && $coerce_value <= 6 ) ? $coerce_value : 0;
1172                    if ( update_option( $key, $limit_value ) ) {
1173                        $updated[ $key ] = $limit_value;
1174                    }
1175                    break;
1176
1177                case 'site_icon':
1178                    /*
1179                     * settings are stored as deletable numeric (all empty
1180                     * values as delete intent), validated as media image
1181                     */
1182                    if ( empty( $value ) || WPCOM_JSON_API::is_falsy( $value ) ) {
1183                        /**
1184                         * Fallback mechanism to clear a third party site icon setting. Can be used
1185                         * to unset the option when an API request instructs the site to remove the site icon.
1186                         *
1187                         * @module json-api
1188                         *
1189                         * @since 4.10
1190                         */
1191                        if ( delete_option( $key ) || apply_filters( 'rest_api_site_icon_cleared', false ) ) {
1192                            $updated[ $key ] = null;
1193                        }
1194                    } elseif ( is_numeric( $value ) ) {
1195                        $coerce_value = (int) $value;
1196                        if ( wp_attachment_is_image( $coerce_value ) && update_option( $key, $coerce_value ) ) {
1197                            $updated[ $key ] = $coerce_value;
1198                        }
1199                    }
1200                    break;
1201
1202                case Jetpack_SEO_Utils::FRONT_PAGE_META_OPTION:
1203                    if ( ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() && ! Jetpack_SEO_Utils::has_legacy_front_page_meta() ) {
1204                        return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
1205                    }
1206
1207                    if ( ! is_string( $value ) ) {
1208                        return new WP_Error( 'invalid_input', __( 'Invalid SEO meta description value.', 'jetpack' ), 400 );
1209                    }
1210
1211                    $new_description = Jetpack_SEO_Utils::update_front_page_meta_description( $value );
1212
1213                    if ( ! empty( $new_description ) ) {
1214                        $updated[ $key ] = $new_description;
1215                    }
1216                    break;
1217
1218                case Jetpack_SEO_Titles::TITLE_FORMATS_OPTION:
1219                    if ( ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) {
1220                        if ( Jetpack_SEO_Utils::has_legacy_front_page_meta() ) {
1221                            break;
1222                        }
1223                        return new WP_Error( 'unauthorized', __( 'SEO tools are not enabled for this site.', 'jetpack' ), 403 );
1224                    }
1225
1226                    if ( ! Jetpack_SEO_Titles::are_valid_title_formats( $value ) ) {
1227                        return new WP_Error( 'invalid_input', __( 'Invalid SEO title format.', 'jetpack' ), 400 );
1228                    }
1229
1230                    $new_title_formats = Jetpack_SEO_Titles::update_title_formats( $value );
1231
1232                    if ( ! empty( $new_title_formats ) ) {
1233                        $updated[ $key ] = $new_title_formats;
1234                    }
1235                    break;
1236
1237                case 'verification_services_codes':
1238                    foreach ( $value as $raw_code ) {
1239                        if ( '' === $raw_code || null === $raw_code || false === $raw_code ) {
1240                            continue;
1241                        }
1242
1243                        if ( false === jetpack_verification_validate_code( $raw_code ) ) {
1244                            return new WP_Error(
1245                                'invalid_input',
1246                                __( 'Invalid site verification code. Enter a verification code or verification tag.', 'jetpack' ),
1247                                400
1248                            );
1249                        }
1250                    }
1251
1252                    $verification_codes = jetpack_verification_validate_codes( $value );
1253
1254                    if ( update_option( 'verification_services_codes', $verification_codes ) ) {
1255                        $updated[ $key ] = $verification_codes;
1256                    }
1257                    break;
1258
1259                case 'wpcom_publish_posts_with_markdown':
1260                case 'wpcom_publish_comments_with_markdown':
1261                    $coerce_value = (bool) $value;
1262                    if ( update_option( $key, $coerce_value ) ) {
1263                        $updated[ $key ] = $coerce_value;
1264                    }
1265                    break;
1266
1267                case 'wpcom_gifting_subscription':
1268                    $coerce_value = (bool) $value;
1269
1270                    /*
1271                     * get_option returns a boolean false if the option doesn't exist, otherwise it always returns
1272                     * a serialized value. Knowing that we can check if the option already exists.
1273                     */
1274                    $gift_toggle = get_option( $key );
1275                    if ( false === $gift_toggle ) {
1276                        // update_option will not create a new option if the initial value is false. So use add_option.
1277                        if ( add_option( $key, $coerce_value ) ) {
1278                            $updated[ $key ] = $coerce_value;
1279                        }
1280                    } elseif ( update_option( $key, $coerce_value ) ) { // If the option already exists use update_option.
1281                        $updated[ $key ] = $coerce_value;
1282                    }
1283                    break;
1284
1285                case 'rss_use_excerpt':
1286                    $sanitized_value = (int) (bool) $value;
1287                    update_option( $key, $sanitized_value );
1288                    $updated[ $key ] = $sanitized_value;
1289                    break;
1290
1291                case 'wpcom_subscription_emails_use_excerpt':
1292                    update_option( 'wpcom_subscription_emails_use_excerpt', (bool) $value );
1293                    $updated[ $key ] = (bool) $value;
1294                    break;
1295
1296                case 'jetpack_subscriptions_reply_to':
1297                    require_once JETPACK__PLUGIN_DIR . 'modules/subscriptions/class-settings.php';
1298                    $to_set_value = Automattic\Jetpack\Modules\Subscriptions\Settings::is_valid_reply_to( $value )
1299                        ? (string) $value
1300                        : Automattic\Jetpack\Modules\Subscriptions\Settings::$default_reply_to;
1301
1302                    if ( update_option( $key, $to_set_value ) ) {
1303                        $updated[ $key ] = $to_set_value;
1304                    }
1305                    break;
1306
1307                case 'jetpack_subscriptions_from_name':
1308                    $sanitized_value = sanitize_text_field( $value );
1309                    if ( update_option( $key, $sanitized_value ) ) {
1310                        $updated[ $key ] = $sanitized_value;
1311                    }
1312                    break;
1313
1314                case 'instant_search_enabled':
1315                    update_option( 'instant_search_enabled', (bool) $value );
1316                    $updated[ $key ] = (bool) $value;
1317                    break;
1318
1319                case 'lang_id':
1320                    /*
1321                     * Due to the fact that locale variants are set in a locale_variant option,
1322                     * changing locale from variant to primary
1323                     * would look like the same lang_id is being saved and update_option would return false,
1324                     * even though the correct options would be set by pre_update_option_lang_id,
1325                     * so we should always return lang_id as updated.
1326                     */
1327                    update_option( 'lang_id', (int) $value );
1328                    $updated[ $key ] = (int) $value;
1329                    break;
1330
1331                case 'wpcom_newsletter_send_default':
1332                    update_option( 'wpcom_newsletter_send_default', (int) (bool) $value );
1333                    $updated[ $key ] = (int) (bool) $value;
1334                    break;
1335
1336                case 'wpcom_featured_image_in_email':
1337                    update_option( 'wpcom_featured_image_in_email', (int) (bool) $value );
1338                    $updated[ $key ] = (int) (bool) $value;
1339                    break;
1340
1341                case Jetpack_Newsletter_Category_Helper::NEWSLETTER_CATEGORIES_OPTION:
1342                    $update_newsletter_categories = Jetpack_Newsletter_Category_Helper::save_category_ids( (array) $value );
1343                    if ( $update_newsletter_categories ) {
1344                        $updated[ $key ] = $update_newsletter_categories;
1345                    }
1346
1347                    break;
1348
1349                case 'wpcom_newsletter_categories_enabled':
1350                    update_option( 'wpcom_newsletter_categories_enabled', (int) (bool) $value );
1351                    $updated[ $key ] = (int) (bool) $value;
1352                    break;
1353
1354                case 'sm_enabled':
1355                    update_option( 'sm_enabled', (int) (bool) $value );
1356                    $updated[ $key ] = (int) (bool) $value;
1357                    break;
1358
1359                case 'jetpack_subscribe_overlay_enabled':
1360                    update_option( 'jetpack_subscribe_overlay_enabled', (int) (bool) $value );
1361                    $updated[ $key ] = (int) (bool) $value;
1362                    break;
1363
1364                case 'jetpack_subscribe_floating_button_enabled':
1365                    update_option( 'jetpack_subscribe_floating_button_enabled', (int) (bool) $value );
1366                    $updated[ $key ] = (int) (bool) $value;
1367                    break;
1368
1369                case 'jetpack_subscriptions_subscribe_post_end_enabled':
1370                    update_option( 'jetpack_subscriptions_subscribe_post_end_enabled', (int) (bool) $value );
1371                    $updated[ $key ] = (int) (bool) $value;
1372                    break;
1373
1374                case 'jetpack_subscriptions_login_navigation_enabled':
1375                    update_option( 'jetpack_subscriptions_login_navigation_enabled', (int) (bool) $value );
1376                    $updated[ $key ] = (int) (bool) $value;
1377                    break;
1378
1379                case 'jetpack_subscriptions_subscribe_navigation_enabled':
1380                    update_option( 'jetpack_subscriptions_subscribe_navigation_enabled', (int) (bool) $value );
1381                    $updated[ $key ] = (int) (bool) $value;
1382                    break;
1383
1384                case 'show_on_front':
1385                    if ( in_array( $value, array( 'page', 'posts' ), true ) && update_option( $key, $value ) ) {
1386                            $updated[ $key ] = $value;
1387                    }
1388                    break;
1389
1390                case 'page_on_front':
1391                case 'page_for_posts':
1392                    if ( $value === '' ) { // empty function is not applicable here because '0' may be a valid page id
1393                        if ( delete_option( $key ) ) {
1394                            $updated[ $key ] = null;
1395                        }
1396
1397                        break;
1398                    }
1399
1400                    if ( ! $this->is_valid_page_id( $value ) ) {
1401                        break;
1402                    }
1403
1404                    $related_option_key   = $key === 'page_on_front' ? 'page_for_posts' : 'page_on_front';
1405                    $related_option_value = get_option( $related_option_key );
1406                    if ( $related_option_value === $value ) {
1407                        // page_on_front and page_for_posts are not allowed to be the same
1408                        break;
1409                    }
1410
1411                    if ( update_option( $key, $value ) ) {
1412                        $updated[ $key ] = $value;
1413                    }
1414
1415                    break;
1416
1417                case 'in_site_migration_flow':
1418                    if ( empty( $value ) ) {
1419                        delete_option( 'in_site_migration_flow' );
1420                        break;
1421                    }
1422
1423                    $migration_flow_whitelist = array(
1424                        'site-migration',
1425                        'migration-signup',
1426                    );
1427
1428                    if ( ! in_array( $value, $migration_flow_whitelist, true ) ) {
1429                        break;
1430                    }
1431
1432                    update_option( 'in_site_migration_flow', $value );
1433                    $updated[ $key ] = $value;
1434                    break;
1435
1436                case 'migration_source_site_domain':
1437                    // If we get an empty value, delete the option
1438                    if ( empty( $value ) ) {
1439                        delete_option( 'migration_source_site_domain' );
1440                        break;
1441                    }
1442
1443                    // If we get a non-url value, don't update the option.
1444                    if ( wp_http_validate_url( $value ) === false ) {
1445                        break;
1446                    }
1447
1448                    update_option( 'migration_source_site_domain', $value );
1449                    $updated[ $key ] = $value;
1450                    break;
1451
1452                case 'is_fully_managed_agency_site':
1453                case 'wpcom_hide_action_bar':
1454                    $coerce_value = (int) (bool) $value;
1455                    if ( update_option( $key, $coerce_value ) ) {
1456                        $updated[ $key ] = (bool) $coerce_value;
1457                    }
1458                    break;
1459
1460                case 'mcp_abilities':
1461                    $result = $this->set_site_mcp_abilities( $value );
1462                    if ( is_wp_error( $result ) ) {
1463                        return $result;
1464                    }
1465                    $updated[ $key ] = $this->get_site_mcp_abilities();
1466                    break;
1467
1468                default:
1469                    // allow future versions of this endpoint to support additional settings keys.
1470                    if ( has_filter( 'site_settings_endpoint_update_' . $key ) ) {
1471                        /**
1472                         * Filter current site setting value to be updated.
1473                         *
1474                         * @module json-api
1475                         *
1476                         * @since 3.9.3
1477                         * @since 13.6 Added the API object parameter.
1478                         *
1479                         * @param mixed $response_item A single site setting value.
1480                         * @param WPCOM_JSON_API_Site_Settings_Endpoint The API object parameter.
1481                         */
1482                        $value = apply_filters( 'site_settings_endpoint_update_' . $key, $value, $this );
1483
1484                        if ( is_wp_error( $value ) ) {
1485                            return $value;
1486                        }
1487
1488                        if ( $value ) {
1489                            $updated[ $key ] = $value;
1490                        }
1491                        break;
1492                    }
1493                    // no worries, we've already whitelisted and casted arguments above.
1494                    if ( update_option( $key, $value ) ) {
1495                        $updated[ $key ] = $value;
1496                    }
1497            }
1498        }
1499
1500        if ( $jetpack_relatedposts_options !== array() ) {
1501            // track new jetpack_relatedposts options against old.
1502            $old_relatedposts_options = Jetpack_Options::get_option( 'relatedposts' );
1503
1504            $jetpack_relatedposts_options_to_save = $old_relatedposts_options;
1505            foreach ( $jetpack_relatedposts_options as $key => $value ) {
1506                $jetpack_relatedposts_options_to_save[ $key ] = $value;
1507            }
1508
1509            if ( Jetpack_Options::update_option( 'relatedposts', $jetpack_relatedposts_options_to_save ) ) {
1510                foreach ( $jetpack_relatedposts_options as $key => $value ) {
1511                    if ( in_array( $key, array( 'show_context', 'show_date' ), true ) ) {
1512                        $has_initialized_option = ! isset( $old_relatedposts_options[ $key ] ) && $value;
1513                        $has_updated_option     = isset( $old_relatedposts_options[ $key ] ) && $value !== $old_relatedposts_options[ $key ];
1514
1515                        if ( $has_initialized_option || $has_updated_option ) {
1516                            $updated[ 'jetpack_relatedposts_' . $key ] = (bool) $value;
1517                        }
1518                    } elseif ( isset( $old_relatedposts_options[ $key ] ) && $value !== $old_relatedposts_options[ $key ] ) {
1519                        $updated[ 'jetpack_relatedposts_' . $key ] = $value;
1520                    }
1521                }
1522            }
1523        }
1524
1525        if ( ! empty( $sharing_options ) && class_exists( 'Sharing_Service' ) ) {
1526            $ss = new Sharing_Service();
1527
1528            /*
1529             * Merge current values with updated, since Sharing_Service expects
1530             * all values to be included when updating
1531             */
1532            $current_sharing_options = $ss->get_global_options();
1533            foreach ( $current_sharing_options as $key => $val ) {
1534                if ( ! isset( $sharing_options[ $key ] ) ) {
1535                    $sharing_options[ $key ] = $val;
1536                }
1537            }
1538
1539            $updated_social_options = $ss->set_global_options( $sharing_options );
1540
1541            if ( isset( $input['sharing_button_style'] ) ) {
1542                $updated['sharing_button_style'] = (string) $updated_social_options['button_style'];
1543            }
1544            if ( isset( $input['sharing_label'] ) ) {
1545                // Sharing_Service won't report label as updated if set to default.
1546                $updated['sharing_label'] = (string) $sharing_options['sharing_label'];
1547            }
1548            if ( isset( $input['sharing_show'] ) ) {
1549                $updated['sharing_show'] = (array) $updated_social_options['show'];
1550            }
1551            if ( isset( $input['sharing_open_links'] ) ) {
1552                $updated['sharing_open_links'] = (string) $updated_social_options['open_links'];
1553            }
1554        }
1555
1556        return array(
1557            'updated' => $updated,
1558        );
1559    }
1560
1561    /**
1562     * Get the string value of the jetpack_subscriptions_reply_to option.
1563     * When the option is not set, it will retun 'no-reply'.
1564     *
1565     * @return string
1566     */
1567    protected function get_subscriptions_reply_to_option() {
1568        $reply_to = get_option( 'jetpack_subscriptions_reply_to', null );
1569        if ( $reply_to === null ) {
1570            require_once JETPACK__PLUGIN_DIR . 'modules/subscriptions/class-settings.php';
1571            return Automattic\Jetpack\Modules\Subscriptions\Settings::$default_reply_to;
1572        }
1573        return $reply_to;
1574    }
1575
1576    /**
1577     * Check if the given value is a valid page ID for the current site.
1578     *
1579     * @param mixed $value The value to check.
1580     * @return bool True if the value is a valid page ID for the current site, false otherwise.
1581     */
1582    protected function is_valid_page_id( $value ) {
1583        $all_page_ids = get_all_page_ids();
1584
1585        $valid_page_id = false;
1586        foreach ( $all_page_ids as $page_id ) {
1587            if ( $page_id === (string) $value ) {
1588                $valid_page_id = true;
1589                break;
1590            }
1591        }
1592
1593        return $valid_page_id;
1594    }
1595
1596    /**
1597     * Get the value of the highlander_comment_form_prompt option.
1598     * When the option is not set, it will return the default value.
1599     *
1600     * @return string
1601     */
1602    protected function get_highlander_comment_form_prompt_option() {
1603        $highlander_comment_form_prompt_option = get_option( 'highlander_comment_form_prompt' );
1604
1605        if ( empty( $highlander_comment_form_prompt_option ) ) {
1606            return (string) __( 'Leave a comment', 'jetpack' );
1607        }
1608
1609        return (string) $highlander_comment_form_prompt_option;
1610    }
1611}