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