Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
39.41% covered (danger)
39.41%
928 / 2355
31.69% covered (danger)
31.69%
58 / 183
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack
39.46% covered (danger)
39.46%
928 / 2352
31.69% covered (danger)
31.69%
58 / 183
141769.58
0.00% covered (danger)
0.00%
0 / 1
 init
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
2.86
 plugin_upgrade
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 1
420
 upgrade_on_load
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 update_active_modules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 delete_active_modules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_configure_hook
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 __construct
0.00% covered (danger)
0.00%
0 / 68
0.00% covered (danger)
0.00%
0 / 1
12
 should_eager_load_packages
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
5
 configure_import_package
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 is_premium_analytics_enabled
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
6
 register_premium_analytics_enablement_setting
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 configure
85.37% covered (warning)
85.37%
70 / 82
0.00% covered (danger)
0.00%
0 / 1
22.38
 late_initialization
86.36% covered (warning)
86.36%
19 / 22
0.00% covered (danger)
0.00%
0 / 1
4.04
 add_wpcom_to_allowed_redirect_hosts
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 allow_wpcom_domain
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 point_edit_post_links_to_calypso
n/a
0 / 0
n/a
0 / 0
3
 point_edit_comment_links_to_calypso
n/a
0 / 0
n/a
0 / 0
1
 filter_sync_callable_whitelist
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 filter_sync_multisite_callable_whitelist
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 push_stats
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 jetpack_custom_caps
76.19% covered (warning)
76.19%
16 / 21
0.00% covered (danger)
0.00%
0 / 1
7.66
 register_assets
97.44% covered (success)
97.44%
38 / 39
0.00% covered (danger)
0.00%
0 / 1
5
 guess_locale_from_lang
12.50% covered (danger)
12.50%
2 / 16
0.00% covered (danger)
0.00%
0 / 1
108.47
 get_locale
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 jetpack_main_network_site_option
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 network_name
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 network_allow_new_registrations
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 network_add_new_users
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 network_site_upload_space
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 network_upload_file_types
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 network_max_upload_file_size
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 network_enable_administration_menus
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 maybe_clear_other_linked_admins_transient
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
 get_other_linked_admins
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
7.01
 is_main_network_option
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_multisite
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_multi_network
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 is_single_user_site
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 file_system_write_access
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 get_updates
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
5.93
 get_update_details
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 is_active
n/a
0 / 0
n/a
0 / 0
1
 is_connection_ready
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 development_mode_trigger_text
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
72
 show_development_mode_notice
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 is_development_version
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_connected_user_email
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 get_master_user_email
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 current_user_ip
n/a
0 / 0
n/a
0 / 0
1
 load_modules
55.56% covered (warning)
55.56%
25 / 45
0.00% covered (danger)
0.00%
0 / 1
59.72
 check_rest_api_compat
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_active_plugins
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_parsed_plugin_data
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 get_parsed_theme_data
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 is_plugin_active
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 check_open_graph
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
56
 check_twitter_tags
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 get_option_names
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_option
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 glob_php
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 activate_new_modules
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
132
 get_available_modules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_default_modules
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
7.02
 handle_deprecated_modules
66.67% covered (warning)
66.67%
12 / 18
0.00% covered (danger)
0.00%
0 / 1
10.37
 filter_default_modules
53.85% covered (warning)
53.85%
7 / 13
0.00% covered (danger)
0.00%
0 / 1
14.29
 get_module_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_module_path
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_module
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_file_data
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 translate_module_tag
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_translated_modules
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 get_active_modules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_module_active
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_module
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 catch_errors
n/a
0 / 0
n/a
0 / 0
1
 catch_errors_on_shutdown
n/a
0 / 0
n/a
0 / 0
1
 alias_directories
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 activate_default_modules
40.96% covered (danger)
40.96%
34 / 83
0.00% covered (danger)
0.00%
0 / 1
318.68
 activate_module
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 deactivate_module
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 enable_module_configurable
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 module_configuration_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 bail_on_activation
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
30
 plugin_activation
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
7.14
 get_activation_source
93.55% covered (success)
93.55%
29 / 31
0.00% covered (danger)
0.00%
0 / 1
13.05
 do_version_bump
n/a
0 / 0
n/a
0 / 0
1
 activate_subscriptions_module_for_existing_sites
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
6.40
 register_upgrade_init_hooks
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 reconcile_ai_master_optout
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 is_module_active_for_seo_option
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 migrate_sitemaps_module_to_seo_option
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 sync_seo_sitemap_option
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 migrate_canonical_urls_module_to_seo_option
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 sync_seo_canonical_urls_option
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 reconcile_seo_module_state_options
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 register_seo_module_migration_hooks
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 seed_seo_visibility_cohort
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 set_update_modal_display
n/a
0 / 0
n/a
0 / 0
1
 enqueue_block_style
n/a
0 / 0
n/a
0 / 0
2
 plugin_initialize
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
4.01
 handle_default_module_activation
88.24% covered (warning)
88.24%
15 / 17
0.00% covered (danger)
0.00%
0 / 1
5.04
 plugin_deactivation
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
4.02
 on_idc_disconnect
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 disconnect
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 jetpack_site_disconnected
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 disconnect_user
n/a
0 / 0
n/a
0 / 0
1
 registration_check_domains
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 log
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
20
 get_log
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
132
 log_settings_change
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_stat_data
n/a
0 / 0
n/a
0 / 0
3
 get_additional_stat_data
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 get_site_user_count
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 admin_init
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
240
 admin_body_class
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 add_jetpack_pagestyles
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 throw_error_on_activate_plugin
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
56
 plugins_page_init_jetpack_state
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 intercept_plugin_error_scrape_init
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 intercept_plugin_error_scrape
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
30
 add_remote_request_handlers
15.38% covered (danger)
15.38%
2 / 13
0.00% covered (danger)
0.00%
0 / 1
36.69
 remote_request_handlers
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
72
 upload_handler
0.00% covered (danger)
0.00%
0 / 93
0.00% covered (danger)
0.00%
0 / 1
870
 plugin_action_links
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 deactivate_dialog
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 jetpack_plugin_portal_containers
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 login_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 login_init
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
2.00
 get_registration_error_description
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 admin_page_load
0.00% covered (danger)
0.00%
0 / 144
0.00% covered (danger)
0.00%
0 / 1
2162
 admin_notices
0.00% covered (danger)
0.00%
0 / 106
0.00% covered (danger)
0.00%
0 / 1
56
 initialize_stats
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
2.50
 stat
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 do_stats
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 do_server_side_stat
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 build_stats_url
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 build_connect_url
68.97% covered (warning)
68.97%
20 / 29
0.00% covered (danger)
0.00%
0 / 1
16.30
 build_authorize_url
n/a
0 / 0
n/a
0 / 0
1
 filter_connect_request_body
n/a
0 / 0
n/a
0 / 0
1
 filter_jetpack_current_user_connection_data
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
6.01
 filter_connect_redirect_url
n/a
0 / 0
n/a
0 / 0
1
 authorize_starting
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 handle_unique_registrations_stats
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 authorize_ending_linked
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 authorize_ending_authorized
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 activate_default_modules_on_site_register
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 reconnection_completed
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 apply_activation_source_to_args
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 build_reconnect_url
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 admin_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 nonce_url_no_esc
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 dismiss_jetpack_notice
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
 sort_modules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 ajax_recheck_ssl
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 verify_onboarding_token
n/a
0 / 0
n/a
0 / 0
15
 create_onboarding_token
n/a
0 / 0
n/a
0 / 0
2
 invalidate_onboarding_token
n/a
0 / 0
n/a
0 / 0
1
 validate_onboarding_token_action
n/a
0 / 0
n/a
0 / 0
3
 permit_ssl
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_ssl_test_message
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 alert_auto_ssl_fail
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
6
 connection
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 get_secrets
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 filter_token_request_body
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 maybe_set_version_option
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 state
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 restate
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 should_set_cookie
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 check_privacy
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
42
 login_form_json_api_authorization
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 post_login_form_to_signed_url
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
42
 preserve_action_in_login_form_for_json_api_authorization
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 store_json_api_authorization_token
n/a
0 / 0
n/a
0 / 0
1
 allow_wpcom_public_api_domain
n/a
0 / 0
n/a
0 / 0
1
 is_redirect_encoded
n/a
0 / 0
n/a
0 / 0
1
 allow_wpcom_environments
n/a
0 / 0
n/a
0 / 0
1
 add_token_to_login_redirect_json_api_authorization
n/a
0 / 0
n/a
0 / 0
1
 verify_json_api_authorization_request
n/a
0 / 0
n/a
0 / 0
1
 login_message_json_api_authorization
n/a
0 / 0
n/a
0 / 0
1
 get_content_width
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_cloud_site_options
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 check_identity_crisis
n/a
0 / 0
n/a
0 / 0
1
 normalize_url_protocol_agnostic
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 maybe_min_asset
28.57% covered (danger)
28.57%
6 / 21
0.00% covered (danger)
0.00%
0 / 1
31.32
 set_suffix_on_min
50.00% covered (danger)
50.00%
4 / 8
0.00% covered (danger)
0.00%
0 / 1
10.50
 maybe_inline_style
n/a
0 / 0
n/a
0 / 0
1
 load_view
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 register_jetpack_connection_tests
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 deprecated_hooks
100.00% covered (success)
100.00%
284 / 284
100.00% covered (success)
100.00%
1 / 1
5
 absolutize_css_urls
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
10
 jetpack_check_heartbeat_data
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
132
 get_jetpack_options_for_reset
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_user_option_meta_box_order_dashboard
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 is_akismet_active
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
90
 get_file_url_for_environment
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_rewind_enabled
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
110
 get_calypso_env
n/a
0 / 0
n/a
0 / 0
1
 get_calypso_host
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 handle_post_authorization_actions
58.33% covered (warning)
58.33%
7 / 12
0.00% covered (danger)
0.00%
0 / 1
5.16
 show_backups_ui
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
20
 show_scan_ui
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 user_meta_cleanup
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 is_active_and_not_offline_mode
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 get_products_for_purchase
0.00% covered (danger)
0.00%
0 / 134
0.00% covered (danger)
0.00%
0 / 1
6
 get_partner_coupon_product_descriptions
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 current_user_can_purchase
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 add_5_star_review_link
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 initialize_tracking
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
6.00
 run_initialize_tracking_action
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 maybe_initialize_rest_jsonapi
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 plugin_post_activation
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
56
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * The mega-class.
4 *
5 * This contains too much, so please think twice before adding more.
6 *
7 * @package automattic/jetpack
8 */
9
10use Automattic\Jetpack\Activity_Log\Jetpack_Activity_Log as Activity_Log_Init;
11use Automattic\Jetpack\Assets;
12use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
13use Automattic\Jetpack\Config;
14use Automattic\Jetpack\Connection\Authorize_Json_Api;
15use Automattic\Jetpack\Connection\Client;
16use Automattic\Jetpack\Connection\Manager as Connection_Manager;
17use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
18use Automattic\Jetpack\Connection\Secrets;
19use Automattic\Jetpack\Connection\Tokens;
20use Automattic\Jetpack\Connection\Webhooks\Authorize_Redirect;
21use Automattic\Jetpack\Constants;
22use Automattic\Jetpack\CookieState;
23use Automattic\Jetpack\Current_Plan as Jetpack_Plan;
24use Automattic\Jetpack\Device_Detection\User_Agent_Info;
25use Automattic\Jetpack\Errors;
26use Automattic\Jetpack\Files;
27use Automattic\Jetpack\Heartbeat;
28use Automattic\Jetpack\Identity_Crisis;
29use Automattic\Jetpack\Import\Main as Import_Main;
30use Automattic\Jetpack\Licensing;
31use Automattic\Jetpack\Modules;
32use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer;
33use Automattic\Jetpack\Newsletter\Reader_Link;
34use Automattic\Jetpack\Paths;
35use Automattic\Jetpack\Plugin\Deprecate;
36use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
37use Automattic\Jetpack\Podcast\Podcast;
38use Automattic\Jetpack\Redirect;
39use Automattic\Jetpack\Scan_Page\Jetpack_Scan as Scan_Page_Init;
40use Automattic\Jetpack\SEO\Initializer as Jetpack_SEO_Initializer;
41use Automattic\Jetpack\Status;
42use Automattic\Jetpack\Status\Host;
43use Automattic\Jetpack\Status\Visitor;
44use Automattic\Jetpack\Sync\Actions as Sync_Actions;
45use Automattic\Jetpack\Sync\Health;
46use Automattic\Jetpack\Sync\Sender;
47use Automattic\Jetpack\Terms_Of_Service;
48use Automattic\Jetpack\Tracking;
49use Automattic\Woocommerce_Analytics;
50
51if ( ! defined( 'ABSPATH' ) ) {
52    exit( 0 );
53}
54
55/*
56Options:
57jetpack_options (array)
58    An array of options.
59    @see Jetpack_Options::get_option_names()
60
61jetpack_register (string)
62    Temporary verification secrets.
63
64jetpack_activated (int)
65    1: the plugin was activated normally
66    2: the plugin was activated on this site because of a network-wide activation
67    3: the plugin was auto-installed
68    4: the plugin was manually disconnected (but is still installed)
69
70jetpack_active_modules (array)
71    Array of active module slugs.
72
73jetpack_do_activate (bool)
74    Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
75*/
76
77require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
78
79/**
80 * The Jetpack class.
81 */
82class Jetpack {
83    /**
84     * Marks that the durable Jetpack SEO module-state options have been reconciled against
85     * the site's module configuration, so the repair runs at most once.
86     *
87     * {@see self::reconcile_seo_module_state_options()}
88     *
89     * @since 16.1
90     *
91     * @var string
92     */
93    const SEO_MODULE_STATE_RECONCILED_OPTION = 'jetpack_seo_module_state_reconciled';
94
95    /**
96     * XMLRPC server instance.
97     *
98     * @var null|Jetpack_XMLRPC_Server XMLRPC server used by Jetpack.
99     */
100    public $xmlrpc_server = null;
101
102    /**
103     * Contains all assets that have had their URL rewritten to minified versions.
104     *
105     * @var array
106     */
107    public static $min_assets = array();
108
109    /**
110     * Plugins to deactivate.
111     *
112     * @var array Plugins to deactivate by module.
113     */
114    public $plugins_to_deactivate = array(
115        'contact-form'        => array(
116            array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
117            array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
118        ),
119        'gravatar-hovercards' => array(
120            array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
121        ),
122        'latex'               => array(
123            array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
124        ),
125        'random-redirect'     => array(
126            array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
127        ),
128        'sharedaddy'          => array(
129            array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
130            array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
131        ),
132        'shortlinks'          => array(
133            array( 'stats/stats.php', 'WordPress.com Stats' ),
134        ),
135        'stats'               => array(
136            array( 'stats/stats.php', 'WordPress.com Stats' ),
137        ),
138        'twitter-widget'      => array(
139            array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
140        ),
141        'videopress'          => array(
142            array( 'video/video.php', 'VideoPress' ),
143        ),
144        'widget-visibility'   => array(
145            array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
146            array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
147        ),
148    );
149
150    /**
151     * Map of roles we care about, and their corresponding minimum capabilities.
152     *
153     * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
154     *
155     * @access public
156     * @static
157     *
158     * @var array
159     */
160    public static $capability_translations = array(
161        'administrator' => 'manage_options',
162        'editor'        => 'edit_others_posts',
163        'author'        => 'publish_posts',
164        'contributor'   => 'edit_posts',
165        'subscriber'    => 'read',
166    );
167
168    /**
169     * Map of modules that have conflicts with plugins and should not be auto-activated
170     * if the plugins are active.  Used by filter_default_modules
171     *
172     * Plugin Authors: If you'd like to prevent a single module from auto-activating,
173     * change `module-slug` and add this to your plugin:
174     *
175     * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
176     * function my_jetpack_get_default_modules( $modules ) {
177     *     return array_diff( $modules, array( 'module-slug' ) );
178     * }
179     *
180     * @var array
181     */
182    private $conflicting_plugins = array(
183        'comments'           => array(
184            'Intense Debate'                 => 'intensedebate/intensedebate.php',
185            'Disqus'                         => 'disqus-comment-system/disqus.php',
186            'Livefyre'                       => 'livefyre-comments/livefyre.php',
187            'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
188            'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
189            'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
190        ),
191        'comment-likes'      => array(
192            'Epoch' => 'epoch/plugincore.php',
193        ),
194        'latex'              => array(
195            'LaTeX for WordPress'     => 'latex/latex.php',
196            'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
197            'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
198            'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
199            'Enable Latex'            => 'enable-latex/enable-latex.php',
200            'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
201        ),
202        'protect'            => array(
203            'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
204            'Captcha'                           => 'captcha/captcha.php',
205            'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
206            'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
207            'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
208            'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
209            'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
210            'Security-protection'               => 'security-protection/security-protection.php',
211            'Login Security'                    => 'login-security/login-security.php',
212            'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
213            'Wordfence Security'                => 'wordfence/wordfence.php',
214            'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
215            'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
216        ),
217        'random-redirect'    => array(
218            'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
219        ),
220        'related-posts'      => array(
221            'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
222            'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
223            'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
224            'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
225            'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
226            'outbrain'                    => 'outbrain/outbrain.php',
227            'Shareaholic'                 => 'shareaholic/shareaholic.php',
228            'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
229        ),
230        'sharedaddy'         => array(
231            'AddThis'     => 'addthis/addthis_social_widget.php',
232            'Add To Any'  => 'add-to-any/add-to-any.php',
233            'ShareThis'   => 'share-this/sharethis.php',
234            'Shareaholic' => 'shareaholic/shareaholic.php',
235        ),
236        'seo-tools'          => array(
237            'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
238            'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
239            'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
240            'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
241            'The SEO Framework'              => 'autodescription/autodescription.php',
242            'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
243            'Slim SEO'                       => 'slim-seo/slim-seo.php',
244            'SEOKEY'                         => 'seo-key/seo-key.php',
245            'SEOKEY Pro'                     => 'seo-key-pro/seo-key.php',
246            'SEOPress'                       => 'wp-seopress/seopress.php',
247            'SEOPress Pro'                   => 'wp-seopress-pro/seopress-pro.php',
248        ),
249        'verification-tools' => array(
250            'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
251            'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
252            'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
253            'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
254            'The SEO Framework'              => 'autodescription/autodescription.php',
255            'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
256            'Slim SEO'                       => 'slim-seo/slim-seo.php',
257        ),
258        'widget-visibility'  => array(
259            'Widget Logic'    => 'widget-logic/widget_logic.php',
260            'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
261        ),
262        'sitemaps'           => array(
263            'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
264            'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
265            'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
266            'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
267            'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
268            'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
269            'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
270            'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
271            'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
272            'The SEO Framework'                    => 'autodescription/autodescription.php',
273            'Sitemap'                              => 'sitemap/sitemap.php',
274            'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
275            'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
276            'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
277            'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
278            'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
279            'Slim SEO'                             => 'slim-seo/slim-seo.php',
280        ),
281    );
282
283    /**
284     * Plugins for which we turn off our Facebook OG Tags implementation.
285     *
286     * Note: the following plugins automatically deactivate Jetpack's Open
287     * Graph tags via filter when their Social Meta modules are active:
288     *
289     * - All in One SEO Pack, All in one SEO Pack Pro
290     * - WordPress SEO by Yoast, WordPress SEO Premium by Yoast
291     *
292     * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
293     * add_filter( 'jetpack_enable_open_graph', '__return_false' );
294     *
295     * @var array Array of plugin slugs.
296     */
297    private $open_graph_conflicting_plugins = array(
298        '2-click-socialmedia-buttons/2-click-socialmedia-buttons.php', // 2 Click Social Media Buttons.
299        'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook.
300        'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags.
301        'complete-open-graph/complete-open-graph.php',           // Complete Open Graph.
302        'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail.
303        'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php', // Open Graph Meta Tags by Heateor.
304        'facebook/facebook.php',                                 // Facebook (official plugin).
305        'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one.
306        'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php', // Facebook Featured Image & OG Meta Tags.
307        'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags.
308        'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php', // Facebook Open Graph Meta Tags for WordPress.
309        'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag.
310        'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer.
311        'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php', // Fedmich's Facebook Open Graph Meta.
312        'network-publisher/networkpub.php',                      // Network Publisher.
313        'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG.
314        'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php', // NextScripts SNAP.
315        'og-tags/og-tags.php',                                   // OG Tags.
316        'opengraph/opengraph.php',                               // Open Graph.
317        'open-graph-protocol-framework/open-graph-protocol-framework.php', // Open Graph Protocol Framework.
318        'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments.
319        'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate.
320        'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic.
321        'shareaholic/sexy-bookmarks.php',                        // Shareaholic.
322        'sharepress/sharepress.php',                             // SharePress.
323        'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect.
324        'social-discussions/social-discussions.php',             // Social Discussions.
325        'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit.
326        'socialize/socialize.php',                               // Socialize.
327        'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLYâ„¢.
328        'only-tweet-like-share-and-google-1/tweet-like-plusone.php', // Tweet, Like, Google +1 and Share.
329        'wordbooker/wordbooker.php',                             // Wordbooker.
330        'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization.
331        'wp-caregiver/wp-caregiver.php',                         // WP Caregiver.
332        'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php', // WP Facebook Like Send & Open Graph Meta.
333        'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol.
334        'wp-ogp/wp-ogp.php',                                     // WP-OGP.
335        'wp-seopress/seopress.php',                              // SEOPress.
336        'wp-seopress-pro/seopress-pro.php',                      // SEOPress Pro.
337        'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin.
338        'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button.
339        'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox.
340        'seo-by-rank-math/rank-math.php',                        // Rank Math.
341        'slim-seo/slim-seo.php',                                 // Slim SEO.
342    );
343
344    /**
345     * Plugins for which we turn off our Twitter Cards Tags implementation.
346     *
347     * @var array Plugins that conflict with Twitter cards.
348     */
349    private $twitter_cards_conflicting_plugins = array(
350        // phpcs:ignore Squiz.PHP.CommentedOutCode.Found
351        // 'twitter/twitter.php',                       // The official one handles this on its own.
352        // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
353            'eewee-twitter-card/index.php',              // Eewee Twitter Card.
354        'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards.
355        'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards.
356        'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',  // Pure Web Brilliant's Social Graph Twitter Cards Extension.
357        'twitter-cards/twitter-cards.php',           // Twitter Cards.
358        'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta.
359        'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter.
360        'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards.
361        'seo-by-rank-math/rank-math.php',            // Rank Math.
362        'slim-seo/slim-seo.php',                     // Slim SEO.
363    );
364
365    /**
366     * Message to display in admin_notice
367     *
368     * @var string
369     */
370    public $message = '';
371
372    /**
373     * Error to display in admin_notice
374     *
375     * @var string
376     */
377    public $error = '';
378
379    /**
380     * Modules that need more privacy description.
381     *
382     * @var string
383     */
384    public $privacy_checks = '';
385
386    /**
387     * Stats to record once the page loads
388     *
389     * @var array
390     */
391    public $stats = array();
392
393    /**
394     * Jetpack_Sync object
395     *
396     * @todo This is also seemingly unused.
397     *
398     * @var object
399     */
400    public $sync;
401
402    /**
403     * Verified data for JSON authorization request
404     *
405     * @deprecated 13.4
406     *
407     * @var array
408     */
409    public $json_api_authorization_request = array();
410
411    /**
412     * Connection manager.
413     *
414     * @var Automattic\Jetpack\Connection\Manager
415     */
416    protected $connection_manager;
417
418    /**
419     * Plugin lock key.
420     *
421     * @var string Transient key used to prevent multiple simultaneous plugin upgrades
422     */
423    public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
424
425    /**
426     * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
427     *
428     * @var Automattic\Jetpack\A8c_Mc_Stats
429     */
430    public $a8c_mc_stats_instance;
431
432    /**
433     * Constant for login redirect key.
434     *
435     * @var string
436     * @since 8.4.0
437     */
438    public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
439
440    /**
441     * Holds the singleton instance of this class
442     *
443     * @since 2.3.3
444     * @var Jetpack
445     */
446    public static $instance = false;
447
448    /**
449     * Resolved answer for `is_premium_analytics_enabled()`, or null before the first call.
450     *
451     * @since 16.1
452     * @var bool|null
453     */
454    private static $premium_analytics_enabled = null;
455
456    /**
457     * Singleton
458     *
459     * @static
460     */
461    public static function init() {
462        if ( ! self::$instance ) {
463            self::$instance = new Jetpack();
464            add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
465            add_action( 'jetpack_idc_disconnect', array( __CLASS__, 'on_idc_disconnect' ) );
466        }
467
468        return self::$instance;
469    }
470
471    /**
472     * Must never be called statically
473     */
474    public function plugin_upgrade() {
475        if ( self::is_connection_ready() ) {
476            list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
477            if ( JETPACK__VERSION !== $version ) {
478                // Prevent multiple upgrades at once - only a single process should trigger an upgrade to avoid stampedes.
479                if ( wp_using_ext_object_cache() ) {
480                    if ( true !== wp_cache_add( self::$plugin_upgrade_lock_key, 1, 'transient', 10 ) ) {
481                        return;
482                    }
483                } else {
484                    if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
485                        return;
486                    }
487
488                    set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
489                }
490
491                // check which active modules actually exist and remove others from active_modules list.
492                $unfiltered_modules = self::get_active_modules();
493                $modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
494                if ( array_diff( $unfiltered_modules, $modules ) ) {
495                    self::update_active_modules( $modules );
496                }
497
498                self::register_upgrade_init_hooks();
499
500                // Upgrade to 4.3.0.
501                if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
502                    Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
503                }
504
505                // Make sure Markdown for posts gets turned back on.
506                if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
507                    update_option( 'wpcom_publish_posts_with_markdown', true );
508                }
509
510                /*
511                 * Minileven deprecation. 8.3.0.
512                 * Only delete options if not using
513                 * the replacement standalone Minileven plugin.
514                 */
515                if (
516                    ! self::is_plugin_active( 'minileven-master/minileven.php' )
517                    && ! self::is_plugin_active( 'minileven/minileven.php' )
518                ) {
519                    if ( get_option( 'wp_mobile_custom_css' ) ) {
520                        delete_option( 'wp_mobile_custom_css' );
521                    }
522                    if ( get_option( 'wp_mobile_excerpt' ) ) {
523                        delete_option( 'wp_mobile_excerpt' );
524                    }
525                    if ( get_option( 'wp_mobile_featured_images' ) ) {
526                        delete_option( 'wp_mobile_featured_images' );
527                    }
528                    if ( get_option( 'wp_mobile_app_promos' ) ) {
529                        delete_option( 'wp_mobile_app_promos' );
530                    }
531                }
532
533                // Upgrade to 8.4.0.
534                if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
535                    Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
536                }
537
538                // Update to 8.8.x (WordPress 5.5 Compatibility).
539                if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
540                    $updated = update_site_option(
541                        'auto_update_plugins',
542                        array_unique(
543                            array_merge(
544                                (array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
545                                (array) get_site_option( 'auto_update_plugins', array() )
546                            )
547                        )
548                    );
549
550                    if ( $updated ) {
551                        Jetpack_Options::delete_option( 'autoupdate_plugins' );
552                    } // Should we have some type of fallback if something fails here?
553                }
554
555                // Set the newsletter send default option for existing sites.
556                if ( false === get_option( 'wpcom_newsletter_send_default' ) ) {
557                    add_option( 'wpcom_newsletter_send_default', 1 );
558                }
559
560                if ( did_action( 'wp_loaded' ) ) {
561                    self::upgrade_on_load();
562                } else {
563                    add_action(
564                        'wp_loaded',
565                        array( __CLASS__, 'upgrade_on_load' )
566                    );
567                }
568            }
569        }
570    }
571
572    /**
573     * Runs upgrade routines that need to have modules loaded.
574     */
575    public static function upgrade_on_load() {
576
577        // Not attempting any upgrades if jetpack_modules_loaded did not fire.
578        // This can happen in case Jetpack has been just upgraded and is
579        // being initialized late during the page load. In this case we wait
580        // until the next proper admin page load with Jetpack active.
581        if ( ! did_action( 'jetpack_modules_loaded' ) ) {
582            delete_transient( self::$plugin_upgrade_lock_key );
583
584            return;
585        }
586
587        self::maybe_set_version_option();
588
589        if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
590            Jetpack_Widget_Conditions::migrate_post_type_rules();
591        }
592
593        if (
594            class_exists( 'Jetpack_Sitemap_Manager' )
595        ) {
596            do_action( 'jetpack_sitemaps_purge_data' );
597        }
598
599        // Delete old stats cache.
600        delete_option( 'jetpack_restapi_stats_cache' );
601
602        delete_transient( self::$plugin_upgrade_lock_key );
603    }
604
605    /**
606     * Saves all the currently active modules to options.
607     * Also fires Action hooks for each newly activated and deactivated module.
608     *
609     * @param array $modules Array of active modules to be saved in options.
610     *
611     * @return bool $success true for success, false for failure.
612     */
613    public static function update_active_modules( $modules ) {
614        return ( new Modules() )->update_active( $modules );
615    }
616
617    /**
618     * Remove all active modules.
619     *
620     * @return void
621     */
622    public static function delete_active_modules() {
623        self::update_active_modules( array() );
624    }
625
626    /**
627     * Adds a hook to plugins_loaded at a priority that's currently the earliest
628     * available.
629     */
630    public function add_configure_hook() {
631        global $wp_filter;
632
633        $current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
634        if ( false !== $current_priority ) {
635            remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
636        }
637
638        $taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
639        sort( $taken_priorities );
640
641        $first_priority = array_shift( $taken_priorities );
642
643        if ( $first_priority <= PHP_INT_MIN ) {
644            $new_priority = PHP_INT_MIN;
645        } else {
646            $new_priority = $first_priority - 1;
647        }
648
649        add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
650    }
651
652    /**
653     * Constructor.  Initializes WordPress hooks
654     */
655    private function __construct() {
656        /*
657         * Check for and alert any deprecated hooks
658         */
659        add_action( 'init', array( $this, 'deprecated_hooks' ) );
660
661        // Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
662        add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
663        add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
664        add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
665        add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
666
667        /**
668         * Prepare Gutenberg Editor functionality
669         *
670         * The hooks previously here have been moved to modules/blocks.php but leaving this here pending
671         * a longer investigation to see if code is expecting the Gutenberg class to always be available.
672         */
673        require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
674        add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
675
676        add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
677
678        add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
679        add_action( 'login_init', array( $this, 'login_init' ) );
680
681        // Set up the REST authentication hooks.
682        Connection_Rest_Authentication::init();
683
684        // Register Jetpack-specific connection tests (sync health, etc.) with the connection
685        // package's health test suite. This runs on all requests (not just admin), because
686        // the connection/test REST endpoint can be called outside admin context.
687        add_action( 'jetpack_connection_tests_loaded', array( $this, 'register_jetpack_connection_tests' ) );
688
689        add_action( 'admin_init', array( $this, 'admin_init' ) );
690        add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
691
692        add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
693
694        // Filter the dashboard meta box order to swap the new one in in place of the old one.
695        add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
696
697        // WordPress dashboard widget.
698        require_once JETPACK__PLUGIN_DIR . 'class-jetpack-stats-dashboard-widget.php';
699        add_action( 'wp_dashboard_setup', array( new Jetpack_Stats_Dashboard_Widget(), 'init' ) );
700
701        // Returns HTTPS support status.
702        add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
703
704        add_action( 'wp_loaded', array( $this, 'register_assets' ) );
705
706        /**
707         * These actions run checks to load additional files.
708         * They check for external files or plugins, so they need to run as late as possible.
709         */
710        add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
711        add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
712        add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
713        add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
714
715        add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
716        add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
717
718        add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
719
720        add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
721        add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
722
723        add_action(
724            'plugins_loaded',
725            function () {
726                if ( User_Agent_Info::is_mobile_app() ) {
727                    add_filter( 'get_edit_post_link', '__return_empty_string' );
728                }
729            }
730        );
731
732        // Update the site's Jetpack plan and products from API on heartbeats.
733        add_action( 'jetpack_heartbeat', array( Jetpack_Plan::class, 'refresh_from_wpcom' ) );
734
735        // The Connection package fetches the site record for `jetpack/v4/site`; reuse it to refresh the plan.
736        add_action( 'jetpack_site_data_fetched', array( Jetpack_Plan::class, 'update_from_site_record' ) );
737
738        // Actually push the stats on shutdown.
739        if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
740            add_action( 'shutdown', array( $this, 'push_stats' ) );
741        }
742
743        // After a successful connection.
744        add_action( 'jetpack_site_registered', array( $this, 'activate_default_modules_on_site_register' ) );
745        add_action( 'jetpack_site_registered', array( $this, 'handle_unique_registrations_stats' ) );
746        add_action( 'jetpack_site_registered', array( Reader_Link::class, 'activate_on_connection' ), 9 );
747        add_action( 'jetpack_site_registered', array( \Automattic\Jetpack\Reprint_Export\Reprint_Exporter::class, 'discard_credentials' ) );
748
749        // Actions for Manager::authorize().
750        add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
751        add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
752        add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
753
754        Jetpack_Client_Server::init();
755        add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
756        add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
757        add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
758        add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
759
760        // Filters for the Manager::get_token() urls and request body.
761        add_filter( 'jetpack_token_redirect_url', array( Authorize_Redirect::class, 'filter_connect_redirect_url' ) );
762        add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
763
764        // Filter for the `jetpack/v4/connection/data` API response.
765        add_filter( 'jetpack_current_user_connection_data', array( __CLASS__, 'filter_jetpack_current_user_connection_data' ) );
766
767        // Actions for successful reconnect.
768        add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
769
770        // Actions for successful disconnect.
771        add_action( 'jetpack_site_disconnected', array( $this, 'jetpack_site_disconnected' ) );
772
773        // Actions for licensing.
774        Licensing::instance()->initialize();
775
776        // Filters for Sync Callables.
777        add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'filter_sync_callable_whitelist' ), 10, 1 );
778        add_filter( 'jetpack_sync_multisite_callable_whitelist', array( $this, 'filter_sync_multisite_callable_whitelist' ), 10, 1 );
779
780        // Make resources use static domain when possible.
781        add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
782
783        // Validate the domain names in Jetpack development versions.
784        add_action( 'jetpack_pre_register', array( static::class, 'registration_check_domains' ) );
785
786        // Register product descriptions for partner coupon usage.
787        add_filter( 'jetpack_partner_coupon_products', array( $this, 'get_partner_coupon_product_descriptions' ) );
788
789        // Actions for conditional recommendations.
790        add_action( 'plugins_loaded', array( 'Jetpack_Recommendations', 'init_conditional_recommendation_actions' ) );
791
792        // Add 5-star
793        add_filter( 'plugin_row_meta', array( $this, 'add_5_star_review_link' ), 10, 2 );
794        add_action( 'init', array( Deprecate::class, 'instance' ) );
795
796        // Register Jetpack module management abilities (WordPress Abilities API, WP 6.9+).
797        \Automattic\Jetpack\Plugin\Abilities\Modules_Abilities::init();
798
799        // Register Connection abilities (WordPress Abilities API, WP 6.9+). Scoped to the
800        // Jetpack plugin for now: the Connection package no longer auto-wires these, so
801        // connection-only consumers (Boost, Protect, Search, etc.) do not register them yet.
802        \Automattic\Jetpack\Connection\Abilities\Connection_Abilities::init();
803    }
804
805    /**
806     * Whether the current request should eagerly initialize the admin/REST-only
807     * packages (the Import package and My Jetpack) now, at `plugins_loaded` time.
808     *
809     * Returns true for admin, cron, POST, and WP-CLI requests â€” the contexts,
810     * knowable this early, where those packages have work to do. Returns false
811     * for a plain front-end GET *and* for a REST request: the two can't be told
812     * apart yet (this runs before `rest_api_init`), so callers defer the REST
813     * case by initializing the package on `rest_api_init` instead, while a plain
814     * page view never fires that hook and so loads nothing. This keeps
815     * admin/REST-only PHP out of opcache on the front-end GET hot path.
816     *
817     * No in-repo code depends on the deferral. The one externally observable
818     * change is timing: the packages' documented init hooks
819     * (`jetpack_import_initialized`, `jetpack_feature_import_enabled`, and
820     * `my_jetpack_init`) no longer fire on a plain front-end GET â€” they fire on
821     * the admin, cron, POST, WP-CLI, and REST requests where the packages load.
822     *
823     * @return bool
824     */
825    private static function should_eager_load_packages() {
826        $is_post_request = isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) );
827        $is_wp_cli       = Constants::is_true( 'WP_CLI' );
828
829        return is_admin() || wp_doing_cron() || $is_post_request || $is_wp_cli;
830    }
831
832    /**
833     * Configure the Import package from a deferred hook.
834     *
835     * The eager path uses Config::ensure( 'import' ), but the deferred REST path
836     * runs after Config::on_plugins_loaded() has already processed its feature
837     * flags, so it needs a hookable bootstrap callback. Preserve Config's
838     * feature-enabled action for hook consumers.
839     *
840     * @since 16.0
841     *
842     * @return void
843     */
844    public static function configure_import_package() {
845        if ( class_exists( Import_Main::class ) ) {
846            Import_Main::configure();
847
848            if ( ! did_action( 'jetpack_feature_import_enabled' ) ) {
849                do_action( 'jetpack_feature_import_enabled' );
850            }
851        }
852    }
853
854    /**
855     * Whether the bundled Stats v2 dashboard is enabled.
856     *
857     * Stats v2 (formerly "Premium Analytics") ships with the plugin behind this
858     * flag while it rolls out (WOOA7S-1595). When enabled it adds its own admin
859     * menu alongside the existing Stats UI; it never replaces or hides the
860     * legacy Stats menu, admin-bar entries, post-list column, or WP dashboard
861     * widget. The Stats module's tracking is unaffected either way, and Stats v2
862     * reads what that module collects, so while the module is off the plugin
863     * answers false here before even reading the flag.
864     *
865     * The package has to be loadable for this to be true, so a site with the
866     * flag on but a missing package answers false here and never adds the
867     * Stats v2 menu (a warning is logged instead).
868     *
869     * @since 16.1
870     *
871     * @return bool
872     */
873    public static function is_premium_analytics_enabled() {
874        if ( null !== self::$premium_analytics_enabled ) {
875            return self::$premium_analytics_enabled;
876        }
877
878        if ( ! self::is_module_active( 'stats' ) ) {
879            self::$premium_analytics_enabled = false;
880            return false;
881        }
882
883        /**
884         * Filters whether the bundled Premium Analytics dashboard is enabled.
885         *
886         * Resolved once, from `Jetpack::configure()` on `plugins_loaded`, and only
887         * while the Stats module is active. Register this from a mu-plugin or a
888         * plugin's main file â€” a callback added on `plugins_loaded` or later runs
889         * too late to be seen.
890         *
891         * @since 16.1
892         *
893         * @param bool $enabled Defaults to the `jetpack_premium_analytics_enabled` option (false).
894         */
895        $flag = (bool) apply_filters( 'jetpack_premium_analytics_enabled', (bool) get_option( 'jetpack_premium_analytics_enabled' ) );
896
897        self::$premium_analytics_enabled = $flag && class_exists( 'Automattic\Jetpack\PremiumAnalytics\Analytics' );
898
899        if ( $flag && ! self::$premium_analytics_enabled ) {
900            wp_trigger_error(
901                __METHOD__,
902                'The jetpack_premium_analytics_enabled flag is on but the Premium Analytics package is not loadable; keeping the Stats UI in place.'
903            );
904        }
905
906        return self::$premium_analytics_enabled;
907    }
908
909    /**
910     * Expose the setting that turns the Premium Analytics dashboard on and off.
911     *
912     * Deliberately not behind is_premium_analytics_enabled(): this is the setting that flips that
913     * check, so it has to answer while the dashboard is still off.
914     *
915     * @since 16.2
916     *
917     * @return void
918     */
919    public static function register_premium_analytics_enablement_setting() {
920        if ( class_exists( 'Automattic\Jetpack\PremiumAnalytics\Enablement_Setting' ) ) {
921            \Automattic\Jetpack\PremiumAnalytics\Enablement_Setting::register();
922        }
923    }
924
925    /**
926     * Before everything else starts getting initalized, we need to initialize Jetpack using the
927     * Config object.
928     */
929    public function configure() {
930        $config = new Config();
931
932        foreach (
933            array(
934                'jitm',
935                'sync',
936                'account_protection',
937                'waf',
938            )
939            as $feature
940        ) {
941            $config->ensure( $feature );
942        }
943
944        // Enable the VideoPress admin UI (the "Jetpack > VideoPress" dashboard) inside the
945        // Jetpack plugin, mirroring the standalone Jetpack VideoPress plugin. The dashboard
946        // only renders when the VideoPress module is active (Status::is_active()); when it
947        // is not, the menu item links to the My Jetpack interstitial to activate it.
948        $config->ensure( 'videopress', array( 'admin_ui' => true ) );
949
950        /*
951         * The Import package only registers `jetpack/v4/import` REST routes â€” it
952         * does nothing when rendering a front-end page â€” so gate its `ensure()`
953         * to keep its PHP out of opcache on the front-end GET hot path. It still
954         * loads on admin, cron, POST, and WP-CLI requests, and on `rest_api_init`
955         * for REST: a REST request can't be identified yet at `plugins_loaded`
956         * (this runs before `Config::on_plugins_loaded`, and `rest_api_init`
957         * fires later), so it is initialized directly when that hook fires, while
958         * a plain page view never fires it and so loads nothing.
959         *
960         * JITM stays eager (above): unlike Import, its `register()` adds a
961         * `jetpack_sync_before_send_updated_option` filter that records the
962         * `jetpack_last_plugin_sync` transient, and a Jetpack Sync send can fire
963         * on a plain front-end GET â€” including the dedicated-sync `spawn-sync`
964         * GET, which runs on `init` and exits before `rest_api_init`. Deferring
965         * JITM would skip that bookkeeping and leave its message cache stale after
966         * a plugin change, so it loads on every request as before.
967         */
968        if ( self::should_eager_load_packages() ) {
969            $config->ensure( 'import' );
970        } else {
971            add_action(
972                'rest_api_init',
973                array( __CLASS__, 'configure_import_package' ),
974                0
975            );
976        }
977
978        /*
979         * The Stats and Stats Admin packages only do work when the Stats module
980         * is active (the front-end tracking pixel) or on wp-admin, REST, cron,
981         * POST, and WP-CLI requests: the Stats dashboard page, the stats /
982         * stats-app REST endpoints (which the block editor also calls for
983         * email-open rates), the transient-cleanup cron, the connection
984         * package's package-version tracker (which runs on POSTs and reads the
985         * `jetpack_package_versions` filter that Stats registers), and CLI
986         * introspection such as the heartbeat inspector. On a plain front-end
987         * GET page view with the module off they are inert: the pixel
988         * short-circuits on `Stats\Main::should_track()` and every other entry
989         * point only hooks rest_api_init, admin, cron, the POST-only tracker, or
990         * is reached through WP-CLI.
991         * Skip loading them â€” and eagerly constructing the Stats Admin REST
992         * controller â€” on that hot path to keep their PHP out of opcache, but
993         * keep loading them everywhere else exactly as before so the stats REST
994         * permission mapping (view_stats, registered by Stats\Main), the
995         * editor's stats-app calls, the cleanup cron, and the package-version
996         * tracker are all unchanged.
997         *
998         * REST requests are not yet identifiable here (REST_REQUEST is defined
999         * after plugins_loaded), so defer those to rest_api_init. Call the
1000         * package initializers directly rather than `$config->ensure()`: ensure()
1001         * only flags a feature for `Config::on_plugins_loaded()` (plugins_loaded
1002         * priority 2), which has already run by the time rest_api_init fires.
1003         * Priority 0 runs before each package's own priority-10 route
1004         * registration, so their routes still register within the same dispatch.
1005         * A plain page view never fires rest_api_init, so the packages stay
1006         * unloaded there. See JETPACK-1747.
1007         */
1008        $is_post_request = isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'];
1009        $is_wp_cli       = defined( 'WP_CLI' ) && WP_CLI;
1010
1011        if ( self::is_module_active( 'stats' ) || is_admin() || wp_doing_cron() || $is_post_request || $is_wp_cli ) {
1012            $config->ensure( 'stats' );
1013            $config->ensure( 'stats_admin' );
1014        } else {
1015            add_action(
1016                'rest_api_init',
1017                static function () {
1018                    if ( class_exists( 'Automattic\Jetpack\Stats\Main' ) ) {
1019                        \Automattic\Jetpack\Stats\Main::init();
1020                    }
1021                    if ( class_exists( 'Automattic\Jetpack\Stats_Admin\Main' ) ) {
1022                        \Automattic\Jetpack\Stats_Admin\Main::init();
1023                    }
1024                },
1025                0
1026            );
1027        }
1028
1029        // Stats v2 (WOOA7S-1595). Unlike Stats above it cannot be deferred when enabled â€” see
1030        // Analytics::init() for why, and for why it takes no menu_title here.
1031        if ( self::is_premium_analytics_enabled() ) {
1032            \Automattic\Jetpack\PremiumAnalytics\Analytics::init();
1033        }
1034
1035        // Outside the check above on purpose â€” see Enablement_Setting. Deferred like Stats, to keep
1036        // the autoload off the front-end hot path.
1037        add_action( 'rest_api_init', array( __CLASS__, 'register_premium_analytics_enablement_setting' ), 0 );
1038
1039        $config->ensure(
1040            'connection',
1041            array(
1042                'slug' => 'jetpack',
1043                'name' => 'Jetpack',
1044            )
1045        );
1046
1047        // Identity crisis package.
1048        $config->ensure(
1049            'identity_crisis',
1050            array(
1051                'slug'       => 'jetpack',
1052                'admin_page' => '/wp-admin/admin.php?page=jetpack',
1053            )
1054        );
1055
1056        $config->ensure( 'search' );
1057
1058        if ( ! $this->connection_manager ) {
1059            $this->connection_manager = new Connection_Manager( 'jetpack' );
1060        }
1061
1062        $modules = new Automattic\Jetpack\Modules();
1063        if ( $modules->is_active( 'publicize' ) && $this->connection_manager->has_connected_user() ) {
1064            $config->ensure( 'publicize' );
1065        }
1066
1067        add_action( 'jetpack_initialize_tracking', array( $this, 'initialize_tracking' ) );
1068
1069        /*
1070         * Load things that should only be in Network Admin.
1071         *
1072         * For now blow away everything else until a more full
1073         * understanding of what is needed at the network level is
1074         * available
1075         */
1076        if ( is_multisite() ) {
1077            $network = Jetpack_Network::init();
1078            $network->set_connection( $this->connection_manager );
1079        }
1080
1081        $is_connection_ready = self::is_connection_ready();
1082
1083        if ( $is_connection_ready ) {
1084            add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
1085            $this->run_initialize_tracking_action();
1086
1087            Jetpack_Heartbeat::init();
1088            if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
1089                require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
1090                Jetpack_Search_Performance_Logger::init();
1091            }
1092        } else {
1093            add_action( 'jetpack_agreed_to_terms_of_service', array( $this, 'run_initialize_tracking_action' ) );
1094            add_action( 'rest_api_init', array( $this, 'run_initialize_tracking_action' ) );
1095            add_filter(
1096                'xmlrpc_methods',
1097                function ( $methods ) {
1098                    $this->run_initialize_tracking_action();
1099                    return $methods;
1100                },
1101                1
1102            );
1103        }
1104
1105        // Initialize remote file upload request handlers.
1106        $this->add_remote_request_handlers();
1107
1108        /*
1109         * Enable enhanced handling of previewing sites in Calypso
1110         */
1111        if ( $is_connection_ready ) {
1112            require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
1113            add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
1114            add_action( 'rest_api_init', array( $this, 'maybe_initialize_rest_jsonapi' ) );
1115        }
1116    }
1117
1118    /**
1119     * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
1120     * initialization code.
1121     *
1122     * @action plugins_loaded
1123     */
1124    public function late_initialization() {
1125        add_action( 'after_setup_theme', array( 'Jetpack', 'load_modules' ), -2 );
1126
1127        /*
1128         * My Jetpack is a wp-admin dashboard. Its Initializer::init() only wires
1129         * up admin-menu, admin_init, and rest_api_init surfaces â€” and eagerly
1130         * loads every product class (backup, boost, protect, â€¦) just to register
1131         * admin plugin-action links â€” so none of it is needed on a plain
1132         * front-end GET page view. (The pieces that do immediate work, e.g.
1133         * Connection REST authentication and Licensing, are already initialized
1134         * unconditionally in Jetpack's constructor, so they are unaffected here.)
1135         *
1136         * Gate the call to the request types where My Jetpack actually does work.
1137         * REST can't be detected yet at plugins_loaded, so initialize on
1138         * rest_api_init for that branch; a plain page view never fires it, so My
1139         * Jetpack stays unloaded there.
1140         */
1141        if ( self::should_eager_load_packages() ) {
1142            My_Jetpack_Initializer::init();
1143        } else {
1144            add_action( 'rest_api_init', array( My_Jetpack_Initializer::class, 'init' ), 0 );
1145        }
1146
1147        Activity_Log_Init::initialize();
1148        Scan_Page_Init::initialize();
1149        Jetpack_SEO_Initializer::init();
1150
1151        if ( ( new Modules() )->is_active( 'podcast' ) ) {
1152            Podcast::init();
1153        }
1154
1155        /*
1156         * Initialize Boost Speed Score. It only does work on REST requests (the
1157         * dashboard speed-score endpoints) and on a few Jetpack Boost lifecycle
1158         * actions, so defer constructing it â€” and loading the boost-speed-score
1159         * package classes â€” until one of those hooks actually fires instead of on
1160         * every request. Priority 0 ensures the object's own callbacks (added in
1161         * its constructor at the default priority) still run for the firing hook.
1162         */
1163        $initialize_speed_score = static function () {
1164            static $initialized = false;
1165            if ( $initialized ) {
1166                return;
1167            }
1168            $initialized = true;
1169            new Speed_Score( array(), 'jetpack-dashboard' );
1170        };
1171        add_action( 'rest_api_init', $initialize_speed_score, 0 );
1172        add_action( 'jetpack_boost_deactivate', $initialize_speed_score, 0 );
1173        add_action( 'jetpack_boost_environment_changed', $initialize_speed_score, 0 );
1174        add_action( 'handle_environment_change', $initialize_speed_score, 0 );
1175
1176        /**
1177         * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
1178         * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
1179         *
1180         * @since 8.1.0
1181         *
1182         * @param Jetpack $jetpack the main plugin class object.
1183         */
1184        do_action( 'jetpack_loaded', $this );
1185
1186        add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 2 );
1187    }
1188
1189    /**
1190     * This is ported over from the manage module, which has been deprecated and baked in here.
1191     */
1192    public function add_wpcom_to_allowed_redirect_hosts() {
1193        add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
1194    }
1195
1196    /**
1197     * Return $domains, with 'wordpress.com' appended.
1198     * This is ported over from the manage module, which has been deprecated and baked in here.
1199     *
1200     * @param array $domains Array of domains allowed for redirect.
1201     *
1202     * @return array
1203     */
1204    public function allow_wpcom_domain( $domains ) {
1205        if ( empty( $domains ) ) {
1206            $domains = array();
1207        }
1208        $domains[] = 'wordpress.com';
1209        return array_unique( $domains );
1210    }
1211
1212    /**
1213     * Redirect edit post links to Calypso.
1214     *
1215     * @deprecated since 13.9
1216     *
1217     * @param string $default_url Post edit URL.
1218     * @param int    $post_id Post ID.
1219     *
1220     * @return string
1221     */
1222    public function point_edit_post_links_to_calypso( $default_url, $post_id ) {
1223        _deprecated_function( __METHOD__, '13.9' );
1224
1225        $post = get_post( $post_id );
1226
1227        if ( empty( $post ) ) {
1228            return $default_url;
1229        }
1230
1231        $post_type = $post->post_type;
1232
1233        // Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1234        // https://en.support.wordpress.com/custom-post-types/.
1235        $allowed_post_types = array(
1236            'post',
1237            'page',
1238            'jetpack-portfolio',
1239            'jetpack-testimonial',
1240        );
1241
1242        if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1243            return $default_url;
1244        }
1245
1246        return Redirect::get_url(
1247            'calypso-edit-' . $post_type,
1248            array(
1249                'path' => $post_id,
1250            )
1251        );
1252    }
1253
1254    /**
1255     * Redirect edit comment links to Calypso.
1256     *
1257     * @deprecated since 13.9
1258     *
1259     * @param string $url Comment edit URL.
1260     *
1261     * @return string
1262     */
1263    public function point_edit_comment_links_to_calypso( $url ) {
1264        _deprecated_function( __METHOD__, '13.9' );
1265
1266        // Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1267        $query_args = null;
1268        wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
1269
1270        return Redirect::get_url(
1271            'calypso-edit-comment',
1272            array(
1273                'path' => $query_args['amp;c'],
1274            )
1275        );
1276    }
1277
1278    /**
1279     * Extend Sync callables with Jetpack Plugin functions.
1280     *
1281     * @param array $callables list of callables.
1282     *
1283     * @return array list of callables.
1284     */
1285    public function filter_sync_callable_whitelist( $callables ) {
1286        // Jetpack Functions.
1287        $jetpack_callables = array(
1288            'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1289            'updates'                  => array( 'Jetpack', 'get_updates' ),
1290            'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1291        );
1292        return array_merge( $callables, $jetpack_callables );
1293    }
1294
1295    /**
1296     * Extend Sync multisite callables with Jetpack Plugin functions.
1297     *
1298     * @param array $callables list of callables.
1299     *
1300     * @return array list of callables.
1301     */
1302    public function filter_sync_multisite_callable_whitelist( $callables ) {
1303
1304        // Jetpack Funtions.
1305        $jetpack_multisite_callables = array(
1306            'network_name'                        => array( 'Jetpack', 'network_name' ),
1307            'network_allow_new_registrations'     => array( 'Jetpack', 'network_allow_new_registrations' ),
1308            'network_add_new_users'               => array( 'Jetpack', 'network_add_new_users' ),
1309            'network_site_upload_space'           => array( 'Jetpack', 'network_site_upload_space' ),
1310            'network_upload_file_types'           => array( 'Jetpack', 'network_upload_file_types' ),
1311            'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1312        );
1313        $callables                   = array_merge( $callables, $jetpack_multisite_callables );
1314
1315        return $callables;
1316    }
1317
1318    /**
1319     * If there are any stats that need to be pushed, but haven't been, push them now.
1320     */
1321    public function push_stats() {
1322        if ( ! empty( $this->stats ) ) {
1323            $this->do_stats( 'server_side' );
1324        }
1325    }
1326
1327    /**
1328     * Sets the Jetpack custom capabilities.
1329     *
1330     * @param string[] $caps    Array of the user's capabilities.
1331     * @param string   $cap     Capability name.
1332     */
1333    public function jetpack_custom_caps( $caps, $cap ) {
1334        switch ( $cap ) {
1335            case 'jetpack_manage_autoupdates':
1336                $caps = array(
1337                    'manage_options',
1338                    'update_plugins',
1339                );
1340                break;
1341            case 'jetpack_network_admin_page':
1342            case 'jetpack_network_settings_page':
1343                $caps = array( 'manage_network_plugins' );
1344                break;
1345            case 'jetpack_network_sites_page':
1346                $caps = array( 'manage_sites' );
1347                break;
1348            case 'jetpack_admin_page':
1349                $is_offline_mode = ( new Status() )->is_offline_mode();
1350                if ( $is_offline_mode ) {
1351                    $caps = array( 'manage_options' );
1352                    break;
1353                } else {
1354                    $caps = array( 'edit_posts' );
1355                }
1356                break;
1357        }
1358        return $caps;
1359    }
1360
1361    /**
1362     * Register assets for use in various modules and the Jetpack admin page.
1363     *
1364     * @uses wp_script_is, wp_register_script, plugins_url
1365     * @action wp_loaded
1366     * @return void
1367     */
1368    public function register_assets() {
1369        if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1370            wp_register_script(
1371                'jetpack-gallery-settings',
1372                Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1373                array( 'media-views' ),
1374                '20121225',
1375                true
1376            );
1377        }
1378
1379        if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1380            wp_register_script(
1381                'jetpack-twitter-timeline',
1382                Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1383                array(),
1384                '4.0.0',
1385                true
1386            );
1387        }
1388
1389        if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1390            wp_register_script(
1391                'jetpack-facebook-embed',
1392                Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1393                array(),
1394                JETPACK__VERSION,
1395                true
1396            );
1397
1398            /** This filter is documented in modules/sharedaddy/sharing-sources.php */
1399            $fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1400            if ( ! is_numeric( $fb_app_id ) ) {
1401                $fb_app_id = '';
1402            }
1403            wp_localize_script(
1404                'jetpack-facebook-embed',
1405                'jpfbembed',
1406                array(
1407                    'appid'  => $fb_app_id,
1408                    'locale' => $this->get_locale(),
1409                )
1410            );
1411        }
1412
1413        /**
1414         * As jetpack_register_genericons is by default fired off a hook,
1415         * the hook may have already fired by this point.
1416         * So, let's just trigger it manually.
1417         */
1418        require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1419        jetpack_register_genericons();
1420
1421        /**
1422         * Register the social logos
1423         */
1424        require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1425        jetpack_register_social_logos();
1426    }
1427
1428    /**
1429     * Guess locale from language code.
1430     *
1431     * @param string $lang Language code.
1432     * @return string|bool
1433     */
1434    public function guess_locale_from_lang( $lang ) {
1435        if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1436            return 'en_US';
1437        }
1438
1439        if ( ! class_exists( 'GP_Locales' ) ) {
1440            if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1441                return false;
1442            }
1443
1444            require JETPACK__GLOTPRESS_LOCALES_PATH;
1445        }
1446
1447        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1448            // WP.com: get_locale() returns 'it'.
1449            $locale = GP_Locales::by_slug( $lang );
1450        } else {
1451            // Jetpack: get_locale() returns 'it_IT';.
1452            $locale = GP_Locales::by_field( 'facebook_locale', $lang );
1453        }
1454
1455        if ( ! $locale ) {
1456            return false;
1457        }
1458
1459        if ( empty( $locale->facebook_locale ) ) {
1460            if ( empty( $locale->wp_locale ) ) {
1461                return false;
1462            } else {
1463                // Facebook SDK is smart enough to fall back to en_US if a
1464                // locale isn't supported. Since supported Facebook locales
1465                // can fall out of sync, we'll attempt to use the known
1466                // wp_locale value and rely on said fallback.
1467                return $locale->wp_locale;
1468            }
1469        }
1470
1471        return $locale->facebook_locale;
1472    }
1473
1474    /**
1475     * Get the locale.
1476     *
1477     * @return string|bool
1478     */
1479    public function get_locale() {
1480        $locale = $this->guess_locale_from_lang( get_locale() );
1481
1482        if ( ! $locale ) {
1483            $locale = 'en_US';
1484        }
1485
1486        return $locale;
1487    }
1488
1489    /**
1490     * Return the network_site_url so that .com knows what network this site is a part of.
1491     *
1492     * @return string
1493     */
1494    public function jetpack_main_network_site_option() {
1495        return network_site_url();
1496    }
1497    /**
1498     * Network Name.
1499     */
1500    public static function network_name() {
1501        global $current_site;
1502        return $current_site->site_name;
1503    }
1504    /**
1505     * Does the network allow new user and site registrations.
1506     *
1507     * @return string
1508     */
1509    public static function network_allow_new_registrations() {
1510        return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ), true ) ? get_site_option( 'registration' ) : 'none' );
1511    }
1512    /**
1513     * Does the network allow admins to add new users.
1514     *
1515     * @return bool
1516     */
1517    public static function network_add_new_users() {
1518        return (bool) get_site_option( 'add_new_users' );
1519    }
1520    /**
1521     * File upload psace left per site in MB.
1522     *  -1 means NO LIMIT.
1523     *
1524     * @return int
1525     */
1526    public static function network_site_upload_space() {
1527        // value in MB.
1528        return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1529    }
1530
1531    /**
1532     * Network allowed file types.
1533     *
1534     * @return string
1535     */
1536    public static function network_upload_file_types() {
1537        return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1538    }
1539
1540    /**
1541     * Maximum file upload size set by the network.
1542     *
1543     * @return int
1544     */
1545    public static function network_max_upload_file_size() {
1546        // value in KB.
1547        return get_site_option( 'fileupload_maxk', 300 );
1548    }
1549
1550    /**
1551     * Lets us know if a site allows admins to manage the network.
1552     *
1553     * @return array
1554     */
1555    public static function network_enable_administration_menus() {
1556        return get_site_option( 'menu_items' );
1557    }
1558
1559    /**
1560     * If a user has been promoted to or demoted from admin, we need to clear the
1561     * jetpack_other_linked_admins transient.
1562     *
1563     * @since 4.3.2
1564     * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1565     *
1566     * @param int    $user_id   The user ID whose role changed.
1567     * @param string $role      The new role.
1568     * @param array  $old_roles An array of the user's previous roles.
1569     */
1570    public function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1571        if ( 'administrator' === $role
1572            || ( is_array( $old_roles ) && in_array( 'administrator', $old_roles, true ) )
1573            || $old_roles === null
1574        ) {
1575            delete_transient( 'jetpack_other_linked_admins' );
1576        }
1577    }
1578
1579    /**
1580     * Checks to see if there are any other users available to become primary
1581     * Users must both:
1582     * - Be linked to wpcom
1583     * - Be an admin
1584     *
1585     * @return mixed False if no other users are linked, Int if there are.
1586     */
1587    public static function get_other_linked_admins() {
1588        $other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1589
1590        if ( false === $other_linked_users ) {
1591            $admins = get_users( array( 'role' => 'administrator' ) );
1592            if ( count( $admins ) > 1 ) {
1593                $available = array();
1594                foreach ( $admins as $admin ) {
1595                    if ( self::connection()->is_user_connected( $admin->ID ) ) {
1596                        $available[] = $admin->ID;
1597                    }
1598                }
1599
1600                $count_connected_admins = count( $available );
1601                if ( count( $available ) > 1 ) {
1602                    $other_linked_users = $count_connected_admins;
1603                } else {
1604                    $other_linked_users = 0;
1605                }
1606            } else {
1607                $other_linked_users = 0;
1608            }
1609
1610            set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1611        }
1612
1613        return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1614    }
1615
1616    /**
1617     * Return whether we are dealing with a multi network setup or not.
1618     * The reason we are type casting this is because we want to avoid the situation where
1619     * the result is false since when is_main_network_option return false it cases
1620     * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1621     * database which could be set to anything as opposed to what this function returns.
1622     *
1623     * @return boolean
1624     */
1625    public function is_main_network_option() {
1626        // returns either an '1' or an empty string.
1627        return (string) (bool) self::is_multi_network();
1628    }
1629
1630    /**
1631     * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1632     *
1633     * @return string
1634     */
1635    public function is_multisite() {
1636        return (string) (bool) is_multisite();
1637    }
1638
1639    /**
1640     * Implemented since there is no core is multi network function
1641     * Right now there is no way to tell if we which network is the dominant network on the system
1642     *
1643     * @since  3.3
1644     * @return boolean
1645     */
1646    public static function is_multi_network() {
1647        global  $wpdb;
1648
1649        // if we don't have a multi site setup no need to do any more.
1650        if ( ! is_multisite() ) {
1651            return false;
1652        }
1653
1654        $num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1655        if ( $num_sites > 1 ) {
1656            return true;
1657        } else {
1658            return false;
1659        }
1660    }
1661
1662    /**
1663     * Get back if the current site is single user site.
1664     *
1665     * @return bool
1666     */
1667    public static function is_single_user_site() {
1668        global $wpdb;
1669
1670        $some_users = get_transient( 'jetpack_is_single_user' );
1671        if ( false === $some_users ) {
1672            $some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1673            set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1674        }
1675        return 1 === (int) $some_users;
1676    }
1677
1678    /**
1679     * Returns true if the site has file write access false otherwise.
1680     *
1681     * @return string ( '1' | '0' )
1682     **/
1683    public static function file_system_write_access() {
1684        if ( ! function_exists( 'get_filesystem_method' ) ) {
1685            require_once ABSPATH . 'wp-admin/includes/file.php';
1686        }
1687
1688        require_once ABSPATH . 'wp-admin/includes/template.php';
1689
1690        $filesystem_method = get_filesystem_method();
1691        if ( 'direct' === $filesystem_method ) {
1692            return 1;
1693        }
1694
1695        ob_start();
1696        $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1697        ob_end_clean();
1698        if ( $filesystem_credentials_are_stored ) {
1699            return 1;
1700        }
1701        return 0;
1702    }
1703
1704    // phpcs:disable WordPress.WP.CapitalPDangit.MisspelledInComment
1705    /**
1706     * Gets updates and stores in jetpack_updates.
1707     *
1708     * The jetpack_updates option is saved in the following schema:
1709     *
1710     * array (
1711     *      'plugins'                       => (int) Number of plugin updates available.
1712     *      'themes'                        => (int) Number of theme updates available.
1713     *      'wordpress'                     => (int) Number of WordPress core updates available.
1714     *      'translations'                  => (int) Number of translation updates available.
1715     *      'total'                         => (int) Total of all available updates.
1716     *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1717     * )
1718     *
1719     * @return array
1720     */
1721    public static function get_updates() {
1722        $updates     = array();
1723        $update_data = wp_get_update_data();
1724
1725        // Stores the individual update counts as well as the total count.
1726        if ( isset( $update_data['counts'] ) ) {
1727            $updates = $update_data['counts'];
1728        }
1729
1730        // If we need to update WordPress core, let's find the latest version number.
1731        if ( ! empty( $updates['wordpress'] ) ) {
1732            $cur = get_preferred_from_update_core();
1733            if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1734                $updates['wp_update_version'] = $cur->current;
1735            }
1736        }
1737        return $updates;
1738    }
1739    // phpcs:enable WordPress.WP.CapitalPDangit.MisspelledInComment
1740
1741    /**
1742     * Get update details for core, plugins, and themes.
1743     *
1744     * @return array
1745     */
1746    public static function get_update_details() {
1747        $update_details = array(
1748            'update_core'    => get_site_transient( 'update_core' ),
1749            'update_plugins' => get_site_transient( 'update_plugins' ),
1750            'update_themes'  => get_site_transient( 'update_themes' ),
1751        );
1752        return $update_details;
1753    }
1754
1755    /**
1756     * Is Jetpack active?
1757     * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1758     *
1759     * This method is deprecated since 9.6.0. Please use one of the methods provided by the Manager class in the Connection package,
1760     * or Jetpack::is_connection_ready if you want to know when the Jetpack plugin starts considering the connection ready to be used.
1761     *
1762     * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
1763     *
1764     * @deprecated 9.6.0
1765     *
1766     * @return bool
1767     */
1768    public static function is_active() {
1769        return self::connection()->has_connected_owner();
1770    }
1771
1772    /**
1773     * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1774     *
1775     * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1776     * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1777     * users and this option will be available by default for everybody.
1778     *
1779     * @since 9.6.0
1780     * @since 9.7.0 returns is_connected in all cases and adds filter to the returned value
1781     *
1782     * @return bool is the site connection ready to be used?
1783     */
1784    public static function is_connection_ready() {
1785        /**
1786         * Allows filtering whether the connection is ready to be used. If true, this will enable the Jetpack UI and modules
1787         *
1788         * Modules will be enabled depending on the connection status and if the module requires a connection or user connection.
1789         *
1790         * @since 9.7.0
1791         *
1792         * @param bool                                  $is_connection_ready Is the connection ready?
1793         * @param Automattic\Jetpack\Connection\Manager $connection_manager Instance of the Manager class, can be used to check the connection status.
1794         */
1795        return apply_filters( 'jetpack_is_connection_ready', self::connection()->is_connected(), self::connection() );
1796    }
1797
1798    /**
1799     * Determines reason for Jetpack offline mode.
1800     */
1801    public static function development_mode_trigger_text() {
1802        $status = new Status();
1803
1804        if ( ! $status->is_offline_mode() ) {
1805            return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1806        }
1807
1808        if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1809            $notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1810        } elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1811            $notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1812        } elseif ( $status->is_local_site() ) {
1813            $notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1814        } elseif ( get_option( 'jetpack_offline_mode' ) ) {
1815            $notice = __( 'The jetpack_offline_mode option is set to true.', 'jetpack' );
1816        } else {
1817            $notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1818        }
1819
1820        return $notice;
1821    }
1822    /**
1823     * Get Jetpack offline mode notice text and notice class.
1824     *
1825     * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1826     */
1827    public static function show_development_mode_notice() {
1828        if ( ( new Status() )->is_offline_mode() ) {
1829            $notice = sprintf(
1830                /* translators: %s is a URL */
1831                __( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1832                esc_url( Redirect::get_url( 'jetpack-support-development-mode' ) )
1833            );
1834
1835            $notice .= ' ' . self::development_mode_trigger_text();
1836
1837            echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All provided text.
1838        }
1839
1840        // Throw up a notice if using a development version and as for feedback.
1841        if ( self::is_development_version() ) {
1842            /* translators: %s is a URL */
1843            $notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), esc_url( Redirect::get_url( 'jetpack-contact-support-beta-group' ) ) );
1844
1845            echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All provided text.
1846        }
1847    }
1848
1849    /**
1850     * Whether Jetpack's version maps to a public release, or a development version.
1851     */
1852    public static function is_development_version() {
1853        /**
1854         * Allows filtering whether this is a development version of Jetpack.
1855         *
1856         * This filter is especially useful for tests.
1857         *
1858         * @since 4.3.0
1859         *
1860         * @param bool $development_version Is this a develoment version of Jetpack?
1861         */
1862        return (bool) apply_filters(
1863            'jetpack_development_version',
1864            ! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1865        );
1866    }
1867
1868    /**
1869     * Get the wpcom email of the current|specified connected user.
1870     *
1871     * @param null|int $user_id User ID or will use get_current_user_id if null.
1872     */
1873    public static function get_connected_user_email( $user_id = null ) {
1874        if ( ! $user_id ) {
1875            $user_id = get_current_user_id();
1876        }
1877
1878        $xml = new Jetpack_IXR_Client(
1879            array(
1880                'user_id' => $user_id,
1881            )
1882        );
1883        $xml->query( 'wpcom.getUserEmail' );
1884        if ( ! $xml->isError() ) {
1885            return $xml->getResponse();
1886        }
1887        return false;
1888    }
1889
1890    /**
1891     * Get the wpcom email of the master user.
1892     */
1893    public static function get_master_user_email() {
1894        $master_user_id = Jetpack_Options::get_option( 'master_user' );
1895        if ( $master_user_id ) {
1896            return self::get_connected_user_email( $master_user_id );
1897        }
1898        return '';
1899    }
1900
1901    /**
1902     * Gets current user IP address.
1903     *
1904     * @param  bool $check_all_headers Check all headers? Default is `false`.
1905     *
1906     * @deprecated Jetpack 10.6
1907     *
1908     * @return string                  Current user IP address.
1909     */
1910    public static function current_user_ip( $check_all_headers = false ) {
1911        _deprecated_function( __METHOD__, 'jetpack-10.6', 'Automattic\\Jetpack\\Status\\Visitor::get_ip' );
1912
1913        return ( new Visitor() )->get_ip( $check_all_headers );
1914    }
1915
1916    /**
1917     * Loads the currently active modules.
1918     */
1919    public static function load_modules() {
1920        $status = new Status();
1921
1922        if (
1923            ! self::is_connection_ready()
1924            && ! $status->is_offline_mode()
1925            && (
1926                ! is_multisite()
1927                || ! get_site_option( 'jetpack_protect_active' )
1928            )
1929        ) {
1930            return;
1931        }
1932
1933        $version = Jetpack_Options::get_option( 'version' );
1934        if ( ! $version ) {
1935            $version     = JETPACK__VERSION . ':' . time();
1936            $old_version = $version;
1937            /** This action is documented in class.jetpack.php */
1938            do_action( 'updating_jetpack_version', $version, false );
1939            Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1940        }
1941        list( $version ) = explode( ':', $version );
1942
1943        $modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1944
1945        $modules_data = array();
1946
1947        // Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1948        if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1949            $updated_modules = array();
1950            foreach ( $modules as $module ) {
1951                $modules_data[ $module ] = self::get_module( $module );
1952                if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1953                    continue;
1954                }
1955
1956                if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1957                    continue;
1958                }
1959
1960                $updated_modules[] = $module;
1961            }
1962
1963            $modules = array_diff( $modules, $updated_modules );
1964        }
1965
1966        $is_site_connection = false;
1967
1968        if ( method_exists( self::connection(), 'is_site_connection' ) ) {
1969            $is_site_connection = self::connection()->is_site_connection();
1970        }
1971
1972        foreach ( $modules as $index => $module ) {
1973            // If we're in offline/site-connection mode, disable modules requiring a connection/user connection.
1974            if ( $status->is_offline_mode() || $is_site_connection ) {
1975                // Prime the pump if we need to.
1976                if ( empty( $modules_data[ $module ] ) ) {
1977                    $modules_data[ $module ] = self::get_module( $module );
1978                }
1979                // If the module requires a connection, but we're in local mode, don't include it.
1980                if ( $status->is_offline_mode() && $modules_data[ $module ]['requires_connection'] ) {
1981                    continue;
1982                }
1983
1984                if ( $is_site_connection && $modules_data[ $module ]['requires_user_connection'] ) {
1985                    continue;
1986                }
1987            }
1988
1989            if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1990                continue;
1991            }
1992
1993            if ( ! include_once self::get_module_path( $module ) ) { // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.NotAbsolutePath
1994                unset( $modules[ $index ] );
1995                self::update_active_modules( array_values( $modules ) );
1996                continue;
1997            }
1998
1999            /**
2000             * Fires when a specific module is loaded.
2001             * The dynamic part of the hook, $module, is the module slug.
2002             *
2003             * @since 1.1.0
2004             */
2005            do_action( 'jetpack_module_loaded_' . $module );
2006        }
2007
2008        /**
2009         * Fires when all the modules are loaded.
2010         *
2011         * @since 1.1.0
2012         */
2013        do_action( 'jetpack_modules_loaded' );
2014
2015        // Load module-specific code that is needed even when a module isn't active. Loaded here because code contained therein may need actions such as setup_theme.
2016        require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2017    }
2018
2019    /**
2020     * Check if Jetpack's REST API compat file should be included
2021     *
2022     * @action plugins_loaded
2023     * @return void
2024     */
2025    public function check_rest_api_compat() {
2026        /**
2027         * Filters the list of REST API compat files to be included.
2028         *
2029         * @since 2.2.5
2030         *
2031         * @param array $args Array of REST API compat files to include.
2032         */
2033        $_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2034
2035        foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2036            require_once $_jetpack_rest_api_compat_include;
2037        }
2038    }
2039
2040    /**
2041     * Gets all plugins currently active in values, regardless of whether they're
2042     * traditionally activated or network activated.
2043     *
2044     * @todo Store the result in core's object cache maybe?
2045     */
2046    public static function get_active_plugins() {
2047        // Delegates to the canonical implementation in the Connection package.
2048        return Heartbeat::get_active_plugins();
2049    }
2050
2051    /**
2052     * Gets and parses additional plugin data to send with the heartbeat data
2053     *
2054     * @since 3.8.1
2055     *
2056     * @return array Array of plugin data
2057     */
2058    public static function get_parsed_plugin_data() {
2059        if ( ! function_exists( 'get_plugins' ) ) {
2060            require_once ABSPATH . 'wp-admin/includes/plugin.php';
2061        }
2062        /** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2063        $all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2064        $active_plugins = self::get_active_plugins();
2065
2066        $plugins = array();
2067        foreach ( $all_plugins as $path => $plugin_data ) {
2068            $plugins[ $path ] = array(
2069                'is_active' => in_array( $path, $active_plugins, true ),
2070                'file'      => $path,
2071                'name'      => $plugin_data['Name'],
2072                'version'   => $plugin_data['Version'],
2073                'author'    => $plugin_data['Author'],
2074            );
2075        }
2076
2077        return $plugins;
2078    }
2079
2080    /**
2081     * Gets and parses theme data to send with the heartbeat data
2082     *
2083     * @since 3.8.1
2084     *
2085     * @return array Array of theme data
2086     */
2087    public static function get_parsed_theme_data() {
2088        $all_themes  = wp_get_themes( array( 'allowed' => true ) );
2089        $header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2090
2091        $themes = array();
2092        foreach ( $all_themes as $slug => $theme_data ) {
2093            $theme_headers = array();
2094            foreach ( $header_keys as $header_key ) {
2095                $theme_headers[ $header_key ] = $theme_data->get( $header_key );
2096            }
2097
2098            $themes[ $slug ] = array(
2099                'is_active_theme' => wp_get_theme()->get_template() === $slug,
2100                'slug'            => $slug,
2101                'theme_root'      => $theme_data->get_theme_root_uri(),
2102                'parent'          => $theme_data->parent(),
2103                'headers'         => $theme_headers,
2104            );
2105        }
2106
2107        return $themes;
2108    }
2109
2110    /**
2111     * Checks whether a specific plugin is active.
2112     *
2113     * We don't want to store these in a static variable, in case
2114     * there are switch_to_blog() calls involved.
2115     *
2116     * @param string $plugin Plugin to check in 'folder/file.php` format.
2117     */
2118    public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2119        return in_array( $plugin, self::get_active_plugins(), true );
2120    }
2121
2122    /**
2123     * Check if Jetpack's Open Graph tags should be used.
2124     * If certain plugins are active, Jetpack's og tags are suppressed.
2125     *
2126     * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2127     * @action plugins_loaded
2128     * @return void
2129     */
2130    public function check_open_graph() {
2131        if ( in_array( 'publicize', self::get_active_modules(), true ) || in_array( 'sharedaddy', self::get_active_modules(), true ) ) {
2132            include_once JETPACK__PLUGIN_DIR . 'enhanced-open-graph.php';
2133            add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2134        }
2135
2136        $active_plugins = self::get_active_plugins();
2137
2138        if ( ! empty( $active_plugins ) ) {
2139            foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2140                if ( in_array( $plugin, $active_plugins, true ) ) {
2141                    add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2142                    break;
2143                }
2144            }
2145        }
2146
2147        /**
2148         * Allow the addition of Open Graph Meta Tags to all pages.
2149         *
2150         * @since 2.0.3
2151         *
2152         * @param bool false Should Open Graph Meta tags be added. Default to false.
2153         */
2154        if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2155            require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2156        }
2157    }
2158
2159    /**
2160     * Check if Jetpack's Twitter tags should be used.
2161     * If certain plugins are active, Jetpack's twitter tags are suppressed.
2162     *
2163     * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2164     * @action plugins_loaded
2165     * @return void
2166     */
2167    public function check_twitter_tags() {
2168
2169        $active_plugins = self::get_active_plugins();
2170
2171        if ( ! empty( $active_plugins ) ) {
2172            foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2173                if ( in_array( $plugin, $active_plugins, true ) ) {
2174                    add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2175                    break;
2176                }
2177            }
2178        }
2179
2180        /**
2181         * Allow Twitter Card Meta tags to be disabled.
2182         *
2183         * @since 2.6.0
2184         *
2185         * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2186         */
2187        if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2188            // @todo Remove this require once the deprecated Jetpack_Twitter_Cards wrapper has been removed.
2189            // Twitter Cards functionality now lives in the jetpack-post-media package (Automattic\Jetpack\Post_Media\Twitter_Cards).
2190            require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2191        }
2192    }
2193
2194    /* Jetpack Options API */
2195
2196    /**
2197     * Gets the option names from Jetpack_Options.
2198     *
2199     * @param string $type Jetpack option type.
2200     *
2201     * @return array
2202     */
2203    public static function get_option_names( $type = 'compact' ) {
2204        return Jetpack_Options::get_option_names( $type );
2205    }
2206
2207    /**
2208     * Returns the requested option.
2209     *
2210     * Looks in jetpack_options or jetpack_$name as appropriate.
2211     *
2212     * @param string $name    Option name.
2213     * @param mixed  $default Default value.
2214     */
2215    public static function get_option( $name, $default = false ) {
2216        return Jetpack_Options::get_option( $name, $default );
2217    }
2218
2219    /**
2220     * Returns an array of all PHP files in the specified absolute path.
2221     * Equivalent to glob( "$absolute_path/*.php" ).
2222     *
2223     * @param string $absolute_path The absolute path of the directory to search.
2224     * @return array Array of absolute paths to the PHP files.
2225     */
2226    public static function glob_php( $absolute_path ) {
2227        return ( new Files() )->glob_php( $absolute_path );
2228    }
2229
2230    /**
2231     * Activate new modules.
2232     *
2233     * @param bool $redirect Should this function redirect after activation.
2234     *
2235     * @return void
2236     */
2237    public static function activate_new_modules( $redirect = false ) {
2238        if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2239            return;
2240        }
2241
2242        $jetpack_old_version = Jetpack_Options::get_option( 'version' );
2243        if ( ! $jetpack_old_version ) {
2244            $old_version         = '1.1:' . time();
2245            $version             = $old_version;
2246            $jetpack_old_version = $version;
2247            /** This action is documented in class.jetpack.php */
2248            do_action( 'updating_jetpack_version', $version, false );
2249            Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2250        }
2251
2252        list( $jetpack_version ) = explode( ':', $jetpack_old_version );
2253
2254        if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2255            return;
2256        }
2257
2258        $active_modules     = self::get_active_modules();
2259        $reactivate_modules = array();
2260        foreach ( $active_modules as $active_module ) {
2261            $module = self::get_module( $active_module );
2262            if ( ! isset( $module['changed'] ) ) {
2263                continue;
2264            }
2265
2266            if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2267                continue;
2268            }
2269
2270            $reactivate_modules[] = $active_module;
2271            self::deactivate_module( $active_module );
2272        }
2273
2274        $new_version = JETPACK__VERSION . ':' . time();
2275        /** This action is documented in class.jetpack.php */
2276        do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2277        Jetpack_Options::update_options(
2278            array(
2279                'version'     => $new_version,
2280                'old_version' => $jetpack_old_version,
2281            )
2282        );
2283
2284        self::state( 'message', 'modules_activated' );
2285
2286        self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
2287
2288        if ( $redirect ) {
2289            $page = 'jetpack'; // make sure we redirect to either settings or the jetpack page.
2290            if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ), true ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- we're not changing the site.
2291                $page = sanitize_text_field( wp_unslash( $_GET['page'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- we're not changing the site.
2292            }
2293            wp_safe_redirect( self::admin_url( 'page=' . rawurlencode( $page ) ) );
2294            exit( 0 );
2295        }
2296    }
2297
2298    /**
2299     * List available Jetpack modules. Simply lists .php files in /modules/.
2300     * Make sure to tuck away module "library" files in a sub-directory.
2301     *
2302     * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2303     * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2304     * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2305     * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2306     *
2307     * @return array $modules Array of module slugs
2308     */
2309    public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2310        return ( new Modules() )->get_available( $min_version, $max_version, $requires_connection, $requires_user_connection );
2311    }
2312
2313    /**
2314     * Get default modules loaded on activation.
2315     *
2316     * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2317     * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2318     * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2319     * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2320     *
2321     * @return array $modules Array of module slugs
2322     */
2323    public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2324        $return = array();
2325
2326        foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2327            $module_data = self::get_module( $module );
2328
2329            switch ( strtolower( $module_data['auto_activate'] ) ) {
2330                case 'yes':
2331                    $return[] = $module;
2332                    break;
2333                case 'public':
2334                    if ( Jetpack_Options::get_option( 'public' ) ) {
2335                        $return[] = $module;
2336                    }
2337                    break;
2338                case 'no':
2339                default:
2340                    break;
2341            }
2342        }
2343        /**
2344         * Filters the array of default modules.
2345         *
2346         * @since 2.5.0
2347         *
2348         * @param array $return Array of default modules.
2349         * @param string $min_version Minimum version number required to use modules.
2350         * @param string $max_version Maximum version number required to use modules.
2351         * @param bool|null $requires_connection Value of the Requires Connection filter.
2352         * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2353         */
2354        return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version, $requires_connection, $requires_user_connection );
2355    }
2356
2357    /**
2358     * Checks activated modules during auto-activation to determine
2359     * if any of those modules are being deprecated.  If so, close
2360     * them out, and add any replacement modules.
2361     *
2362     * Runs at priority 99 by default.
2363     *
2364     * This is run late, so that it can still activate a module if
2365     * the new module is a replacement for another that the user
2366     * currently has active, even if something at the normal priority
2367     * would kibosh everything.
2368     *
2369     * @since 2.6
2370     * @uses jetpack_get_default_modules filter
2371     * @param array $modules Array of Jetpack modules.
2372     * @return array
2373     */
2374    public function handle_deprecated_modules( $modules ) {
2375        $deprecated_modules = array(
2376            'debug'                 => null,  // Closed out and moved to the debugger library.
2377            'wpcc'                  => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2378            'gplus-authorship'      => null,  // Closed out in 3.2 -- Google dropped support.
2379            'minileven'             => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2380            'lazy-images'           => null, // Closed out in 12.8 -- WordPress core now has native lazy loading.
2381            'enhanced-distribution' => null, // Closed out in 13.3 -- WP.com is winding down the firehose.
2382        );
2383
2384        // Don't activate SSO if they never completed activating WPCC.
2385        if ( self::is_module_active( 'wpcc' ) ) {
2386            $wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2387            if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2388                $deprecated_modules['wpcc'] = null;
2389            }
2390        }
2391
2392        foreach ( $deprecated_modules as $module => $replacement ) {
2393            if ( self::is_module_active( $module ) ) {
2394                self::deactivate_module( $module );
2395                if ( $replacement ) {
2396                    $modules[] = $replacement;
2397                }
2398            }
2399        }
2400
2401        return array_unique( $modules );
2402    }
2403
2404    /**
2405     * Checks activated plugins during auto-activation to determine
2406     * if any of those plugins are in the list with a corresponding module
2407     * that is not compatible with the plugin. The module will not be allowed
2408     * to auto-activate.
2409     *
2410     * @since 2.6
2411     * @uses jetpack_get_default_modules filter
2412     * @param array $modules Array of Jetpack modules.
2413     * @return array
2414     */
2415    public function filter_default_modules( $modules ) {
2416
2417        $active_plugins = self::get_active_plugins();
2418
2419        if ( ! empty( $active_plugins ) ) {
2420
2421            // For each module we'd like to auto-activate...
2422            foreach ( $modules as $key => $module ) {
2423                // If there are potential conflicts for it...
2424                if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2425                    // For each potential conflict...
2426                    foreach ( $this->conflicting_plugins[ $module ] as $plugin ) {
2427                        // If that conflicting plugin is active...
2428                        if ( in_array( $plugin, $active_plugins, true ) ) {
2429                            // Remove that item from being auto-activated.
2430                            unset( $modules[ $key ] );
2431                        }
2432                    }
2433                }
2434            }
2435        }
2436
2437        // Special case to convert block setting to a block module.
2438        $block_key = array_search( 'blocks', $modules, true );
2439        if ( $block_key !== false ) { // Only care if 'blocks' made it through the previous filters.
2440            $block_option = get_option( 'jetpack_blocks_disabled', null );
2441            if ( $block_option ) {
2442                unset( $modules[ $block_key ] );
2443            }
2444        }
2445
2446        return $modules;
2447    }
2448
2449    /**
2450     * Extract a module's slug from its full path.
2451     *
2452     * @param string $file Full path to a file.
2453     *
2454     * @return string Module slug.
2455     */
2456    public static function get_module_slug( $file ) {
2457        return ( new Modules() )->get_slug( $file );
2458    }
2459
2460    /**
2461     * Generate a module's path from its slug.
2462     *
2463     * @param string $slug Module slug.
2464     */
2465    public static function get_module_path( $slug ) {
2466        return ( new Modules() )->get_path( $slug );
2467    }
2468
2469    /**
2470     * Load module data from module file. Headers differ from WordPress
2471     * plugin headers to avoid them being identified as standalone
2472     * plugins on the WordPress plugins page.
2473     *
2474     * @param string $module The module slug.
2475     */
2476    public static function get_module( $module ) {
2477        return ( new Modules() )->get( $module );
2478    }
2479
2480    /**
2481     * Like core's get_file_data implementation, but caches the result.
2482     *
2483     * @param string $file Absolute path to the file.
2484     * @param array  $headers List of headers, in the format array( 'HeaderKey' => 'Header Name' ).
2485     */
2486    public static function get_file_data( $file, $headers ) {
2487        return ( new Modules() )->get_file_data( $file, $headers );
2488    }
2489
2490    /**
2491     * Return translated module tag.
2492     *
2493     * @param string $tag Tag as it appears in each module heading.
2494     *
2495     * @return mixed
2496     */
2497    public static function translate_module_tag( $tag ) {
2498        return jetpack_get_module_i18n_tag( $tag );
2499    }
2500
2501    /**
2502     * Return module name translation. Uses matching string created in modules/module-headings.php.
2503     *
2504     * @since 3.9.2
2505     *
2506     * @param array $modules Array of Jetpack modules.
2507     *
2508     * @return string|void
2509     */
2510    public static function get_translated_modules( $modules ) {
2511        foreach ( $modules as $index => $module ) {
2512            $i18n_module = jetpack_get_module_i18n( $module['module'] );
2513            if ( isset( $module['name'] ) ) {
2514                $modules[ $index ]['name'] = $i18n_module['name'];
2515            }
2516            if ( isset( $module['description'] ) ) {
2517                $modules[ $index ]['description']       = $i18n_module['description'];
2518                $modules[ $index ]['short_description'] = $i18n_module['description'];
2519            }
2520            if ( isset( $module['module_tags'] ) ) {
2521                $modules[ $index ]['module_tags'] = array_map( 'jetpack_get_module_i18n_tag', $module['module_tags'] );
2522            }
2523        }
2524        return $modules;
2525    }
2526
2527    /**
2528     * Get a list of activated modules as an array of module slugs.
2529     */
2530    public static function get_active_modules() {
2531        return ( new Modules() )->get_active();
2532    }
2533
2534    /**
2535     * Check whether or not a Jetpack module is active.
2536     *
2537     * @param string $module The slug of a Jetpack module.
2538     * @return bool
2539     *
2540     * @static
2541     */
2542    public static function is_module_active( $module ) {
2543        return ( new Modules() )->is_active( $module );
2544    }
2545
2546    /**
2547     * Is slug a valid module.
2548     *
2549     * @param string $module Module slug.
2550     *
2551     * @return bool
2552     */
2553    public static function is_module( $module ) {
2554        return ( new Modules() )->is_module( $module );
2555    }
2556
2557    /**
2558     * Catches PHP errors.  Must be used in conjunction with output buffering.
2559     *
2560     * @deprecated since 13.5
2561     * @param bool $catch True to start catching, False to stop.
2562     *
2563     * @static
2564     * @deprecated 13.5
2565     * @see \Automattic\Jetpack\Errors
2566     */
2567    public static function catch_errors( $catch ) {
2568        _deprecated_function( __METHOD__, '13.5' );
2569        // @phan-suppress-next-line PhanDeprecatedClass
2570        return ( new Errors() )->catch_errors( $catch );
2571    }
2572
2573    /**
2574     * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2575     *
2576     * @deprecated since 13.5
2577     */
2578    public static function catch_errors_on_shutdown() {
2579        _deprecated_function( __METHOD__, '13.5' );
2580        self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2581    }
2582
2583    /**
2584     * Rewrite any string to make paths easier to read.
2585     *
2586     * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2587     * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2588     *
2589     * @param string $string String to attempt rewrite.
2590     * @return mixed
2591     */
2592    public static function alias_directories( $string ) {
2593        // ABSPATH has a trailing slash.
2594        $string = str_replace( ABSPATH, 'ABSPATH/', $string );
2595        // WP_CONTENT_DIR does not have a trailing slash.
2596        $string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2597
2598        return $string;
2599    }
2600
2601    /**
2602     * Activates default Jetpack modules.
2603     *
2604     * @param null|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2605     * @param null|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2606     * @param array       $other_modules Other modules to activate.
2607     * @param null|bool   $redirect Should there be a redirection after activation.
2608     * @param bool        $send_state_messages If a state message should be sent.
2609     * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2610     * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2611     *
2612     * @return void
2613     */
2614    public static function activate_default_modules(
2615        $min_version = false,
2616        $max_version = false,
2617        $other_modules = array(),
2618        $redirect = null,
2619        $send_state_messages = null,
2620        $requires_connection = null,
2621        $requires_user_connection = null
2622    ) {
2623        $jetpack = self::init();
2624
2625        if ( $redirect === null ) {
2626            if (
2627                ( defined( 'REST_REQUEST' ) && REST_REQUEST )
2628            ||
2629                ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2630            ||
2631                ( defined( 'WP_CLI' ) && WP_CLI )
2632            ||
2633                ( defined( 'DOING_CRON' ) && DOING_CRON )
2634            ||
2635                ( defined( 'DOING_AJAX' ) && DOING_AJAX )
2636            ) {
2637                $redirect = false;
2638            } elseif ( is_admin() ) {
2639                $redirect = true;
2640            } else {
2641                $redirect = false;
2642            }
2643        }
2644
2645        if ( $send_state_messages === null ) {
2646            $send_state_messages = current_user_can( 'jetpack_activate_modules' );
2647        }
2648
2649        $modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2650        $modules = array_merge( $other_modules, $modules );
2651
2652        // Look for standalone plugins and disable if active.
2653
2654        $to_deactivate = array();
2655        foreach ( $modules as $module ) {
2656            if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2657                $to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2658            }
2659        }
2660
2661        $deactivated = array();
2662        foreach ( $to_deactivate as $module => $deactivate_us ) {
2663            foreach ( $deactivate_us as $i => $deactivate_me ) {
2664                list( $probable_file, $probable_title ) = $deactivate_me;
2665                if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2666                    $deactivated[] = "$module:$i";
2667                }
2668            }
2669        }
2670
2671        if ( $deactivated ) {
2672            if ( $send_state_messages ) {
2673                self::state( 'deactivated_plugins', implode( ',', $deactivated ) );
2674            }
2675
2676            if ( $redirect ) {
2677                $url = add_query_arg(
2678                    array(
2679                        'action'   => 'activate_default_modules',
2680                        '_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2681                    ),
2682                    add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2683                );
2684                wp_safe_redirect( $url );
2685                exit( 0 );
2686            }
2687        }
2688
2689        /**
2690         * Fires before default modules are activated.
2691         *
2692         * @since 1.9.0
2693         *
2694         * @param string    $min_version Minimum version number required to use modules.
2695         * @param string    $max_version Maximum version number required to use modules.
2696         * @param array     $other_modules Array of other modules to activate alongside the default modules.
2697         * @param bool|null $requires_connection Value of the Requires Connection filter.
2698         * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2699         */
2700        do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
2701
2702        // Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating.
2703        if ( $send_state_messages ) {
2704            self::restate();
2705        }
2706
2707        $active = self::get_active_modules();
2708
2709        foreach ( $modules as $module ) {
2710            if ( did_action( "jetpack_module_loaded_$module" ) ) {
2711                $active[] = $module;
2712                self::update_active_modules( $active );
2713                continue;
2714            }
2715
2716            if ( $send_state_messages && in_array( $module, $active, true ) ) {
2717                $module_info = self::get_module( $module );
2718                if ( ! $module_info['deactivate'] ) {
2719                    $state        = in_array( $module, $other_modules, true ) ? 'reactivated_modules' : 'activated_modules';
2720                    $active_state = self::state( $state );
2721                    if ( $active_state ) {
2722                        $active_state = explode( ',', $active_state );
2723                    } else {
2724                        $active_state = array();
2725                    }
2726                    $active_state[] = $module;
2727                    self::state( $state, implode( ',', $active_state ) );
2728                }
2729                continue;
2730            }
2731
2732            $file = self::get_module_path( $module );
2733            if ( ! file_exists( $file ) ) {
2734                continue;
2735            }
2736
2737            // we'll override this later if the plugin can be included without fatal error.
2738            if ( $redirect ) {
2739                wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2740            }
2741
2742            if ( $send_state_messages ) {
2743                self::state( 'error', 'module_activation_failed' );
2744                self::state( 'module', $module );
2745            }
2746
2747            ob_start();
2748            require_once $file;
2749
2750            $active[] = $module;
2751
2752            if ( $send_state_messages ) {
2753
2754                $state        = in_array( $module, $other_modules, true ) ? 'reactivated_modules' : 'activated_modules';
2755                $active_state = self::state( $state );
2756                if ( $active_state ) {
2757                    $active_state = explode( ',', $active_state );
2758                } else {
2759                    $active_state = array();
2760                }
2761                $active_state[] = $module;
2762                self::state( $state, implode( ',', $active_state ) );
2763            }
2764
2765            self::update_active_modules( $active );
2766
2767            ob_end_clean();
2768        }
2769
2770        if ( $send_state_messages ) {
2771            self::state( 'error', false );
2772            self::state( 'module', false );
2773        }
2774        /**
2775         * Fires when default modules are activated.
2776         *
2777         * @since 1.9.0
2778         *
2779         * @param string    $min_version Minimum version number required to use modules.
2780         * @param string    $max_version Maximum version number required to use modules.
2781         * @param array     $other_modules Array of other modules to activate alongside the default modules.
2782         * @param bool|null $requires_connection Value of the Requires Connection filter.
2783         * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2784         */
2785        do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
2786    }
2787
2788    /**
2789     * Activate a module.
2790     *
2791     * @param string $module Module slug.
2792     * @param bool   $exit Should exit be called after deactivation.
2793     * @param bool   $redirect Should there be a redirection after activation.
2794     *
2795     * @return bool|void
2796     */
2797    public static function activate_module( $module, $exit = true, $redirect = true ) {
2798        return ( new Modules() )->activate( $module, $exit, $redirect );
2799    }
2800
2801    /**
2802     * Deactivate module.
2803     *
2804     * @param string $module Module slug.
2805     *
2806     * @return bool
2807     */
2808    public static function deactivate_module( $module ) {
2809        return ( new Modules() )->deactivate( $module );
2810    }
2811
2812    /**
2813     * Enable a configuable module.
2814     *
2815     * @param string $module Module slug.
2816     *
2817     * @return void
2818     */
2819    public static function enable_module_configurable( $module ) {
2820        $module = self::get_module_slug( $module );
2821        add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2822    }
2823
2824    /**
2825     * Composes a module configure URL. It uses Jetpack settings search as default value
2826     * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
2827     *
2828     * @param string $module Module slug.
2829     * @return string $url module configuration URL.
2830     */
2831    public static function module_configuration_url( $module ) {
2832        $module      = self::get_module_slug( $module );
2833        $default_url = self::admin_url() . "#/settings?term=$module";
2834        /**
2835         * Allows to modify configure_url of specific module to be able to redirect to some custom location.
2836         *
2837         * @since 6.9.0
2838         *
2839         * @param string $default_url Default url, which redirects to jetpack settings page.
2840         */
2841        $url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
2842
2843        return $url;
2844    }
2845
2846    /* Installation */
2847    /**
2848     * Bail on activation if there is an issue.
2849     *
2850     * @param string $message Error message.
2851     * @param bool   $deactivate Deactivate Jetpack or not.
2852     *
2853     * @return never
2854     */
2855    public static function bail_on_activation( $message, $deactivate = true ) {
2856        ?>
2857<!doctype html>
2858<html>
2859<head>
2860<meta charset="<?php bloginfo( 'charset' ); ?>">
2861<style>
2862* {
2863    text-align: center;
2864    margin: 0;
2865    padding: 0;
2866    font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2867}
2868p {
2869    margin-top: 1em;
2870    font-size: 18px;
2871}
2872</style>
2873<body>
2874<p><?php echo esc_html( $message ); ?></p>
2875</body>
2876</html>
2877        <?php
2878        if ( $deactivate ) {
2879            $plugins = get_option( 'active_plugins' );
2880            $jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2881            $update  = false;
2882            foreach ( $plugins as $i => $plugin ) {
2883                if ( $plugin === $jetpack ) {
2884                    $plugins[ $i ] = false;
2885                    $update        = true;
2886                }
2887            }
2888
2889            if ( $update ) {
2890                update_option( 'active_plugins', array_filter( $plugins ) );
2891            }
2892        }
2893        exit( 0 );
2894    }
2895
2896    /**
2897     * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2898     *
2899     * @param bool $network_wide Network-wide activation.
2900     */
2901    public static function plugin_activation( $network_wide ) {
2902        Jetpack_Options::update_option( 'activated', 1 );
2903
2904        if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2905            /* translators: Jetpack version number. */
2906            self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2907        }
2908
2909        if ( $network_wide ) {
2910            self::state( 'network_nag', true );
2911        }
2912
2913        // For firing one-off events (notices) immediately after activation.
2914        set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
2915
2916        update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
2917
2918        Health::on_jetpack_activated();
2919
2920        \Automattic\Jetpack\Reprint_Export\Reprint_Exporter::discard_credentials();
2921
2922        if ( self::is_connection_ready() && method_exists( 'Automattic\Jetpack\Sync\Actions', 'do_only_first_initial_sync' ) ) {
2923            Sync_Actions::do_only_first_initial_sync();
2924        }
2925
2926        if ( ! defined( 'WC_ANALYTICS' ) && class_exists( 'Automattic\Woocommerce_Analytics' ) ) {
2927            Woocommerce_Analytics::maybe_add_proxy_speed_module();
2928        }
2929
2930        self::plugin_initialize();
2931    }
2932
2933    /**
2934     * Returns the activation source.
2935     *
2936     * @param string $referer_url URL.
2937     *
2938     * @return array source_type, source_query.
2939     */
2940    public static function get_activation_source( $referer_url ) {
2941        if ( defined( 'WP_CLI' ) && WP_CLI ) {
2942            return array( 'wp-cli', null );
2943        }
2944
2945        $referer = wp_parse_url( $referer_url );
2946
2947        $source_type  = 'unknown';
2948        $source_query = null;
2949
2950        if ( ! is_array( $referer ) || ! isset( $referer['path'] ) ) {
2951            return array( $source_type, $source_query );
2952        }
2953
2954        $plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
2955        $plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
2956
2957        if ( isset( $referer['query'] ) ) {
2958            parse_str( $referer['query'], $query_parts );
2959        } else {
2960            $query_parts = array();
2961        }
2962
2963        if ( $plugins_path === $referer['path'] ) {
2964            $source_type = 'list';
2965        } elseif ( $plugins_install_path === $referer['path'] ) {
2966            $tab = $query_parts['tab'] ?? 'featured';
2967            switch ( $tab ) {
2968                case 'popular':
2969                    $source_type = 'popular';
2970                    break;
2971                case 'recommended':
2972                    $source_type = 'recommended';
2973                    break;
2974                case 'favorites':
2975                    $source_type = 'favorites';
2976                    break;
2977                case 'search':
2978                    $source_type  = 'search-' . ( $query_parts['type'] ?? 'term' );
2979                    $source_query = $query_parts['s'] ?? null;
2980                    break;
2981                default:
2982                    $source_type = 'featured';
2983            }
2984        }
2985
2986        return array( $source_type, $source_query );
2987    }
2988
2989    /**
2990     * Runs before bumping version numbers up to a new version.
2991     *
2992     * Only ever registered the hooks for the release post update modal, which has been removed.
2993     * No longer hooked to `updating_jetpack_version`.
2994     *
2995     * @deprecated 16.2
2996     *
2997     * @param string $version     Version:timestamp.
2998     * @param string $old_version Old Version:timestamp or false if not set yet.
2999     */
3000    public static function do_version_bump( $version, $old_version ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Signature preserved for the deprecation shim.
3001        _deprecated_function( __METHOD__, 'jetpack-16.2' );
3002    }
3003
3004    /**
3005     * Enables the Newsletter (subscriptions) module for existing sites now that it is a default-on module.
3006     *
3007     * Fresh installs receive the module via its "Auto Activate: Yes" header, so this only handles sites
3008     * upgrading from a version where the module defaulted off. It runs once per site (guarded by the
3009     * subscriptions_default_on_migrated option). Fresh installs are marked as migrated immediately so the
3010     * migration never runs for them. After it has run, the user's choice to deactivate the module again
3011     * (for example from the My Jetpack Products page) is respected and never reverted.
3012     *
3013     * The module requires a connection, so on a disconnected site the migration is deferred without setting
3014     * the guard, allowing a later version bump to retry once the site is connected.
3015     *
3016     * @param string       $version     New Jetpack version:timestamp.
3017     * @param string|false $old_version Previous Jetpack version:timestamp, or false on a fresh install.
3018     */
3019    public static function activate_subscriptions_module_for_existing_sites( $version, $old_version ) {
3020        if ( get_option( 'jetpack_subscriptions_default_on_migrated' ) ) {
3021            return;
3022        }
3023
3024        // Fresh installs get the module via its "Auto Activate: Yes" header. Mark them as migrated so a
3025        // later opt-out is never reverted by the existing-site path on a subsequent version bump.
3026        if ( ! $old_version ) {
3027            update_option( 'jetpack_subscriptions_default_on_migrated', true );
3028            return;
3029        }
3030
3031        if ( ! self::is_connection_ready() ) {
3032            return;
3033        }
3034
3035        // Mark as migrated only once the module is active, so a transient activation failure is retried on
3036        // a later version bump rather than being silently skipped.
3037        if ( self::is_module_active( 'subscriptions' ) || self::activate_module( 'subscriptions', false, false ) ) {
3038            update_option( 'jetpack_subscriptions_default_on_migrated', true );
3039        }
3040    }
3041
3042    /**
3043     * Option flag that records the AI master-switch opt-out reconciliation has run,
3044     * so it never runs twice.
3045     *
3046     * @var string
3047     */
3048    const AI_MASTER_OPTOUT_MIGRATED_OPTION = 'jetpack_ai_master_optout_migrated';
3049
3050    /**
3051     * Register the on-upgrade init hooks whose relative ORDER matters, extracted so
3052     * the ordering can be asserted in tests without invoking plugin_upgrade() (whose
3053     * guards make it unreliable to trigger under test). activate_new_modules()
3054     * (init, default priority 10) auto-activates "Auto Activate: Yes" modules
3055     * including the `ai` master; reconcile_ai_master_optout() must run at a LATER
3056     * priority to honor an explicit AI opt-out.
3057     *
3058     * @return void
3059     */
3060    public static function register_upgrade_init_hooks() {
3061        add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
3062        add_action( 'init', array( __CLASS__, 'reconcile_ai_master_optout' ), 20 );
3063    }
3064
3065    /**
3066     * Preserves an explicit Jetpack AI opt-out when the `ai` module becomes the site-wide
3067     * master switch off WordPress.com Simple (self-hosted and Atomic).
3068     *
3069     * The `ai` module is "Auto Activate: Yes", so on upgrade {@see self::activate_new_modules()}
3070     * turns it on for connected sites â€” the desired default-on / auto-enable-on-connection
3071     * behavior, which this method deliberately leaves alone. The one case it corrects is a site
3072     * that had explicitly disabled Jetpack AI (the `jetpack_ai_enabled` option present and falsey)
3073     * before the module shipped: that opt-out must survive the module becoming the master, so the
3074     * module is deactivated for exactly those sites. An absent or truthy option is left untouched.
3075     *
3076     * Ordering is the whole point. `activate_new_modules()` is hooked on `init` at priority 10 and
3077     * auto-activates the module there; this method is hooked on `init` at priority 20 (see
3078     * {@see self::plugin_upgrade()}), so it runs AFTER the auto-activation and its deactivation is
3079     * the final state. A version-guarded block that ran inline during `plugins_loaded` would be
3080     * undone by the later auto-activation, which is why this is a late-init hook rather than an
3081     * inline upgrade step.
3082     *
3083     * WordPress.com Simple never runs modules â€” the option stays the master there â€” so this is a
3084     * no-op on Simple. The {@see self::AI_MASTER_OPTOUT_MIGRATED_OPTION} flag makes it run exactly
3085     * once, which matters because off-Simple the option is no longer the master after this runs:
3086     * a stale falsey option must not keep re-deactivating a module the user later turns back on.
3087     *
3088     * @return void
3089     */
3090    public static function reconcile_ai_master_optout() {
3091        if ( get_option( self::AI_MASTER_OPTOUT_MIGRATED_OPTION ) ) {
3092            return;
3093        }
3094
3095        // Simple keeps the `jetpack_ai_enabled` option as the master; modules don't run there.
3096        if ( ( new Host() )->is_wpcom_simple() ) {
3097            return;
3098        }
3099
3100        // A sentinel default distinguishes an absent option (leave auto-activation alone) from one
3101        // explicitly stored falsey (an opt-out to preserve).
3102        $stored = get_option( 'jetpack_ai_enabled', 'not-set' );
3103        if ( 'not-set' !== $stored && ! (bool) $stored ) {
3104            ( new Modules() )->deactivate( 'ai' );
3105        }
3106
3107        update_option( self::AI_MASTER_OPTOUT_MIGRATED_OPTION, true );
3108    }
3109
3110    /**
3111     * Whether a module should be recorded as active in its durable Jetpack SEO option.
3112     *
3113     * Permanent module overrides are part of the site's configuration, so the normal
3114     * filtered module state is authoritative. The exception is wpcomsh's private-site
3115     * callback, which temporarily suppresses `sitemaps` on Atomic sites without changing
3116     * the site's configured state. Evaluate the module state with only that callback
3117     * disabled.
3118     *
3119     * The hook is cloned before removing the callback so its ordering remains unchanged for
3120     * the rest of the request. `$available_only` is false because these migrations can run
3121     * after the standalone module file has been removed.
3122     *
3123     * WordPress.com Simple keeps module state outside this site's options table, so its
3124     * normal filtered read remains authoritative.
3125     *
3126     * @since 16.1
3127     *
3128     * @param string $module Module slug.
3129     * @return bool Whether the module should be recorded as active.
3130     */
3131    private static function is_module_active_for_seo_option( $module ) {
3132        $modules = new Modules();
3133
3134        if ( ( new Host() )->is_wpcom_simple() ) {
3135            return $modules->is_active( $module, false );
3136        }
3137
3138        global $wp_filter;
3139
3140        $hook_name             = 'jetpack_active_modules';
3141        $private_site_callback = '\Private_Site\filter_jetpack_active_modules';
3142        $callback_priority     = has_filter( $hook_name, $private_site_callback );
3143
3144        if ( false === $callback_priority ) {
3145            return $modules->is_active( $module, false );
3146        }
3147
3148        $original_hook = $wp_filter[ $hook_name ];
3149        // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Use an isolated hook copy without changing callback order.
3150        $wp_filter[ $hook_name ] = clone $original_hook;
3151        remove_filter( $hook_name, $private_site_callback, $callback_priority );
3152
3153        try {
3154            return $modules->is_active( $module, false );
3155        } finally {
3156            // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restore the untouched original hook.
3157            $wp_filter[ $hook_name ] = $original_hook;
3158        }
3159    }
3160
3161    /**
3162     * Records whether the standalone Sitemaps module is active so the setting survives
3163     * the module's removal.
3164     *
3165     * The Jetpack SEO product reads the {@see Jetpack_SEO_Initializer::SITEMAP_ENABLED_OPTION}
3166     * option instead of the `sitemaps` module's active state. Module-active state is
3167     * filtered against the modules present on disk, so once the standalone module is
3168     * removed it would read as inactive even for sites that had it on. This one-time
3169     * migration captures the configured module state â€” which persists regardless of
3170     * whether the module file is present â€” into the durable option.
3171     *
3172     * Deliberately non-destructive: it never touches generated sitemap data
3173     * (`jp_sitemap*` posts), the `jetpack-sitemap-state` option, sitemap settings, or the
3174     * `jp_sitemap_cron_hook` cron, so no regeneration is triggered. `add_option()` only
3175     * seeds when the option is absent, so it is safe to run on every version bump and
3176     * never reverts a value the user has since set.
3177     *
3178     * Hooked on `updating_jetpack_version`; the version arguments are not needed because
3179     * `add_option()` provides the run-once guard.
3180     */
3181    public static function migrate_sitemaps_module_to_seo_option() {
3182        // Ignore wpcomsh's temporary private-site suppression while preserving permanent
3183        // module overrides. {@see self::is_module_active_for_seo_option()}.
3184        $sitemaps_active = self::is_module_active_for_seo_option( 'sitemaps' );
3185
3186        add_option( Jetpack_SEO_Initializer::SITEMAP_ENABLED_OPTION, $sitemaps_active );
3187    }
3188
3189    /**
3190     * Keeps the Jetpack SEO sitemap option in sync with the legacy `sitemaps` module
3191     * while both still exist.
3192     *
3193     * Hooked to the module's activate/deactivate actions, so toggling sitemaps from any
3194     * surface (the legacy Traffic settings, the SEO Settings tab, or WP-CLI) keeps the
3195     * durable {@see Jetpack_SEO_Initializer::SITEMAP_ENABLED_OPTION} option current. The
3196     * actions fire after `active_modules` is updated, so the configured state already
3197     * reflects the new choice. Ignore temporary private-site suppression without bypassing
3198     * permanent module overrides. Removed alongside the module itself.
3199     */
3200    public static function sync_seo_sitemap_option() {
3201        update_option( Jetpack_SEO_Initializer::SITEMAP_ENABLED_OPTION, self::is_module_active_for_seo_option( 'sitemaps' ) );
3202    }
3203
3204    /**
3205     * Records whether the standalone Canonical URLs module is active so the setting survives
3206     * the module's removal.
3207     *
3208     * The Jetpack SEO product reads the {@see Jetpack_SEO_Initializer::CANONICAL_ENABLED_OPTION}
3209     * option instead of the `canonical-urls` module's active state. Module-active state is
3210     * filtered against the modules present on disk, so once the standalone module is
3211     * removed it would read as inactive even for sites that had it on. This one-time
3212     * migration captures the configured module state â€” which persists regardless of
3213     * whether the module file is present â€” into the durable option.
3214     *
3215     * Deliberately non-destructive: `add_option()` only seeds when the option is absent, so
3216     * it is safe to run on every version bump and never reverts a value the user has since
3217     * set.
3218     *
3219     * Hooked on `updating_jetpack_version`; the version arguments are not needed because
3220     * `add_option()` provides the run-once guard.
3221     */
3222    public static function migrate_canonical_urls_module_to_seo_option() {
3223        $canonical_active = self::is_module_active_for_seo_option( 'canonical-urls' );
3224
3225        add_option( Jetpack_SEO_Initializer::CANONICAL_ENABLED_OPTION, $canonical_active );
3226    }
3227
3228    /**
3229     * Keeps the Jetpack SEO canonical-urls option in sync with the legacy `canonical-urls`
3230     * module while both still exist.
3231     *
3232     * Hooked to the module's activate/deactivate actions, so toggling canonical URLs from any
3233     * surface (the legacy Traffic settings, the SEO Settings tab, or WP-CLI) keeps the
3234     * durable {@see Jetpack_SEO_Initializer::CANONICAL_ENABLED_OPTION} option current. The
3235     * actions fire after `active_modules` is updated, so the configured state already
3236     * reflects the new choice. Permanent module overrides remain authoritative. Removed
3237     * alongside the module itself.
3238     */
3239    public static function sync_seo_canonical_urls_option() {
3240        update_option( Jetpack_SEO_Initializer::CANONICAL_ENABLED_OPTION, self::is_module_active_for_seo_option( 'canonical-urls' ) );
3241    }
3242
3243    /**
3244     * Repairs durable SEO module-state options that the first pass of the migration seeded
3245     * from a filtered read.
3246     *
3247     * Jetpack 16.0 seeded {@see Jetpack_SEO_Initializer::SITEMAP_ENABLED_OPTION} and
3248     * {@see Jetpack_SEO_Initializer::CANONICAL_ENABLED_OPTION} through
3249     * {@see Modules::is_active()}, which passes the `jetpack_active_modules` filter. A site
3250     * that was private at the time therefore recorded `sitemaps` as off even though the user
3251     * had it on, and because the migration seeds with `add_option()` the value was never
3252     * revisited â€” making the site public again did not restore the setting.
3253     *
3254     * This runs once and rewrites both options from the site's configured module state,
3255     * including permanent module overrides. That is safe against a choice the user has made
3256     * since: every surface that toggles these settings (the legacy Traffic page, the SEO
3257     * Settings tab, WP-CLI) goes through {@see Modules::activate()}/{@see Modules::deactivate()},
3258     * so the module state and durable option are already in agreement wherever the original
3259     * migration got it right.
3260     *
3261     * Idempotent: the marker is written with `add_option()`, so reruns on later version bumps
3262     * are no-ops. Like the migrations it seeds from, it touches no sitemap data or cron state.
3263     *
3264     * @since 16.1
3265     */
3266    public static function reconcile_seo_module_state_options() {
3267        if ( get_option( self::SEO_MODULE_STATE_RECONCILED_OPTION ) ) {
3268            return;
3269        }
3270
3271        update_option( Jetpack_SEO_Initializer::SITEMAP_ENABLED_OPTION, self::is_module_active_for_seo_option( 'sitemaps' ) );
3272        update_option( Jetpack_SEO_Initializer::CANONICAL_ENABLED_OPTION, self::is_module_active_for_seo_option( 'canonical-urls' ) );
3273
3274        add_option( self::SEO_MODULE_STATE_RECONCILED_OPTION, true );
3275    }
3276
3277    /**
3278     * Wires up the migration + sync hooks that keep the durable Jetpack SEO module-state
3279     * options ({@see Jetpack_SEO_Initializer::SITEMAP_ENABLED_OPTION} /
3280     * {@see Jetpack_SEO_Initializer::CANONICAL_ENABLED_OPTION}) seeded and in sync with their
3281     * legacy modules. Called once from `load-jetpack.php`.
3282     *
3283     * Extracted from file scope so the wiring is unit-testable (file-scope `add_action()`
3284     * calls run during bootstrap and can't be exercised by a test). Removed alongside the
3285     * modules in the deferred post-convergence follow-up that absorbs them into Jetpack SEO.
3286     */
3287    public static function register_seo_module_migration_hooks() {
3288        add_action( 'updating_jetpack_version', array( 'Jetpack', 'migrate_sitemaps_module_to_seo_option' ) );
3289        add_action( 'jetpack_activate_module_sitemaps', array( 'Jetpack', 'sync_seo_sitemap_option' ) );
3290        add_action( 'jetpack_deactivate_module_sitemaps', array( 'Jetpack', 'sync_seo_sitemap_option' ) );
3291
3292        add_action( 'updating_jetpack_version', array( 'Jetpack', 'migrate_canonical_urls_module_to_seo_option' ) );
3293        add_action( 'jetpack_activate_module_canonical-urls', array( 'Jetpack', 'sync_seo_canonical_urls_option' ) );
3294        add_action( 'jetpack_deactivate_module_canonical-urls', array( 'Jetpack', 'sync_seo_canonical_urls_option' ) );
3295
3296        // Runs after both migrations above (default priority, registered last) so a freshly
3297        // seeded site is already correct and the reconciliation is a no-op there.
3298        add_action( 'updating_jetpack_version', array( 'Jetpack', 'reconcile_seo_module_state_options' ) );
3299    }
3300
3301    /**
3302     * Seeds the Jetpack SEO discoverability cohort once, so the new SEO surface is
3303     * auto-discoverable on fresh installs but opt-in on existing ones (JETPACK-1700).
3304     *
3305     * Hooked on `updating_jetpack_version`, which fires on every install including the
3306     * first â€” with `$old_version === false` on a brand-new site (the same signal
3307     * {@see self::activate_subscriptions_module_for_existing_sites()} keys off). Fresh
3308     * installs are seeded visible; existing installs are seeded hidden and opt in later
3309     * via the legacy Traffic page or My Jetpack. `add_option()` makes this seed-once: it
3310     * never overrides a value a later opt-in (or opt-out) has set. WordPress.com sites
3311     * ignore this option entirely (always visible) â€” see
3312     * {@see \Automattic\Jetpack\SEO\Initializer::is_seo_surface_visible()}.
3313     *
3314     * @param string       $version     The new Jetpack version (unused).
3315     * @param string|false $old_version The previous version, or false on a fresh install.
3316     */
3317    public static function seed_seo_visibility_cohort( $version, $old_version ) {
3318        add_option( Jetpack_SEO_Initializer::VISIBILITY_OPTION, ! $old_version );
3319    }
3320
3321    /**
3322     * Sets the display_update_modal state.
3323     *
3324     * The release post update modal that read this state has been removed. The write is kept so the
3325     * method still behaves as documented for the deprecation window. When this is deleted, also drop
3326     * the matching `display_update_modal` guard in Automattic\Jetpack\CookieState::should_set_cookie(),
3327     * which exists only to keep this key out of the cookie on the Jetpack admin screen.
3328     *
3329     * @deprecated 16.2
3330     */
3331    public static function set_update_modal_display() {
3332        _deprecated_function( __METHOD__, 'jetpack-16.2' );
3333        self::state( 'display_update_modal', true );
3334    }
3335
3336    /**
3337     * Enqueues the block library styles.
3338     *
3339     * Only ever used by the release post update modal, which has been removed.
3340     *
3341     * @deprecated 16.2
3342     *
3343     * @param string $hook The current admin page.
3344     */
3345    public static function enqueue_block_style( $hook ) {
3346        _deprecated_function( __METHOD__, 'jetpack-16.2' );
3347        if ( 'toplevel_page_jetpack' === $hook ) {
3348            wp_enqueue_style( 'wp-block-library' );
3349        }
3350    }
3351
3352    /**
3353     * Sets the internal version number and activation state.
3354     *
3355     * @static
3356     */
3357    public static function plugin_initialize() {
3358        if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3359            Jetpack_Options::update_option( 'activated', 2 );
3360        }
3361
3362        if ( ! Jetpack_Options::get_option( 'version' ) ) {
3363            $old_version = JETPACK__VERSION . ':' . time();
3364            $version     = $old_version;
3365            /** This action is documented in class.jetpack.php */
3366            do_action( 'updating_jetpack_version', $version, false );
3367            Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3368        }
3369
3370        if ( self::is_connection_ready() ) {
3371            self::handle_default_module_activation( true );
3372        }
3373
3374        self::load_modules();
3375
3376        Jetpack_Options::delete_option( 'do_activate' );
3377    }
3378
3379    /**
3380     * Handles the activation of the default modules depending on the current state of the site:
3381     *  - If the site already has the jetpack_active_modules option, activate those.
3382     *  - If the site has a site-only connection, only activate the default modules that require only a site connection.
3383     *  - If the site has a user connection, activate the default modules that require a user connection.
3384     *
3385     * @param bool $should_activate_user_modules Whether the status of the user connection should be checked and the default modules that
3386     *                                           require a user connection activated.
3387     */
3388    private static function handle_default_module_activation( $should_activate_user_modules ) {
3389        $active_modules = Jetpack_Options::get_option( 'active_modules' );
3390        if ( $active_modules ) {
3391            self::delete_active_modules();
3392
3393            /**
3394             * Previously active modules could mean two things. First, it could mean
3395             * that Jetpack was previously active on the site. In this case we would like
3396             * to only activate the modules that were set to active.
3397             * Another case could be that the module option was set by a standalone
3398             * plugin. In that case the `active_modules_initalized` option will not
3399             * be set, so we need to enable default Jetpack modules as well.
3400             */
3401            if ( ! Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
3402                $default_modules = self::get_default_modules();
3403                $active_modules  = array_merge( $active_modules, $default_modules );
3404                Jetpack_Options::update_option( 'active_modules_initialized', true );
3405            }
3406
3407            self::activate_default_modules(
3408                999, // This version trick basically excludes every default module.
3409                1,
3410                $active_modules,
3411                false
3412            );
3413        } elseif ( $should_activate_user_modules && ( new Connection_Manager() )->get_connection_owner_id() ) { // Check for a user connection.
3414            self::activate_default_modules( false, false, array(), false, null, null, null );
3415            Jetpack_Options::update_option( 'active_modules_initialized', true );
3416        } else {
3417            self::activate_default_modules( false, false, array(), false, null, null, false );
3418        }
3419    }
3420
3421    /**
3422     * Removes all connection options
3423     *
3424     * @static
3425     */
3426    public static function plugin_deactivation() {
3427        require_once ABSPATH . '/wp-admin/includes/plugin.php';
3428        $tracking = new Tracking();
3429        $tracking->record_user_event( 'deactivate_plugin', array() );
3430        if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3431            Jetpack_Network::init()->deactivate();
3432        } else {
3433            add_filter( 'jetpack_update_activated_state_on_disconnect', '__return_false' );
3434            self::disconnect();
3435            Jetpack_Options::delete_option( 'version' );
3436        }
3437
3438        if ( ! defined( 'WC_ANALYTICS' ) && class_exists( 'Automattic\Woocommerce_Analytics' ) ) {
3439            Woocommerce_Analytics::maybe_remove_proxy_speed_module();
3440        }
3441    }
3442
3443    /**
3444     * Set activated option to 4 on jetpack_idc_disconnect action.
3445     */
3446    public static function on_idc_disconnect() {
3447        \Jetpack_Options::update_option( 'activated', 4 );
3448    }
3449
3450    /**
3451     * Disconnects from the Jetpack servers.
3452     * Forgets all connection details and tells the Jetpack servers to do the same.
3453     *
3454     * Will not disconnect if there are other plugins using the connection.
3455     *
3456     * @since 11.0 Do not disconnect if other plugins are using the connection.
3457     *
3458     * @static
3459     */
3460    public static function disconnect() {
3461
3462        $connection = self::connection();
3463
3464        // If the site is in an IDC because sync is not allowed,
3465        // let's make sure to not disconnect the production site.
3466        $connection->remove_connection( ! Identity_Crisis::validate_sync_error_idc_option() );
3467    }
3468
3469    /**
3470     * Happens after a successful disconnection.
3471     *
3472     * @static
3473     */
3474    public static function jetpack_site_disconnected() {
3475        Identity_Crisis::clear_all_idc_options();
3476
3477        \Automattic\Jetpack\Reprint_Export\Reprint_Exporter::discard_credentials();
3478
3479        // Delete all the sync related data. Since it could be taking up space.
3480        Sender::get_instance()->uninstall();
3481
3482        /**
3483         * Filters whether the Jetpack activated state should be updated after disconnecting.
3484         *
3485         * @since 10.0.0
3486         *
3487         * @param bool $update_activated_state Whether activated state should be updated after disconnecting, defaults to true.
3488         */
3489        $update_activated_state = apply_filters( 'jetpack_update_activated_state_on_disconnect', true );
3490
3491        if ( $update_activated_state ) {
3492            Jetpack_Options::update_option( 'activated', 4 );
3493        }
3494    }
3495
3496    /**
3497     * Disconnects the user.
3498     *
3499     * @deprecated 13.4
3500     * @see \Automattic\Jetpack\Connection\Manager::disconnect_user()
3501     *
3502     * @param int $user_id The user ID to disconnect.
3503     */
3504    public function disconnect_user( $user_id ) {
3505        $this->connection_manager->disconnect_user( $user_id );
3506    }
3507
3508    /**
3509     * Checking the domain names in beta versions.
3510     * If this is a development version, before attempting to connect, let's make sure that the domains are viable.
3511     *
3512     * @param null|\WP_Error $error The domain validation error, or `null` if everything's fine.
3513     *
3514     * @return null|\WP_Error The domain validation error, or `null` if everything's fine.
3515     */
3516    public static function registration_check_domains( $error ) {
3517        if ( static::is_development_version() ) {
3518            $domains_to_check = array_unique(
3519                array(
3520                    'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3521                    'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3522                )
3523            );
3524            foreach ( $domains_to_check as $domain ) {
3525                $result = static::connection()->is_usable_domain( $domain );
3526                if ( is_wp_error( $result ) ) {
3527                    return $result;
3528                }
3529            }
3530        }
3531
3532        return $error;
3533    }
3534
3535    /**
3536     * Tracking an internal event log. Try not to put too much chaff in here.
3537     *
3538     * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3539     *
3540     * @param mixed $code Error code to log.
3541     * @param mixed $data Data to log.
3542     */
3543    public static function log( $code, $data = null ) {
3544
3545        $raw_log = Jetpack_Options::get_option( 'log', array() );
3546        // This can be modified by the `jetpack_options` filter, so abort if we don't have an array.
3547        if ( ! is_array( $raw_log ) ) {
3548            return;
3549        }
3550
3551        // only grab the latest 200 entries.
3552        $log = array_slice( $raw_log, -199, 199 );
3553
3554        // Append our event to the log.
3555        $log_entry = array(
3556            'time'    => time(),
3557            'user_id' => get_current_user_id(),
3558            'blog_id' => Jetpack_Options::get_option( 'id' ),
3559            'code'    => $code,
3560        );
3561        // Don't bother storing it unless we've got some.
3562        if ( $data !== null ) {
3563            $log_entry['data'] = $data;
3564        }
3565        $log[] = $log_entry;
3566
3567        // Try add_option first, to make sure it's not autoloaded.
3568        // @todo: Add an add_option method to Jetpack_Options.
3569        if ( ! add_option( 'jetpack_log', $log, '', 'no' ) ) {
3570            Jetpack_Options::update_option( 'log', $log );
3571        }
3572
3573        /**
3574         * Fires when Jetpack logs an internal event.
3575         *
3576         * @since 3.0.0
3577         *
3578         * @param array $log_entry {
3579         *  Array of details about the log entry.
3580         *
3581         *  @param string time Time of the event.
3582         *  @param int user_id ID of the user who trigerred the event.
3583         *  @param int blog_id Jetpack Blog ID.
3584         *  @param string code Unique name for the event.
3585         *  @param string data Data about the event.
3586         * }
3587         */
3588        do_action( 'jetpack_log_entry', $log_entry );
3589    }
3590
3591    /**
3592     * Get the internal event log.
3593     *
3594     * @param string $event only return the specific log events.
3595     * @param int    $num - get specific number of latest results, limited to 200.
3596     *
3597     * @return array of log events || WP_Error for invalid params
3598     */
3599    public static function get_log( $event = false, $num = false ) {
3600        if ( $event && ! is_string( $event ) ) {
3601            return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3602        }
3603
3604        if ( $num && ! is_numeric( $num ) ) {
3605            return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3606        }
3607
3608        $entire_log = Jetpack_Options::get_option( 'log', array() );
3609
3610        // If nothing set - act as it did before, otherwise let's start customizing the output.
3611        if ( ! $num && ! $event ) {
3612            return $entire_log;
3613        } else {
3614            $entire_log = array_reverse( $entire_log );
3615        }
3616
3617        $custom_log_output = array();
3618
3619        if ( $event ) {
3620            foreach ( $entire_log as $log_event ) {
3621                if ( $event === $log_event['code'] ) {
3622                    $custom_log_output[] = $log_event;
3623                }
3624            }
3625        } else {
3626            $custom_log_output = $entire_log;
3627        }
3628
3629        if ( $num ) {
3630            $custom_log_output = array_slice( $custom_log_output, 0, $num );
3631        }
3632
3633        return $custom_log_output;
3634    }
3635
3636    /**
3637     * Log modification of important settings.
3638     *
3639     * @param string $option Option name.
3640     * @param string $old_value Old value of option.
3641     * @param string $value New value of option.
3642     */
3643    public static function log_settings_change( $option, $old_value, $value ) {
3644        switch ( $option ) {
3645            case 'jetpack_sync_non_public_post_stati':
3646                self::log( $option, $value );
3647                break;
3648        }
3649    }
3650
3651    /**
3652     * Return stat data for WPCOM sync.
3653     *
3654     * The Sync stats module was this method's last caller and moved to the Connection package's
3655     * `Heartbeat::generate_stats_array()`, which assembles the heartbeat data through the
3656     * `jetpack_heartbeat_stats_array` filter. Note the package method does not include the extended
3657     * data from `get_additional_stat_data()`, so callers relying on `$extended` need to add it themselves.
3658     *
3659     * @deprecated 16.2
3660     *
3661     * @param bool $encode JSON encode the result.
3662     * @param bool $extended Adds additional stats data.
3663     *
3664     * @return array|string Stats data. Array if $encode is false. JSON-encoded string is $encode is true.
3665     */
3666    public static function get_stat_data( $encode = true, $extended = true ) {
3667        _deprecated_function( __METHOD__, 'jetpack-16.2', 'Automattic\\Jetpack\\Heartbeat::generate_stats_array' );
3668
3669        // Site environment stats now live in the Connection package; merge them with the Jetpack-specific stats.
3670        $data = array_merge( Jetpack_Heartbeat::generate_stats_array(), Heartbeat::get_environment_stats() );
3671
3672        if ( $extended ) {
3673            $additional_data = self::get_additional_stat_data();
3674            $data            = array_merge( $data, $additional_data );
3675        }
3676
3677        if ( $encode ) {
3678            return wp_json_encode( $data, JSON_UNESCAPED_SLASHES );
3679        }
3680
3681        return $data;
3682    }
3683
3684    /**
3685     * Get additional stat data to sync to WPCOM
3686     *
3687     * @param string $prefix Stats prefix.
3688     *
3689     * @return array stats values.
3690     */
3691    public static function get_additional_stat_data( $prefix = '' ) {
3692        $return                             = array();
3693        $return[ "{$prefix}themes" ]        = self::get_parsed_theme_data();
3694        $return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3695        $return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3696        $return[ "{$prefix}site-count" ]    = 0;
3697
3698        if ( function_exists( 'get_blog_count' ) ) {
3699            $return[ "{$prefix}site-count" ] = get_blog_count();
3700        }
3701        return $return;
3702    }
3703
3704    /**
3705     * Get current site's user count.
3706     *
3707     * @return int|string|null Number of users on the site. -1 for a large network.
3708     */
3709    private static function get_site_user_count() {
3710        global $wpdb;
3711
3712        if ( function_exists( 'wp_is_large_network' ) ) {
3713            if ( wp_is_large_network( 'users' ) ) {
3714                return -1; // Not a real value but should tell us that we are dealing with a large network.
3715            }
3716        }
3717        $user_count = get_transient( 'jetpack_site_user_count' );
3718        if ( false === ( $user_count ) ) {
3719            // It wasn't there, so regenerate the data and save the transient.
3720            $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3721            set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3722        }
3723        return $user_count;
3724    }
3725
3726    /* Admin Pages */
3727
3728    /**
3729     * Admin init function.
3730     *
3731     * Runs on admin_init hook.
3732     *
3733     * @return void
3734     */
3735    public function admin_init() {
3736        // If the plugin is not connected, display a connect message.
3737        if (
3738            // the plugin was auto-activated and needs its candy.
3739            Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3740        ||
3741            // the plugin is active, but was never activated.  Probably came from a site-wide network activation.
3742            ! Jetpack_Options::get_option( 'activated' )
3743        ) {
3744            self::plugin_initialize();
3745        }
3746
3747        $is_offline_mode              = ( new Status() )->is_offline_mode();
3748        $fallback_no_verify_ssl_certs = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
3749        /** Already documented in automattic/jetpack-connection::src/class-client.php */
3750        $client_verify_ssl_certs = apply_filters( 'jetpack_client_verify_ssl_certs', false );
3751
3752        // Run post-activation actions if needed.
3753        $this->plugin_post_activation();
3754
3755        if ( ( self::is_connection_ready() || $is_offline_mode ) && false === $fallback_no_verify_ssl_certs && ! $client_verify_ssl_certs ) {
3756            // Upgrade: 1.1 -> 1.1.1
3757            // Check and see if host can verify the Jetpack servers' SSL certificate.
3758            $args = array();
3759            // @phan-suppress-next-line PhanAccessMethodInternal -- Phan is correct, but the usage is intentional.
3760            Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3761        }
3762
3763        if (
3764            current_user_can( 'manage_options' )
3765            && ! self::permit_ssl()
3766            && ! $is_offline_mode
3767        ) {
3768            add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3769        }
3770
3771        add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3772        add_action( 'load-plugins.php', array( $this, 'plugins_page_init_jetpack_state' ) );
3773
3774        if ( ! ( is_multisite() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) && ! is_network_admin() ) ) {
3775            add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3776        }
3777
3778        add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3779
3780        if ( self::is_connection_ready() || $is_offline_mode ) {
3781            // Artificially throw errors in certain specific cases during plugin activation.
3782            add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3783        }
3784    }
3785
3786    /**
3787     * Adds body classes.
3788     *
3789     * @param string $admin_body_class Body classes.
3790     *
3791     * @return string
3792     */
3793    public function admin_body_class( $admin_body_class = '' ) {
3794        $classes = explode( ' ', trim( $admin_body_class ) );
3795
3796        $classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3797
3798        $admin_body_class = implode( ' ', array_unique( $classes ) );
3799        return " $admin_body_class ";
3800    }
3801
3802    /**
3803     * Adds Jetpack Page styles by appending class to the admin body class.
3804     *
3805     * @param string $admin_body_class Existing admin body class string.
3806     *
3807     * @return string
3808     */
3809    public static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3810        return $admin_body_class . ' jetpack-pagestyles ';
3811    }
3812
3813    /**
3814     * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3815     * This function artificially throws errors for such cases (per a specific list).
3816     *
3817     * @param string $plugin The activated plugin.
3818     * @throws RuntimeException If a conflicting plugin is detected.
3819     */
3820    public function throw_error_on_activate_plugin( $plugin ) {
3821        $active_modules = self::get_active_modules();
3822
3823        // The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3824        if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules, true ) ) {
3825            $throw = false;
3826
3827            // Try and make sure it really was the stats plugin.
3828            if ( ! class_exists( 'ReflectionFunction' ) ) {
3829                if ( 'stats.php' === basename( $plugin ) ) {
3830                    $throw = true;
3831                }
3832            } else {
3833                // @phan-suppress-next-line PhanUndeclaredFunctionInCallable -- Checked above. See also https://github.com/phan/phan/issues/1204.
3834                $reflection = new ReflectionFunction( 'stats_get_api_key' );
3835                if ( basename( $plugin ) === basename( $reflection->getFileName() ) ) {
3836                    $throw = true;
3837                }
3838            }
3839
3840            if ( $throw ) {
3841                /* translators: Plugin name to deactivate. */
3842                throw new RuntimeException( sprintf( __( 'Jetpack contains the most recent version of the old "%1$s" plugin.', 'jetpack' ), 'WordPress.com Stats' ) );
3843            }
3844        }
3845    }
3846
3847    /**
3848     * Call to Jetpack::state on the load-plugins.php hook.
3849     * In case the jetpackState cookie is populated, this call will read and re-set the cookie before HTTP headers are sent.
3850     */
3851    public function plugins_page_init_jetpack_state() {
3852        self::state( 'message' );
3853    }
3854
3855    /**
3856     * Adds the intercept action to the check_admin_referer hook.
3857     *
3858     * @return void
3859     */
3860    public function intercept_plugin_error_scrape_init() {
3861        add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3862    }
3863
3864    /**
3865     * Detect if conflicting plugin is being deactivated.
3866     *
3867     * @param string   $action The nonce action.
3868     * @param bool|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
3869     *
3870     * @return void
3871     */
3872    public function intercept_plugin_error_scrape( $action, $result ) {
3873        if ( ! $result ) {
3874            return;
3875        }
3876
3877        foreach ( $this->plugins_to_deactivate as $deactivate_us ) {
3878            foreach ( $deactivate_us as $deactivate_me ) {
3879                if ( "plugin-activation-error_{$deactivate_me[0]}" === $action ) {
3880                    /* translators: Plugin name to deactivate. */
3881                    self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3882                }
3883            }
3884        }
3885    }
3886
3887    /**
3888     * Register the remote file upload request handlers, if needed.
3889     *
3890     * @access public
3891     */
3892    public function add_remote_request_handlers() {
3893        // Remote file uploads are allowed only via AJAX requests.
3894        if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3895            return;
3896        }
3897
3898        // Remote file uploads are allowed only for a set of specific AJAX actions.
3899        $remote_request_actions = array(
3900            'jetpack_upload_file',
3901            'jetpack_update_file',
3902        );
3903
3904        // phpcs:ignore WordPress.Security.NonceVerification
3905        if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3906            return;
3907        }
3908
3909        // Require Jetpack authentication for the remote file upload AJAX requests.
3910        if ( ! $this->connection_manager ) {
3911            $this->connection_manager = new Connection_Manager();
3912        }
3913
3914        $this->connection_manager->require_jetpack_authentication();
3915
3916        // Register the remote file upload AJAX handlers.
3917        foreach ( $remote_request_actions as $action ) {
3918            add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3919        }
3920    }
3921
3922    /**
3923     * Handler for Jetpack remote file uploads.
3924     *
3925     * @access public
3926     * @return never
3927     */
3928    public function remote_request_handlers() {
3929        switch ( current_filter() ) {
3930            case 'wp_ajax_nopriv_jetpack_upload_file':
3931                $response = $this->upload_handler();
3932                break;
3933
3934            case 'wp_ajax_nopriv_jetpack_update_file':
3935                $response = $this->upload_handler( true );
3936                break;
3937            default:
3938                $response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
3939                break;
3940        }
3941
3942        if ( ! $response ) {
3943            $response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
3944        }
3945
3946        if ( is_wp_error( $response ) ) {
3947            $status_code       = $response->get_error_data();
3948            $error             = $response->get_error_code();
3949            $error_description = $response->get_error_message();
3950
3951            if ( ! is_int( $status_code ) ) {
3952                $status_code = 400;
3953            }
3954
3955            wp_send_json( (object) compact( 'error', 'error_description' ), $status_code, JSON_UNESCAPED_SLASHES );
3956        }
3957
3958        if ( true === $response ) {
3959            status_header( 200 );
3960            exit( 0 );
3961        }
3962
3963        wp_send_json( (object) $response, 200, JSON_UNESCAPED_SLASHES );
3964    }
3965
3966    /**
3967     * Uploads a file gotten from the global $_FILES.
3968     * If `$update_media_item` is true and `post_id` is defined
3969     * the attachment file of the media item (gotten through of the post_id)
3970     * will be updated instead of add a new one.
3971     *
3972     * @param  boolean $update_media_item - update media attachment.
3973     * @return array|WP_Error - An array describing the uploading files process.
3974     */
3975    public function upload_handler( $update_media_item = false ) {
3976        if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' !== strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) ) {
3977            return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
3978        }
3979
3980        $user = wp_authenticate( '', '' );
3981        if ( ! $user || is_wp_error( $user ) ) {
3982            return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
3983        }
3984
3985        wp_set_current_user( $user->ID );
3986
3987        if ( ! current_user_can( 'upload_files' ) ) {
3988            return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3989        }
3990
3991        if ( empty( $_FILES ) ) {
3992            return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3993        }
3994
3995        foreach ( array_keys( $_FILES ) as $files_key ) {
3996            if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes here.
3997                return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3998            }
3999        }
4000
4001        $media_keys = isset( $_FILES['media'] ) ? array_keys( $_FILES['media'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Unslash is not needed for `$_FILES`, the sniff is wrong. Sanitization should happen below.
4002
4003        $token = ( new Tokens() )->get_access_token( get_current_user_id() );
4004        if ( ! $token || is_wp_error( $token ) ) {
4005            return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
4006        }
4007
4008        /**
4009         * Optionally block uploads processed through Jetpack's upload_handler().
4010         * The filter may return false or WP_Error to block this particular upload.
4011         *
4012         * @since 10.8
4013         *
4014         * @param bool|WP_Error $allowed If false or WP_Error, block the upload. If true, allow the upload.
4015         * @param mixed $_FILES The $_FILES attempting to be uploaded.
4016         */
4017        $can_upload = apply_filters( 'jetpack_upload_handler_can_upload', true, $_FILES );
4018        if ( ! $can_upload || is_wp_error( $can_upload ) ) {
4019            if ( is_wp_error( $can_upload ) ) {
4020                return $can_upload;
4021            }
4022            return new WP_Error( 'handler_cannot_upload', __( 'The upload handler cannot upload files', 'jetpack' ), 400 );
4023        }
4024
4025        $uploaded_files = array();
4026        $global_post    = $GLOBALS['post'] ?? null;
4027        unset( $GLOBALS['post'] );
4028        if ( empty( $_FILES['media']['name'] ) ) {
4029            // Nothing to process, just return.
4030            return $uploaded_files;
4031        }
4032        foreach ( $_FILES['media']['name'] as $index => $name ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- As above, unslash sniff is wrong. Validation should happen below.
4033            $file = array();
4034            foreach ( $media_keys as $media_key ) {
4035                $file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ] ?? null; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,,WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- As above, the unslash sniff is wrong.
4036            }
4037
4038            list( $hmac_provided, $salt ) = isset( $_POST['_jetpack_file_hmac_media'][ $index ] ) ? explode( ':', filter_var( wp_unslash( $_POST['_jetpack_file_hmac_media'][ $index ] ) ) ) : array( 'no', '' ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce should have been checked by the caller.
4039
4040            $hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
4041            if ( $hmac_provided !== $hmac_file ) {
4042                $uploaded_files[ $index ] = (object) array(
4043                    'error'             => 'invalid_hmac',
4044                    'error_description' => 'The corresponding HMAC for this file does not match',
4045                );
4046                continue;
4047            }
4048
4049            $_FILES['.jetpack.upload.'] = $file;
4050            $post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- caller should have checked a nonce.
4051            if ( ! current_user_can( 'edit_post', $post_id ) ) {
4052                $post_id = 0;
4053            }
4054
4055            if ( $update_media_item ) {
4056                if ( ! isset( $post_id ) || 0 === $post_id ) {
4057                    return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
4058                }
4059
4060                $media_array = $_FILES['media']; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
4061
4062                $file_array             = array();
4063                $file_array['name']     = $media_array['name'][0];
4064                $file_array['type']     = $media_array['type'][0];
4065                $file_array['tmp_name'] = $media_array['tmp_name'][0];
4066                $file_array['error']    = $media_array['error'][0];
4067                $file_array['size']     = $media_array['size'][0];
4068
4069                $edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
4070
4071                if ( is_wp_error( $edited_media_item ) ) {
4072                    return $edited_media_item;
4073                }
4074
4075                $response = (object) array(
4076                    'id'   => (string) $post_id,
4077                    'file' => (string) $edited_media_item->post_title,
4078                    'url'  => (string) wp_get_attachment_url( $post_id ),
4079                    'type' => (string) $edited_media_item->post_mime_type,
4080                    'meta' => (array) wp_get_attachment_metadata( $post_id ),
4081                );
4082
4083                return array( $response );
4084            }
4085
4086            $attachment_id = media_handle_upload(
4087                '.jetpack.upload.',
4088                $post_id,
4089                array(),
4090                array(
4091                    'action' => 'jetpack_upload_file',
4092                )
4093            );
4094
4095            if ( ! $attachment_id ) {
4096                $uploaded_files[ $index ] = (object) array(
4097                    'error'             => 'unknown',
4098                    'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
4099                );
4100            } elseif ( is_wp_error( $attachment_id ) ) {
4101                $uploaded_files[ $index ] = (object) array(
4102                    'error'             => 'attachment_' . $attachment_id->get_error_code(),
4103                    'error_description' => $attachment_id->get_error_message(),
4104                );
4105            } else {
4106                $attachment               = get_post( $attachment_id );
4107                $uploaded_files[ $index ] = (object) array(
4108                    'id'   => (string) $attachment_id,
4109                    'file' => $attachment->post_title,
4110                    'url'  => wp_get_attachment_url( $attachment_id ),
4111                    'type' => $attachment->post_mime_type,
4112                    'meta' => wp_get_attachment_metadata( $attachment_id ),
4113                );
4114            }
4115        }
4116        if ( $global_post !== null ) {
4117            $GLOBALS['post'] = $global_post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
4118        }
4119
4120        return $uploaded_files;
4121    }
4122
4123    /**
4124     * Add action links for the Jetpack plugin.
4125     *
4126     * @param array $actions Plugin actions.
4127     *
4128     * @return array
4129     */
4130    public function plugin_action_links( $actions ) {
4131        if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
4132            return array_merge(
4133                array( 'settings' => sprintf( '<a href="%s">%s</a>', esc_url( self::admin_url( 'page=jetpack#/settings' ) ), __( 'Settings', 'jetpack' ) ) ),
4134                $actions
4135            );
4136        }
4137
4138        return $actions;
4139    }
4140
4141    /**
4142     * Adds the deactivation warning modal for Jetpack.
4143     *
4144     * @param string $hook The current admin page.
4145     *
4146     * @return void
4147     */
4148    public function deactivate_dialog( $hook ) {
4149        if (
4150            'plugins.php' === $hook
4151            && self::is_connection_ready()
4152        ) {
4153
4154            // Register jp-tracks-functions dependency.
4155            Tracking::register_tracks_functions_scripts( true );
4156
4157            // add a deactivation script that will pick up deactivation actions for the Jetpack plugin.
4158            Assets::register_script(
4159                'jetpack-plugins-page-js',
4160                '_inc/build/plugins-page.js',
4161                JETPACK__PLUGIN_FILE,
4162                array(
4163                    'in_footer'  => true,
4164                    'textdomain' => 'jetpack',
4165                )
4166            );
4167            Assets::enqueue_script( 'jetpack-plugins-page-js' );
4168
4169            // Add objects to be passed to the initial state of the app.
4170            // Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
4171            wp_add_inline_script( 'jetpack-plugins-page-js', 'var Initial_State=' . wp_json_encode( Jetpack_Redux_State_Helper::get_minimal_state(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ';', 'before' );
4172
4173            add_action( 'admin_footer', array( $this, 'jetpack_plugin_portal_containers' ) );
4174        }
4175    }
4176
4177    /**
4178     * Outputs the wrapper for the plugin modal
4179     * Contents are loaded by React script
4180     *
4181     * @return void
4182     */
4183    public function jetpack_plugin_portal_containers() {
4184        $this->load_view( 'admin/jetpack-plugin-portal-containers.php' );
4185    }
4186
4187    /**
4188     * Filters the login URL to include the registration flow in case the user isn't logged in.
4189     *
4190     * @param string $login_url The wp-login URL.
4191     * @param string $redirect  URL to redirect users after logging in.
4192     * @since Jetpack 8.4
4193     * @return string
4194     */
4195    public function login_url( $login_url, $redirect ) {
4196        parse_str( (string) wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4197        if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4198            $login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4199        }
4200        return $login_url;
4201    }
4202
4203    /**
4204     * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4205     *
4206     * @since Jetpack 8.4
4207     */
4208    public function login_init() {
4209        // phpcs:ignore WordPress.Security.NonceVerification
4210        if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4211            add_filter( 'allowed_redirect_hosts', array( Host::class, 'allow_wpcom_environments' ) );
4212            wp_safe_redirect(
4213                add_query_arg(
4214                    array(
4215                        'forceInstall' => 1,
4216                        'url'          => rawurlencode( get_site_url() ),
4217                    ),
4218                    // @todo provide way to go to specific calypso env.
4219                    self::get_calypso_host() . 'jetpack/connect'
4220                )
4221            );
4222            exit( 0 );
4223        }
4224    }
4225
4226    /*
4227     * Registration flow:
4228     * 1 - ::admin_page_load() action=register
4229     * 2 - ::try_registration()
4230     * 3 - ::register()
4231     *     - Creates jetpack_register option containing two secrets and a timestamp
4232     *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4233     *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4234     *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4235     *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4236     *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4237     *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4238     *       jetpack_id, jetpack_secret, jetpack_public
4239     *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4240     * 4 - redirect to https://wordpress.com/start/jetpack-connect
4241     * 5 - user logs in with WP.com account
4242     * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4243     *      - Manager::authorize()
4244     *      - Manager::get_token()
4245     *      - GET https://jetpack.wordpress.com/jetpack.token/1/ with
4246     *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4247     *          - which responds with access_token, token_type, scope
4248     *      - Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4249     *      - Jetpack::activate_default_modules()
4250     *          - Deactivates deprecated plugins
4251     *          - Activates all default modules
4252     *      - Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4253     * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4254     * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4255     *     Done!
4256     */
4257
4258    /**
4259     * Build the user-facing description stored alongside a registration error code.
4260     *
4261     * @since 16.2
4262     *
4263     * @param string $error_code The WP_Error code.
4264     * @param string $message    The WP_Error message.
4265     * @return string The description, empty when the message is not user-facing copy.
4266     */
4267    public static function get_registration_error_description( $error_code, $message ) {
4268        // Manager::validate_remote_register_response() does not always put user-facing copy in the
4269        // message slot: wpcom_5??, wpcom_408 and wpcom_bad_response store the HTTP status there,
4270        // and jetpack_id stores the raw response body, which can also overflow the state cookie.
4271        if ( 'jetpack_id' === $error_code || is_numeric( $message ) ) {
4272            return '';
4273        }
4274
4275        return mb_substr( (string) $message, 0, 250 );
4276    }
4277
4278    /**
4279     * Handles the page load events for the Jetpack admin page
4280     */
4281    public function admin_page_load() {
4282        $error = false;
4283
4284        // Make sure we have the right body class to hook stylings for subpages off of.
4285        add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4286
4287        if ( ! empty( $_GET['jetpack_restate'] ) ) {
4288            // Should only be used in intermediate redirects to preserve state across redirects.
4289            self::restate();
4290        }
4291
4292        if ( isset( $_GET['action'] ) ) {
4293            switch ( $_GET['action'] ) {
4294                /**
4295                 * Cases authorize and authorize_redirect are now handled by Connection package Webhooks
4296                 */
4297                case 'authorize_redirect':
4298                case 'authorize':
4299                    break;
4300                case 'register':
4301                    if ( ! current_user_can( 'jetpack_connect' ) ) {
4302                        $error = 'cheatin';
4303                        break;
4304                    }
4305                    check_admin_referer( 'jetpack-register' );
4306                    self::log( 'register' );
4307                    self::maybe_set_version_option();
4308                    $from = isset( $_GET['from'] ) ? sanitize_text_field( wp_unslash( $_GET['from'] ) ) : false;
4309                    if ( $from ) {
4310                        static::connection()->add_register_request_param( 'from', (string) $from );
4311                    }
4312                    $registered = static::connection()->try_registration();
4313                    if ( is_wp_error( $registered ) ) {
4314                        $error = $registered->get_error_code();
4315                        self::state( 'error', $error );
4316
4317                        self::state( 'error_description', self::get_registration_error_description( $error, $registered->get_error_message() ) );
4318
4319                        /**
4320                         * Jetpack registration Error.
4321                         *
4322                         * @since 7.5.0
4323                         *
4324                         * @param string|int $error The error code.
4325                         * @param \WP_Error $registered The error object.
4326                         */
4327                        do_action( 'jetpack_connection_register_fail', $error, $registered );
4328                        break;
4329                    }
4330
4331                    $redirect = isset( $_GET['redirect'] ) ? wp_unslash( $_GET['redirect'] ) : false; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
4332
4333                    /**
4334                     * Jetpack registration Success.
4335                     *
4336                     * @since 7.5.0
4337                     *
4338                     * @param string $from 'from' GET parameter;
4339                     */
4340                    do_action( 'jetpack_connection_register_success', $from );
4341
4342                    $url = $this->build_connect_url( true, $redirect, $from );
4343
4344                    if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4345                        $url = add_query_arg( 'auth_approved', 'true', $url );
4346                    }
4347
4348                    add_filter( 'allowed_redirect_hosts', array( Host::class, 'allow_wpcom_environments' ) );
4349                    wp_safe_redirect( $url );
4350                    exit( 0 );
4351                case 'activate':
4352                    if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4353                        $error = 'cheatin';
4354                        break;
4355                    }
4356
4357                    $module = isset( $_GET['module'] ) ? sanitize_text_field( wp_unslash( $_GET['module'] ) ) : '';
4358                    check_admin_referer( "jetpack_activate-$module" );
4359                    self::log( 'activate', $module );
4360                    if ( ! self::activate_module( $module ) ) {
4361                        /* translators: module/feature name */
4362                        self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4363                    }
4364                    // The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4365                    wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4366                    exit( 0 );
4367                case 'activate_default_modules':
4368                    check_admin_referer( 'activate_default_modules' );
4369                    self::log( 'activate_default_modules' );
4370                    self::restate();
4371                    $min_version   = isset( $_GET['min_version'] ) ? sanitize_text_field( wp_unslash( $_GET['min_version'] ) ) : false;
4372                    $max_version   = isset( $_GET['max_version'] ) ? sanitize_text_field( wp_unslash( $_GET['max_version'] ) ) : false;
4373                    $other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_GET['other_modules'] ) ) : array();
4374                    self::activate_default_modules( $min_version, $max_version, $other_modules );
4375                    wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4376                    exit( 0 );
4377                case 'disconnect':
4378                    if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4379                        $error = 'cheatin';
4380                        break;
4381                    }
4382
4383                    check_admin_referer( 'jetpack-disconnect' );
4384                    self::log( 'disconnect' );
4385                    self::disconnect();
4386                    wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4387                    exit( 0 );
4388                case 'reconnect':
4389                    if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4390                        $error = 'cheatin';
4391                        break;
4392                    }
4393
4394                    check_admin_referer( 'jetpack-reconnect' );
4395                    self::log( 'reconnect' );
4396                    self::disconnect();
4397
4398                    add_filter( 'allowed_redirect_hosts', array( Host::class, 'allow_wpcom_environments' ) );
4399                    wp_safe_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4400                    exit( 0 );
4401                case 'deactivate':
4402                    if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4403                        $error = 'cheatin';
4404                        break;
4405                    }
4406
4407                    $modules = sanitize_text_field( wp_unslash( $_GET['module'] ) );
4408                    check_admin_referer( "jetpack_deactivate-$modules" );
4409                    foreach ( explode( ',', $modules ) as $module ) {
4410                        self::log( 'deactivate', $module );
4411                        self::deactivate_module( $module );
4412                        self::state( 'message', 'module_deactivated' );
4413                    }
4414                    self::state( 'module', $modules );
4415                    wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4416                    exit( 0 );
4417                case 'unlink':
4418                    $redirect = isset( $_GET['redirect'] ) ? sanitize_text_field( wp_unslash( $_GET['redirect'] ) ) : '';
4419                    check_admin_referer( 'jetpack-unlink' );
4420                    self::log( 'unlink' );
4421                    $this->connection_manager->disconnect_user();
4422                    self::state( 'message', 'unlinked' );
4423                    if ( 'sub-unlink' === $redirect ) {
4424                        wp_safe_redirect( admin_url() );
4425                    } else {
4426                        wp_safe_redirect( self::admin_url( array( 'page' => rawurlencode( $redirect ) ) ) );
4427                    }
4428                    exit( 0 );
4429                default:
4430                    /**
4431                     * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4432                     *
4433                     * @since 2.6.0
4434                     *
4435                     * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4436                     */
4437                    do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4438            }
4439        }
4440
4441        $error = $error ? $error : self::state( 'error' );
4442        if ( ! $error ) {
4443            self::activate_new_modules( true );
4444        }
4445
4446        $activated_manage = false;
4447        $message_code     = self::state( 'message' );
4448        if ( self::state( 'optin-manage' ) ) {
4449            $activated_manage = $message_code;
4450            $message_code     = 'jetpack-manage';
4451        }
4452
4453        switch ( $message_code ) {
4454            case 'jetpack-manage':
4455                $sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4456                // translators: %s is the URL to the "Sites" panel on wordpress.com.
4457                $this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), $sites_url ) . '</strong>';
4458                if ( $activated_manage ) {
4459                    $this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4460                }
4461                break;
4462
4463        }
4464
4465        $deactivated_plugins = self::state( 'deactivated_plugins' );
4466
4467        if ( ! empty( $deactivated_plugins ) ) {
4468            $deactivated_plugins = explode( ',', $deactivated_plugins );
4469            $deactivated_titles  = array();
4470            foreach ( $deactivated_plugins as $deactivated_plugin ) {
4471                list( $module, $idx ) = explode( ':', $deactivated_plugin );
4472                if ( ! isset( $this->plugins_to_deactivate[ $module ][ $idx ] ) ) {
4473                    continue;
4474                }
4475
4476                $deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $module ][ $idx ][1] ) . '</strong>';
4477            }
4478
4479            if ( $deactivated_titles ) {
4480                if ( $this->message ) {
4481                    $this->message .= "<br /><br />\n";
4482                }
4483
4484                $this->message .= wp_sprintf(
4485                    _n(
4486                        'Jetpack contains the most recent version of the old %l plugin.',
4487                        'Jetpack contains the most recent versions of the old %l plugins.',
4488                        count( $deactivated_titles ),
4489                        'jetpack'
4490                    ),
4491                    $deactivated_titles
4492                );
4493
4494                $this->message .= "<br />\n";
4495
4496                $this->message .= _n(
4497                    'The old version has been deactivated and can be removed from your site.',
4498                    'The old versions have been deactivated and can be removed from your site.',
4499                    count( $deactivated_titles ),
4500                    'jetpack'
4501                );
4502            }
4503        }
4504
4505        $this->privacy_checks = self::state( 'privacy_checks' );
4506
4507        if ( $this->message || $this->error || $this->privacy_checks ) {
4508            add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4509        }
4510
4511        add_filter( 'jetpack_short_module_description', 'wptexturize' );
4512    }
4513
4514    /**
4515     * Display admin notice upon error.
4516     *
4517     * @return void
4518     */
4519    public function admin_notices() {
4520
4521        if ( $this->error ) {
4522            ?>
4523<div id="message" class="jetpack-message jetpack-err">
4524    <div class="squeezer">
4525        <h2>
4526            <?php
4527            echo wp_kses(
4528                $this->error,
4529                array(
4530                    'a'      => array( 'href' => array() ),
4531                    'small'  => true,
4532                    'code'   => true,
4533                    'strong' => true,
4534                    'br'     => true,
4535                    'b'      => true,
4536                )
4537            );
4538            ?>
4539            </h2>
4540            <?php
4541            $desc = self::state( 'error_description' );
4542            if ( $desc ) :
4543                ?>
4544        <p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4545<?php    endif; ?>
4546    </div>
4547</div>
4548            <?php
4549        }
4550
4551        if ( $this->message ) {
4552            ?>
4553<div id="message" class="jetpack-message">
4554    <div class="squeezer">
4555        <h2>
4556            <?php
4557            echo wp_kses(
4558                $this->message,
4559                array(
4560                    'strong' => array(),
4561                    'a'      => array( 'href' => true ),
4562                    'br'     => true,
4563                )
4564            );
4565            ?>
4566            </h2>
4567    </div>
4568</div>
4569            <?php
4570        }
4571
4572        if ( $this->privacy_checks ) :
4573            $module_names = array();
4574            $module_slugs = array();
4575
4576            $privacy_checks = explode( ',', $this->privacy_checks );
4577            $privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4578            foreach ( $privacy_checks as $module_slug ) {
4579                $module = self::get_module( $module_slug );
4580                if ( ! $module ) {
4581                    continue;
4582                }
4583
4584                $module_slugs[] = $module_slug;
4585                $module_names[] = "<strong>{$module['name']}</strong>";
4586            }
4587
4588            $module_slugs = implode( ',', $module_slugs );
4589            ?>
4590<div id="message" class="jetpack-message jetpack-err">
4591    <div class="squeezer">
4592        <h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4593        <p>
4594            <?php
4595            echo wp_kses(
4596                wptexturize(
4597                    wp_sprintf(
4598                        _nx(
4599                            "Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4600                            "Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4601                            count( $privacy_checks ),
4602                            '%l = list of Jetpack module/feature names',
4603                            'jetpack'
4604                        ),
4605                        $module_names
4606                    )
4607                ),
4608                array( 'strong' => true )
4609            );
4610
4611            echo "\n<br />\n";
4612
4613            echo wp_kses(
4614                sprintf(
4615                        /* translators: URL to deactivate Jetpack features. */
4616                    _nx(
4617                        'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4618                        'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4619                        count( $privacy_checks ),
4620                        '%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4621                        'jetpack'
4622                    ),
4623                    esc_url(
4624                        wp_nonce_url(
4625                            self::admin_url(
4626                                array(
4627                                    'page'   => 'jetpack',
4628                                    'action' => 'deactivate',
4629                                    'module' => rawurlencode( $module_slugs ),
4630                                )
4631                            ),
4632                            "jetpack_deactivate-$module_slugs"
4633                        )
4634                    ),
4635                    esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4636                ),
4637                array(
4638                    'a' => array(
4639                        'href'  => true,
4640                        'title' => true,
4641                    ),
4642                )
4643            );
4644            ?>
4645        </p>
4646    </div>
4647</div>
4648            <?php
4649endif;
4650    }
4651
4652    /**
4653     * Initialize the jetpack stats instance only when needed
4654     *
4655     * @return void
4656     */
4657    private function initialize_stats() {
4658        if ( $this->a8c_mc_stats_instance === null ) {
4659            $this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4660        }
4661    }
4662
4663    /**
4664     * Record a stat for later output.  This will only currently output in the admin_footer.
4665     *
4666     * @param string $group Stats group.
4667     * @param string $detail Stats detail.
4668     */
4669    public function stat( $group, $detail ) {
4670        $this->initialize_stats();
4671        $this->a8c_mc_stats_instance->add( $group, $detail );
4672
4673        // Keep a local copy for backward compatibility (there are some direct checks on this).
4674        $this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4675    }
4676
4677    /**
4678     * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4679     *
4680     * @param string $method Used to check if method is "server-side".
4681     */
4682    public function do_stats( $method = '' ) {
4683        $this->initialize_stats();
4684        if ( 'server_side' === $method ) {
4685            $this->a8c_mc_stats_instance->do_server_side_stats();
4686        } else {
4687            $this->a8c_mc_stats_instance->do_stats();
4688        }
4689
4690        // Keep a local copy for backward compatibility (there are some direct checks on this).
4691        $this->stats = array();
4692    }
4693
4694    /**
4695     * Runs stats code for a one-off, server-side.
4696     *
4697     * @param array|string $args The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4698     *
4699     * @return bool If it worked.
4700     */
4701    public static function do_server_side_stat( $args ) {
4702        $url                   = self::build_stats_url( $args );
4703        $a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4704        return $a8c_mc_stats_instance->do_server_side_stat( $url );
4705    }
4706
4707    /**
4708     * Builds the stats url.
4709     *
4710     * @param array|string $args The arguments to append to the URL.
4711     *
4712     * @return string The URL to be pinged.
4713     */
4714    public static function build_stats_url( $args ) {
4715
4716        $a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4717        return $a8c_mc_stats_instance->build_stats_url( $args );
4718    }
4719
4720    /**
4721     * Builds a URL to the Jetpack connection auth page
4722     *
4723     * @since 3.9.5
4724     *
4725     * @param bool        $raw If true, URL will not be escaped.
4726     * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4727     *                              If string, will be a custom redirect.
4728     * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4729     * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0.
4730     *
4731     * @return string Connect URL
4732     */
4733    public function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4734        $site_id    = Jetpack_Options::get_option( 'id' );
4735        $blog_token = ( new Tokens() )->get_access_token();
4736
4737        if ( $register || ! $blog_token || ! $site_id ) {
4738            $url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4739
4740            if ( ! empty( $redirect ) ) {
4741                $url = add_query_arg(
4742                    'redirect',
4743                    rawurlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4744                    $url
4745                );
4746            }
4747
4748            if ( is_network_admin() ) {
4749                $url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4750            }
4751
4752            $calypso_env = ( new Host() )->get_calypso_env();
4753
4754            if ( ! empty( $calypso_env ) ) {
4755                $url = add_query_arg( 'calypso_env', $calypso_env, $url );
4756            }
4757        } else {
4758
4759            // Let's check the existing blog token to see if we need to re-register. We only check once per minute
4760            // because otherwise this logic can get us in to a loop.
4761            $last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4762            if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4763                Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4764
4765                $response = Client::wpcom_json_api_request_as_blog(
4766                    sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4767                    '1.1'
4768                );
4769
4770                if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4771
4772                    // Generating a register URL instead to refresh the existing token.
4773                    return $this->build_connect_url( $raw, $redirect, $from, true );
4774                }
4775            }
4776
4777            $url = ( new Authorize_Redirect( static::connection() ) )->build_authorize_url( $redirect );
4778        }
4779
4780        if ( $from ) {
4781            $url = add_query_arg( 'from', $from, $url );
4782        }
4783
4784        $url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4785        /**
4786         * Filter the URL used when connecting a user to a WordPress.com account.
4787         *
4788         * @since 8.1.0
4789         *
4790         * @param string $url Connection URL.
4791         * @param bool   $raw If true, URL will not be escaped.
4792         */
4793        return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4794    }
4795
4796    /**
4797     * Create the Jetpack authorization URL.
4798     *
4799     * @param bool|string $redirect URL to redirect to.
4800     * @param null        $deprecated Deprecated since Jetpack 10.9.
4801     *
4802     * @todo Update default value for redirect since the called function expects a string.
4803     *
4804     * @deprecated 13.4
4805     *
4806     * @return mixed|void
4807     */
4808    public static function build_authorize_url( $redirect = false, $deprecated = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
4809        _deprecated_function( __METHOD__, 'jetpack-13.4', 'Authorize_Redirect::build_authorize_url' );
4810
4811        return ( new Authorize_Redirect( static::connection() ) )->build_authorize_url( $redirect );
4812    }
4813
4814    /**
4815     * Filters the connection URL parameter array.
4816     *
4817     * @deprecated 13.4
4818     *
4819     * @param array $args default URL parameters used by the package.
4820     * @return array the modified URL arguments array.
4821     */
4822    public static function filter_connect_request_body( $args ) {
4823        _deprecated_function( __METHOD__, 'jetpack-13.4', 'Authorize_Redirect::filter_connect_request_body' );
4824
4825        return Authorize_Redirect::filter_connect_request_body( $args );
4826    }
4827
4828    /**
4829     * Filters the `jetpack/v4/connection/data` API response of the Connection package in order to
4830     * add Jetpack-the-plugin related permissions.
4831     *
4832     * @since 10.0
4833     *
4834     * @param array $current_user_connection_data An array containing the current user connection data.
4835     * @return array
4836     */
4837    public static function filter_jetpack_current_user_connection_data( $current_user_connection_data ) {
4838        $jetpack_permissions = array(
4839            'admin_page'         => current_user_can( 'jetpack_admin_page' ),
4840            'manage_modules'     => current_user_can( 'jetpack_manage_modules' ),
4841            'network_admin'      => current_user_can( 'jetpack_network_admin_page' ),
4842            'network_sites_page' => current_user_can( 'jetpack_network_sites_page' ),
4843            'edit_posts'         => current_user_can( 'edit_posts' ),
4844            'publish_posts'      => current_user_can( 'publish_posts' ),
4845            'manage_options'     => current_user_can( 'manage_options' ),
4846            'view_stats'         => current_user_can( 'view_stats' ),
4847            'manage_plugins'     => current_user_can( 'install_plugins' )
4848                                    && current_user_can( 'activate_plugins' )
4849                                    && current_user_can( 'update_plugins' )
4850                                    && current_user_can( 'delete_plugins' ),
4851        );
4852
4853        if ( isset( $current_user_connection_data['permissions'] ) &&
4854            is_array( $current_user_connection_data['permissions'] ) ) {
4855                $current_user_connection_data['permissions'] = array_merge( $current_user_connection_data['permissions'], $jetpack_permissions );
4856        } else {
4857            $current_user_connection_data['permissions'] = $jetpack_permissions;
4858        }
4859
4860        return $current_user_connection_data;
4861    }
4862
4863    /**
4864     * Filters the redirection URL that is used for connect requests. The redirect
4865     * URL should return the user back to the Jetpack console.
4866     *
4867     * @deprecated 13.4
4868     *
4869     * @param String $redirect the default redirect URL used by the package.
4870     * @return String the modified URL.
4871     */
4872    public static function filter_connect_redirect_url( $redirect ) {
4873        _deprecated_function( __METHOD__, 'jetpack-13.4', 'Authorize_Redirect::filter_connect_redirect_url' );
4874        return Authorize_Redirect::filter_connect_redirect_url( $redirect );
4875    }
4876
4877    /**
4878     * This action fires at the beginning of the Manager::authorize method.
4879     */
4880    public static function authorize_starting() {
4881        $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4882        // Checking if site has been active/connected previously before recording unique connection.
4883        if ( ! $jetpack_unique_connection ) {
4884            // jetpack_unique_connection option has never been set.
4885            $jetpack_unique_connection = array(
4886                'connected'    => 0,
4887                'disconnected' => 0,
4888                'version'      => '3.6.1',
4889            );
4890
4891            update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4892
4893            // Track unique connection.
4894            $jetpack = self::init();
4895
4896            $jetpack->stat( 'connections', 'unique-connection' );
4897            $jetpack->do_stats( 'server_side' );
4898        }
4899
4900        // Increment number of times connected.
4901        $jetpack_unique_connection['connected'] += 1;
4902        Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4903    }
4904
4905    /**
4906     * This action fires when the site is registered (connected at a site level).
4907     */
4908    public function handle_unique_registrations_stats() {
4909        $jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
4910        // Checking if site has been registered previously before recording unique connection.
4911        if ( ! $jetpack_unique_registrations ) {
4912
4913            $jetpack_unique_registrations = 0;
4914
4915            $this->stat( 'connections', 'unique-registrations' );
4916            $this->do_stats( 'server_side' );
4917        }
4918
4919        // Increment number of times connected.
4920        ++$jetpack_unique_registrations;
4921        Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
4922    }
4923
4924    /**
4925     * This action fires at the end of the Manager::authorize method when a secondary user is
4926     * linked.
4927     */
4928    public static function authorize_ending_linked() {
4929        // Don't activate anything since we are just connecting a user.
4930        self::state( 'message', 'linked' );
4931    }
4932
4933    /**
4934     * This action fires at the end of the Manager::authorize method when the master user is
4935     * authorized.
4936     *
4937     * @param array $data The request data.
4938     */
4939    public static function authorize_ending_authorized( $data ) {
4940        // If redirect_uri is SSO, ensure SSO module is enabled.
4941        parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4942
4943        /** This filter is documented in class.jetpack-cli.php */
4944        $jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4945
4946        $activate_sso = (
4947            isset( $redirect_options['action'] ) &&
4948            'jetpack-sso' === $redirect_options['action'] &&
4949            $jetpack_start_enable_sso
4950        );
4951
4952        $do_redirect_on_error = ( 'client' === $data['auth_type'] );
4953
4954        self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4955    }
4956
4957    /**
4958     * Fires on the jetpack_site_registered hook and acitvates default modules
4959     */
4960    public static function activate_default_modules_on_site_register() {
4961        self::handle_default_module_activation( false );
4962
4963        // Since this is a fresh connection, be sure to clear out IDC options.
4964        Identity_Crisis::clear_all_idc_options();
4965    }
4966
4967    /**
4968     * This action fires at the end of the REST_Connector connection_reconnect method when the
4969     * reconnect process is completed.
4970     * Note that this currently only happens when we don't need the user to re-authorize
4971     * their WP.com account, eg in cases where we are restoring a connection with
4972     * unhealthy blog token.
4973     */
4974    public static function reconnection_completed() {
4975        self::state( 'message', 'reconnection_completed' );
4976    }
4977
4978    /**
4979     * Apply activation source to a query string array.
4980     *
4981     * @param array $args Args used for a query string.
4982     *
4983     * @return void
4984     */
4985    public static function apply_activation_source_to_args( &$args ) {
4986        list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4987
4988        if ( $activation_source_name ) {
4989            $args['_as'] = rawurlencode( $activation_source_name );
4990        }
4991
4992        if ( $activation_source_keyword ) {
4993            $args['_ak'] = rawurlencode( $activation_source_keyword );
4994        }
4995    }
4996
4997    /**
4998     * Returns the reconnection URL.
4999     *
5000     * @param bool $raw True to return an unescaped URL. False returns value after `esc_url`.
5001     *
5002     * @return string|null
5003     */
5004    public function build_reconnect_url( $raw = false ) {
5005        $url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5006        return $raw ? $url : esc_url( $url );
5007    }
5008
5009    /**
5010     * Jetpack Admin URL.
5011     *
5012     * @param array $args Query string args.
5013     *
5014     * @return string Jetpack admin URL.
5015     */
5016    public static function admin_url( $args = null ) {
5017        return ( new Paths() )->admin_url( $args );
5018    }
5019
5020    /**
5021     * Creates a nonce from an URL.
5022     *
5023     * @param string $actionurl URL for action.
5024     * @param string $action Nonce action.
5025     * @param string $name Query arg name.
5026     *
5027     * @return string
5028     */
5029    public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5030        $actionurl = str_replace( '&amp;', '&', $actionurl );
5031        return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5032    }
5033
5034    /**
5035     * Dismiss Jetpack notices.
5036     *
5037     * @return void
5038     */
5039    public function dismiss_jetpack_notice() {
5040        if ( ! isset( $_GET['jetpack-notice'] ) ) {
5041            return;
5042        }
5043
5044        switch ( $_GET['jetpack-notice'] ) {
5045            case 'dismiss':
5046                if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5047
5048                    require_once ABSPATH . 'wp-admin/includes/plugin.php';
5049                    deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5050                    wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5051                }
5052                break;
5053        }
5054    }
5055
5056    /**
5057     * Determines which module has a higher sort order.
5058     *
5059     * @param array $a Modules array.
5060     * @param array $b Modules array.
5061     *
5062     * @return int 0 if the same sort or (+/-) to indicate which is greater.
5063     */
5064    public static function sort_modules( $a, $b ) {
5065        return $a['sort'] <=> $b['sort'];
5066    }
5067
5068    /**
5069     * Recheck SSL status for use via an AJAX call.
5070     *
5071     * Sends data back via `wp_send_json`.
5072     *
5073     * @return void
5074     */
5075    public function ajax_recheck_ssl() {
5076        check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5077        $result = self::permit_ssl( true );
5078        wp_send_json(
5079            array(
5080                'enabled' => $result,
5081                'message' => self::get_ssl_test_message(),
5082            ),
5083            null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
5084            JSON_UNESCAPED_SLASHES
5085        );
5086    }
5087
5088    /* Client API */
5089
5090    /**
5091     * Verify the onboarding token.
5092     *
5093     * @deprecated since 13.9
5094     *
5095     * @param array  $token_data Token data.
5096     * @param string $token Token value.
5097     * @param string $request_data JSON-encoded request data.
5098     *
5099     * @return mixed
5100     */
5101    public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5102        _deprecated_function( __METHOD__, '13.9' );
5103        // Default to a blog token.
5104        $token_type = 'blog';
5105
5106        // Let's see if this is onboarding. In such case, use user token type and the provided user id.
5107        if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes, if caller is changing the site the nonce should be verified there.
5108            if ( ! empty( $_GET['onboarding'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
5109                $jpo = $_GET; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
5110            } else {
5111                $jpo = json_decode( $request_data, true );
5112            }
5113
5114            $jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5115            $jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5116
5117            if (
5118                isset( $jpo_user )
5119                && isset( $jpo_token )
5120                && is_email( $jpo_user )
5121                && ctype_alnum( $jpo_token )
5122                && isset( $_GET['rest_route'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
5123                && self::validate_onboarding_token_action(
5124                    $jpo_token,
5125                    wp_unslash( $_GET['rest_route'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- no site changes.
5126                )
5127            ) {
5128                $jp_user = get_user_by( 'email', $jpo_user );
5129                if ( is_a( $jp_user, 'WP_User' ) ) {
5130                    wp_set_current_user( $jp_user->ID );
5131                    $user_can = is_multisite()
5132                        ? current_user_can_for_site( get_current_blog_id(), 'manage_options' )
5133                        : current_user_can( 'manage_options' );
5134                    if ( $user_can ) {
5135                        $token_type              = 'user';
5136                        $token->external_user_id = $jp_user->ID;
5137                    }
5138                }
5139            }
5140
5141            $token_data['type']    = $token_type;
5142            $token_data['user_id'] = $token->external_user_id;
5143        }
5144
5145        return $token_data;
5146    }
5147
5148    /**
5149     * Create a random secret for validating onboarding payload
5150     *
5151     * @deprecated since 13.9
5152     * @return string Secret token
5153     */
5154    public static function create_onboarding_token() {
5155        _deprecated_function( __METHOD__, '13.9' );
5156        $token = Jetpack_Options::get_option( 'onboarding' );
5157        if ( false === ( $token ) ) {
5158            $token = wp_generate_password( 32, false );
5159            Jetpack_Options::update_option( 'onboarding', $token );
5160        }
5161
5162        return $token;
5163    }
5164
5165    /**
5166     * Remove the onboarding token
5167     *
5168     * @deprecated since 13.9
5169     * @return bool True on success, false on failure
5170     */
5171    public static function invalidate_onboarding_token() {
5172        _deprecated_function( __METHOD__, '13.9' );
5173        return Jetpack_Options::delete_option( 'onboarding' );
5174    }
5175
5176    /**
5177     * Validate an onboarding token for a specific action
5178     *
5179     * @deprecated since 13.9
5180     *
5181     * @param string $token Onboarding token.
5182     * @param string $action Action name.
5183     *
5184     * @return boolean True if token/action pair is accepted, false if not
5185     */
5186    public static function validate_onboarding_token_action( $token, $action ) {
5187        _deprecated_function( __METHOD__, '13.9' );
5188        // Compare tokens, bail if tokens do not match.
5189        if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5190            return false;
5191        }
5192
5193        // List of valid actions we can take.
5194        $valid_actions = array(
5195            '/jetpack/v4/settings',
5196        );
5197
5198        // Only allow valid actions.
5199        if ( ! in_array( $action, $valid_actions, true ) ) {
5200            return false;
5201        }
5202
5203        return true;
5204    }
5205
5206    /**
5207     * Checks to see if the URL is using SSL to connect with Jetpack
5208     *
5209     * @param bool $force_recheck Force SSL recheck.
5210     *
5211     * @return boolean
5212     * @since 2.3.3
5213     */
5214    public static function permit_ssl( $force_recheck = false ) {
5215        // Delegates to the canonical SSL check in the Connection package.
5216        return Heartbeat::permit_ssl( $force_recheck );
5217    }
5218
5219    /**
5220     * Returns a localized message describing the last SSL connectivity failure, if any.
5221     *
5222     * The Connection package's canonical SSL check stores a neutral reason code; this maps it to
5223     * a translated, `jetpack`-domain message for display in the admin notice and AJAX recheck.
5224     *
5225     * @since 16.1
5226     *
5227     * @return string The localized message, or an empty string when there is no failure.
5228     */
5229    public static function get_ssl_test_message() {
5230        $error = Heartbeat::get_ssl_test_error();
5231
5232        switch ( $error['code'] ) {
5233            case 'no_ssl_support':
5234                return __( 'WordPress reports no SSL support', 'jetpack' );
5235            case 'bad_response':
5236                return __( 'Response was not OK: ', 'jetpack' ) . $error['detail'];
5237            default:
5238                return '';
5239        }
5240    }
5241
5242    /**
5243     * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5244     */
5245    public function alert_auto_ssl_fail() {
5246        if ( ! current_user_can( 'manage_options' ) ) {
5247            return;
5248        }
5249
5250        $ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5251        ?>
5252
5253        <div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5254            <div class="jp-banner__content">
5255                <h2><?php esc_html_e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5256                <p><?php esc_html_e( 'Your site could not connect to WordPress.com via HTTPS. This could be due to any number of reasons, including faulty SSL certificates, misconfigured or missing SSL libraries, or network issues.', 'jetpack' ); ?></p>
5257                <p>
5258                    <?php esc_html_e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5259                    <a href="#" id="jetpack-recheck-ssl-button"><?php esc_html_e( 'Try again', 'jetpack' ); ?></a>
5260                    <span id="jetpack-recheck-ssl-output"><?php echo esc_html( self::get_ssl_test_message() ); ?></span>
5261                </p>
5262                <p>
5263                    <?php
5264                    printf(
5265                            /* translators: Both are URLs. First for the connection debug tool and the second for a support page. */
5266                        __( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- we're building known HTML.
5267                        esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5268                        esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5269                    );
5270                    ?>
5271                </p>
5272            </div>
5273        </div>
5274        <style>
5275            #jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5276        </style>
5277        <script type="text/javascript">
5278            jQuery( document ).ready( function( $ ) {
5279                $( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5280                    var $this = $( this );
5281                    $this.html( <?php echo wp_json_encode( esc_html__( 'Checking', 'jetpack' ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> );
5282                    $( '#jetpack-recheck-ssl-output' ).html( '' );
5283                    e.preventDefault();
5284                    var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': <?php echo wp_json_encode( $ajax_nonce, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> };
5285                    $.post( ajaxurl, data )
5286                    .done( function( response ) {
5287                        if ( response.enabled ) {
5288                            $( '#jetpack-ssl-warning' ).hide();
5289                        } else {
5290                            this.html( <?php echo wp_json_encode( esc_html__( 'Try again', 'jetpack' ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> );
5291                            $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5292                        }
5293                    }.bind( $this ) );
5294                } );
5295            } );
5296        </script>
5297
5298        <?php
5299    }
5300
5301    /**
5302     * Returns the connection manager object.
5303     *
5304     * @return Automattic\Jetpack\Connection\Manager
5305     */
5306    public static function connection() {
5307        $jetpack = static::init();
5308
5309        // If the connection manager hasn't been instantiated, do that now.
5310        if ( ! $jetpack->connection_manager ) {
5311            $jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5312        }
5313
5314        return $jetpack->connection_manager;
5315    }
5316
5317    /**
5318     * Get verification secrets.
5319     *
5320     * @param string $action Action name.
5321     * @param int    $user_id User ID.
5322     *
5323     * @return array|string|WP_Error
5324     */
5325    public static function get_secrets( $action, $user_id ) {
5326        $secrets = ( new Secrets() )->get( $action, $user_id );
5327
5328        if ( Secrets::SECRETS_MISSING === $secrets ) {
5329            return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5330        }
5331
5332        if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5333            return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5334        }
5335
5336        return $secrets;
5337    }
5338
5339    /**
5340     * Filters the token request body to include tracking properties.
5341     *
5342     * @param array $properties Token request properties.
5343     *
5344     * @return array amended properties.
5345     */
5346    public static function filter_token_request_body( $properties ) {
5347        $tracking        = new Tracking();
5348        $tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5349
5350        return array_merge(
5351            $properties,
5352            array(
5353                '_ui' => $tracks_identity['_ui'],
5354                '_ut' => $tracks_identity['_ut'],
5355            )
5356        );
5357    }
5358
5359    /**
5360     * If the db version is showing something other that what we've got now, bump it to current.
5361     *
5362     * @return bool True if the option was incorrect and updated, false if nothing happened.
5363     */
5364    public static function maybe_set_version_option() {
5365        list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5366        if ( JETPACK__VERSION !== $version ) {
5367            Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5368
5369            if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5370                /** This action is documented in class.jetpack.php */
5371                do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5372            }
5373
5374            return true;
5375        }
5376        return false;
5377    }
5378
5379    /* Client Server API */
5380
5381    /**
5382     * State is passed via cookies from one request to the next, but never to subsequent requests.
5383     * SET: state( $key, $value );
5384     * GET: $value = state( $key );
5385     *
5386     * @param string $key State key.
5387     * @param string $value Value.
5388     * @param bool   $restate Reset the cookie (private).
5389     */
5390    public static function state( $key = null, $value = null, $restate = false ) {
5391        return ( new CookieState() )->state( $key, $value, $restate );
5392    }
5393
5394    /**
5395     * Set an empty state.
5396     *
5397     * @return void
5398     */
5399    public static function restate() {
5400        self::state( null, null, true );
5401    }
5402
5403    /**
5404     * Determines whether the jetpackState[$key] value should be added to the
5405     * cookie.
5406     *
5407     * @param string $key The state key.
5408     *
5409     * @return boolean Whether the value should be added to the cookie.
5410     */
5411    public static function should_set_cookie( $key ) {
5412        return ( new CookieState() )->should_set_cookie( $key );
5413    }
5414
5415    /**
5416     * Check if site is publicly accessible.
5417     *
5418     * @param string $file Module file.
5419     *
5420     * @return void
5421     */
5422    public static function check_privacy( $file ) {
5423        static $is_site_publicly_accessible = null;
5424
5425        if ( $is_site_publicly_accessible === null ) {
5426            $is_site_publicly_accessible = false;
5427
5428            $rpc = new Jetpack_IXR_Client();
5429
5430            $success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5431            if ( $success ) {
5432                $response = $rpc->getResponse();
5433                if ( $response ) {
5434                    $is_site_publicly_accessible = true;
5435                }
5436            }
5437
5438            Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5439        }
5440
5441        if ( $is_site_publicly_accessible ) {
5442            return;
5443        }
5444
5445        $module_slug = self::get_module_slug( $file );
5446
5447        $privacy_checks = self::state( 'privacy_checks' );
5448        if ( ! $privacy_checks ) {
5449            $privacy_checks = $module_slug;
5450        } else {
5451            $privacy_checks .= ",$module_slug";
5452        }
5453
5454        self::state( 'privacy_checks', $privacy_checks );
5455    }
5456
5457    /* JSON API Authorization */
5458
5459    /**
5460     * Handles the login action for Authorizing the JSON API
5461     */
5462    public function login_form_json_api_authorization() {
5463        $authorize_json_api = new Authorize_Json_Api();
5464        $authorize_json_api->verify_json_api_authorization_request();
5465
5466        add_action( 'wp_login', array( $authorize_json_api, 'store_json_api_authorization_token' ), 10, 2 );
5467
5468        add_action( 'login_message', array( $authorize_json_api, 'login_message_json_api_authorization' ) );
5469        add_action( 'login_form', array( $this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5470        add_filter( 'site_url', array( $this, 'post_login_form_to_signed_url' ), 10, 3 );
5471    }
5472
5473    /**
5474     * Make sure the login form is POSTed to the signed URL so we can reverify the request.
5475     *
5476     * @param string $url Redirect URL.
5477     * @param string $path Path.
5478     * @param string $scheme URL Scheme.
5479     */
5480    public function post_login_form_to_signed_url( $url, $path, $scheme ) {
5481        if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5482            return $url;
5483        }
5484        $query_string = isset( $_SERVER['QUERY_STRING'] ) ? wp_unslash( $_SERVER['QUERY_STRING'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
5485        $parsed_url   = wp_parse_url( $url );
5486        $url          = strtok( $url, '?' );
5487        $url          = "$url?{$query_string}";
5488        if ( ! empty( $parsed_url['query'] ) ) {
5489            $url .= "&{$parsed_url['query']}";
5490        }
5491
5492        return $url;
5493    }
5494
5495    /**
5496     * Make sure the POSTed request is handled by the same action.
5497     */
5498    public function preserve_action_in_login_form_for_json_api_authorization() {
5499        $http_host   = isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- escaped with esc_url below.
5500        $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- escaped with esc_url below.
5501        echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5502        echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $http_host . $request_uri ) ) . "' />\n";
5503    }
5504
5505    /**
5506     * If someone logs in to approve API access, store the Access Code in usermeta.
5507     *
5508     * @deprecated 13.4
5509     *
5510     * @param string  $user_login Unused.
5511     * @param WP_User $user User logged in.
5512     */
5513    public function store_json_api_authorization_token( $user_login, $user ) {
5514        _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Connection\\Authorize_Json_Api::store_json_api_authorization_token' );
5515
5516        return ( new Authorize_Json_Api() )->store_json_api_authorization_token( $user_login, $user );
5517    }
5518
5519    /**
5520     * Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5521     *
5522     * To be used with a filter of allowed domains for a redirect.
5523     *
5524     * @deprecated 13.4
5525     *
5526     * @param array $domains Allowed WP.com Environments.
5527     */
5528    public function allow_wpcom_public_api_domain( $domains ) {
5529        _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Status\\Host::allow_wpcom_public_api_domain' );
5530
5531        return Host::allow_wpcom_public_api_domain( $domains );
5532    }
5533
5534    /**
5535     * Check if the redirect is encoded.
5536     *
5537     * @deprecated 13.4
5538     *
5539     * @param string $redirect_url Redirect URL.
5540     *
5541     * @return bool If redirect has been encoded.
5542     */
5543    public static function is_redirect_encoded( $redirect_url ) {
5544        _deprecated_function( __METHOD__, 'jetpack-13.4' );
5545        return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5546    }
5547
5548    /**
5549     * Add all wordpress.com environments to the safe redirect allowed list.
5550     *
5551     * To be used with a filter of allowed domains for a redirect.
5552     *
5553     * @param array $domains Allowed WP.com Environments.
5554     *
5555     * @deprecated since 11.1
5556     */
5557    public function allow_wpcom_environments( $domains ) {
5558        return Host::allow_wpcom_environments( $domains );
5559    }
5560
5561    /**
5562     * Add the Access Code details to the public-api.wordpress.com redirect.
5563     *
5564     * @deprecated 13.4
5565     *
5566     * @param string  $redirect_to URL.
5567     * @param string  $original_redirect_to URL.
5568     * @param WP_User $user WP_User for the redirect.
5569     *
5570     * @return string
5571     */
5572    public function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5573        _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Connection\\Authorize_Json_Api::add_token_to_login_redirect_json_api_authorization' );
5574
5575        return ( new Authorize_Json_Api() )->add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user );
5576    }
5577
5578    /**
5579     * Verifies the request by checking the signature
5580     *
5581     * @deprecated 13.4
5582     *
5583     * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5584     * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5585     *
5586     * @param null|array $environment Value to override $_REQUEST.
5587     */
5588    public function verify_json_api_authorization_request( $environment = null ) {
5589        _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Connection\\Authorize_Json_Api::verify_json_api_authorization_request' );
5590
5591        return ( new Authorize_Json_Api() )->verify_json_api_authorization_request( $environment );
5592    }
5593
5594    /**
5595     * HTML for the JSON API authorization notice.
5596     *
5597     * @deprecated 13.4
5598     *
5599     * @return string
5600     */
5601    public function login_message_json_api_authorization() {
5602        _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Connection\\Authorize_Json_Api::login_message_json_api_authorization' );
5603
5604        return ( new Authorize_Json_Api() )->login_message_json_api_authorization();
5605    }
5606
5607    /**
5608     * Get $content_width, but with a <s>twist</s> filter.
5609     */
5610    public static function get_content_width() {
5611        $content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5612            ? $GLOBALS['content_width']
5613            : false;
5614        /**
5615         * Filter the Content Width value.
5616         *
5617         * @since 2.2.3
5618         *
5619         * @param string $content_width Content Width value.
5620         */
5621        return apply_filters( 'jetpack_content_width', $content_width );
5622    }
5623
5624    /**
5625     * Pings the WordPress.com Mirror Site for the specified options.
5626     *
5627     * @param string|array $option_names The option names to request from the WordPress.com Mirror Site.
5628     *
5629     * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5630     */
5631    public function get_cloud_site_options( $option_names ) {
5632        $option_names = array_filter( (array) $option_names, 'is_string' );
5633
5634        $xml = new Jetpack_IXR_Client();
5635        $xml->query( 'jetpack.fetchSiteOptions', $option_names );
5636        if ( $xml->isError() ) {
5637            return array(
5638                'error_code' => $xml->getErrorCode(),
5639                'error_msg'  => $xml->getErrorMessage(),
5640            );
5641        }
5642        $cloud_site_options = $xml->getResponse();
5643
5644        return $cloud_site_options;
5645    }
5646
5647    /**
5648     * Checks if the site is currently in an identity crisis.
5649     *
5650     * Now delegates to the Connection package so this matches what the heartbeat itself reports.
5651     * Note the package guards on `Connection\Manager::is_connected()` where this used to guard on
5652     * `Jetpack::is_connection_ready()`, so the `jetpack_is_connection_ready` filter no longer applies.
5653     *
5654     * @deprecated 16.2
5655     *
5656     * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5657     */
5658    public static function check_identity_crisis() {
5659        _deprecated_function( __METHOD__, 'jetpack-16.2', 'Automattic\\Jetpack\\Identity_Crisis::check_identity_crisis' );
5660
5661        return Identity_Crisis::check_identity_crisis();
5662    }
5663
5664    /**
5665     * Normalizes a url by doing three things:
5666     *  - Strips protocol
5667     *  - Strips www
5668     *  - Adds a trailing slash
5669     *
5670     * @since 4.4.0
5671     * @param string $url URL.
5672     * @return WP_Error|string
5673     */
5674    public static function normalize_url_protocol_agnostic( $url ) {
5675        $parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5676        if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5677            /* translators: URL string */
5678            return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5679        }
5680
5681        // Strip www and protocols.
5682        $url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5683        return $url;
5684    }
5685
5686    /**
5687     * Maybe Use a .min.css stylesheet, maybe not.
5688     *
5689     * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5690     *
5691     * @param string $url URL.
5692     * @param string $path File path.
5693     * @param string $plugin Plugin.
5694     *
5695     * @return mixed
5696     */
5697    public static function maybe_min_asset( $url, $path, $plugin ) {
5698        // Short out on things trying to find actual paths.
5699        if ( ! $path || empty( $plugin ) ) {
5700            return $url;
5701        }
5702
5703        $path = ltrim( $path, '/' );
5704
5705        // Strip out the abspath.
5706        $base = dirname( plugin_basename( $plugin ) );
5707
5708        // Short out on non-Jetpack assets.
5709        if ( ! str_starts_with( $base, 'jetpack/' ) ) {
5710            return $url;
5711        }
5712
5713        // File name parsing.
5714        $file              = "{$base}/{$path}";
5715        $full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5716        $file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5717        $file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5718        $extension         = array_shift( $file_name_parts_r );
5719
5720        if ( in_array( strtolower( $extension ), array( 'css', 'js' ), true ) ) {
5721            // Already pointing at the minified version.
5722            if ( 'min' === $file_name_parts_r[0] ) {
5723                return $url;
5724            }
5725
5726            $min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5727            if ( file_exists( $min_full_path ) ) {
5728                $url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5729                // If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5730                if ( 'css' === $extension ) {
5731                    $key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5732                    self::$min_assets[ $key ] = $path;
5733                }
5734            }
5735        }
5736
5737        return $url;
5738    }
5739
5740    /**
5741     * If the asset is minified, let's flag .min as the suffix.
5742     *
5743     * Attached to `style_loader_src` filter.
5744     *
5745     * @param string $src source file.
5746     * @param string $handle The registered handle of the script in question.
5747     *
5748     * @return mixed
5749     */
5750    public static function set_suffix_on_min( $src, $handle ) {
5751        if ( ! is_string( $src ) || ! str_contains( $src, '.min.css' ) ) {
5752            return $src;
5753        }
5754
5755        if ( ! empty( self::$min_assets ) ) {
5756            foreach ( self::$min_assets as $file => $path ) {
5757                if ( str_contains( $src, $file ) ) {
5758                    wp_style_add_data( $handle, 'suffix', '.min' );
5759                    return $src;
5760                }
5761            }
5762        }
5763
5764        return $src;
5765    }
5766
5767    /**
5768     * Maybe inlines a stylesheet.
5769     *
5770     * @deprecated since 11.7.
5771     *
5772     * @param string $tag The tag that would link to the external asset.
5773     * @param string $handle The registered handle of the script in question.
5774     *
5775     * @return string
5776     */
5777    public static function maybe_inline_style( $tag, $handle ) { //phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
5778        _deprecated_function( __METHOD__, '11.7', 'wp_maybe_inline_styles' );
5779
5780        return $tag;
5781    }
5782
5783    /**
5784     * Loads a view file from the views
5785     *
5786     * Data passed in with the $data parameter will be available in the
5787     * template file as $data['value']
5788     *
5789     * @html-template-var array $data
5790     *
5791     * @param string $template - Template file to load.
5792     * @param array  $data - Any data to pass along to the template.
5793     * @return boolean - If template file was found.
5794     **/
5795    public function load_view( $template, $data = array() ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- This is used via the required files.
5796        $views_dir = JETPACK__PLUGIN_DIR . 'views/';
5797
5798        if ( file_exists( $views_dir . $template ) ) {
5799            require_once $views_dir . $template;
5800            return true;
5801        }
5802
5803        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
5804            trigger_error( sprintf( 'Jetpack: Unable to find view file: %s', esc_html( $views_dir . $template ) ), E_USER_WARNING ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
5805        }
5806        return false;
5807    }
5808
5809    /**
5810     * Register Jetpack-specific tests on the connection package's health test suite.
5811     *
5812     * @param \Automattic\Jetpack\Connection\Connection_Health_Tests $connection_tests The test suite instance.
5813     */
5814    public function register_jetpack_connection_tests( $connection_tests ) {
5815        require_once JETPACK__PLUGIN_DIR . '_inc/lib/debugger/class-jetpack-cxn-tests.php';
5816        $jetpack_tests = new Jetpack_Cxn_Tests();
5817        $jetpack_tests->register_tests_on( $connection_tests );
5818    }
5819
5820    /**
5821     * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
5822     */
5823    public function deprecated_hooks() {
5824        $filter_deprecated_list = array(
5825            'jetpack_bail_on_shortcode'                    => array(
5826                'replacement' => 'jetpack_shortcodes_to_include',
5827                'version'     => 'jetpack-3.1.0',
5828            ),
5829            'wpl_sharing_2014_1'                           => array(
5830                'replacement' => null,
5831                'version'     => 'jetpack-3.6.0',
5832            ),
5833            'jetpack-tools-to-include'                     => array(
5834                'replacement' => 'jetpack_tools_to_include',
5835                'version'     => 'jetpack-3.9.0',
5836            ),
5837            'jetpack_identity_crisis_options_to_check'     => array(
5838                'replacement' => null,
5839                'version'     => 'jetpack-4.0.0',
5840            ),
5841            'update_option_jetpack_single_user_site'       => array(
5842                'replacement' => null,
5843                'version'     => 'jetpack-4.3.0',
5844            ),
5845            'audio_player_default_colors'                  => array(
5846                'replacement' => null,
5847                'version'     => 'jetpack-4.3.0',
5848            ),
5849            'add_option_jetpack_featured_images_enabled'   => array(
5850                'replacement' => null,
5851                'version'     => 'jetpack-4.3.0',
5852            ),
5853            'add_option_jetpack_update_details'            => array(
5854                'replacement' => null,
5855                'version'     => 'jetpack-4.3.0',
5856            ),
5857            'add_option_jetpack_updates'                   => array(
5858                'replacement' => null,
5859                'version'     => 'jetpack-4.3.0',
5860            ),
5861            'add_option_jetpack_network_name'              => array(
5862                'replacement' => null,
5863                'version'     => 'jetpack-4.3.0',
5864            ),
5865            'add_option_jetpack_network_allow_new_registrations' => array(
5866                'replacement' => null,
5867                'version'     => 'jetpack-4.3.0',
5868            ),
5869            'add_option_jetpack_network_add_new_users'     => array(
5870                'replacement' => null,
5871                'version'     => 'jetpack-4.3.0',
5872            ),
5873            'add_option_jetpack_network_site_upload_space' => array(
5874                'replacement' => null,
5875                'version'     => 'jetpack-4.3.0',
5876            ),
5877            'add_option_jetpack_network_upload_file_types' => array(
5878                'replacement' => null,
5879                'version'     => 'jetpack-4.3.0',
5880            ),
5881            'add_option_jetpack_network_enable_administration_menus' => array(
5882                'replacement' => null,
5883                'version'     => 'jetpack-4.3.0',
5884            ),
5885            'add_option_jetpack_is_multi_site'             => array(
5886                'replacement' => null,
5887                'version'     => 'jetpack-4.3.0',
5888            ),
5889            'add_option_jetpack_is_main_network'           => array(
5890                'replacement' => null,
5891                'version'     => 'jetpack-4.3.0',
5892            ),
5893            'add_option_jetpack_main_network_site'         => array(
5894                'replacement' => null,
5895                'version'     => 'jetpack-4.3.0',
5896            ),
5897            'jetpack_sync_all_registered_options'          => array(
5898                'replacement' => null,
5899                'version'     => 'jetpack-4.3.0',
5900            ),
5901            'jetpack_has_identity_crisis'                  => array(
5902                'replacement' => 'jetpack_sync_error_idc_validation',
5903                'version'     => 'jetpack-4.4.0',
5904            ),
5905            'jetpack_is_post_mailable'                     => array(
5906                'replacement' => null,
5907                'version'     => 'jetpack-4.4.0',
5908            ),
5909            'jetpack_seo_site_host'                        => array(
5910                'replacement' => null,
5911                'version'     => 'jetpack-5.1.0',
5912            ),
5913            'jetpack_installed_plugin'                     => array(
5914                'replacement' => 'jetpack_plugin_installed',
5915                'version'     => 'jetpack-6.0.0',
5916            ),
5917            'jetpack_holiday_snow_option_name'             => array(
5918                'replacement' => null,
5919                'version'     => 'jetpack-6.0.0',
5920            ),
5921            'jetpack_holiday_chance_of_snow'               => array(
5922                'replacement' => null,
5923                'version'     => 'jetpack-6.0.0',
5924            ),
5925            'jetpack_holiday_snow_js_url'                  => array(
5926                'replacement' => null,
5927                'version'     => 'jetpack-6.0.0',
5928            ),
5929            'jetpack_is_holiday_snow_season'               => array(
5930                'replacement' => null,
5931                'version'     => 'jetpack-6.0.0',
5932            ),
5933            'jetpack_holiday_snow_option_updated'          => array(
5934                'replacement' => null,
5935                'version'     => 'jetpack-6.0.0',
5936            ),
5937            'jetpack_holiday_snowing'                      => array(
5938                'replacement' => null,
5939                'version'     => 'jetpack-6.0.0',
5940            ),
5941            'jetpack_sso_auth_cookie_expirtation'          => array(
5942                'replacement' => 'jetpack_sso_auth_cookie_expiration',
5943                'version'     => 'jetpack-6.1.0',
5944            ),
5945            'jetpack_cache_plans'                          => array(
5946                'replacement' => null,
5947                'version'     => 'jetpack-6.1.0',
5948            ),
5949            'jetpack_enable_site_verification'             => array(
5950                'replacement' => null,
5951                'version'     => 'jetpack-6.5.0',
5952            ),
5953            'can_display_jetpack_manage_notice'            => array(
5954                'replacement' => null,
5955                'version'     => 'jetpack-7.3.0',
5956            ),
5957            'atd_http_post_timeout'                        => array(
5958                'replacement' => null,
5959                'version'     => 'jetpack-7.3.0',
5960            ),
5961            'atd_service_domain'                           => array(
5962                'replacement' => null,
5963                'version'     => 'jetpack-7.3.0',
5964            ),
5965            'atd_load_scripts'                             => array(
5966                'replacement' => null,
5967                'version'     => 'jetpack-7.3.0',
5968            ),
5969            'jetpack_widget_authors_exclude'               => array(
5970                'replacement' => 'jetpack_widget_authors_params',
5971                'version'     => 'jetpack-7.7.0',
5972            ),
5973            // Removed in Jetpack 7.9.0.
5974            'jetpack_pwa_manifest'                         => array(
5975                'replacement' => null,
5976                'version'     => 'jetpack-7.9.0',
5977            ),
5978            'jetpack_pwa_background_color'                 => array(
5979                'replacement' => null,
5980                'version'     => 'jetpack-7.9.0',
5981            ),
5982            'jetpack_check_mobile'                         => array(
5983                'replacement' => null,
5984                'version'     => 'jetpack-8.3.0',
5985            ),
5986            'jetpack_mobile_stylesheet'                    => array(
5987                'replacement' => null,
5988                'version'     => 'jetpack-8.3.0',
5989            ),
5990            'jetpack_mobile_template'                      => array(
5991                'replacement' => null,
5992                'version'     => 'jetpack-8.3.0',
5993            ),
5994            'jetpack_mobile_theme_menu'                    => array(
5995                'replacement' => null,
5996                'version'     => 'jetpack-8.3.0',
5997            ),
5998            'minileven_show_featured_images'               => array(
5999                'replacement' => null,
6000                'version'     => 'jetpack-8.3.0',
6001            ),
6002            'minileven_attachment_size'                    => array(
6003                'replacement' => null,
6004                'version'     => 'jetpack-8.3.0',
6005            ),
6006            'instagram_cache_oembed_api_response_body'     => array(
6007                'replacement' => null,
6008                'version'     => 'jetpack-9.1.0',
6009            ),
6010            'jetpack_can_make_outbound_https'              => array(
6011                'replacement' => null,
6012                'version'     => 'jetpack-9.1.0',
6013            ),
6014            'sharing_email_can_send'                       => array(
6015                'replacement' => null,
6016                'version'     => 'jetpack-11.0.0',
6017            ),
6018            'sharing_email_check'                          => array(
6019                'replacement' => null,
6020                'version'     => 'jetpack-11.0.0',
6021            ),
6022            'sharing_services_email'                       => array(
6023                'replacement' => null,
6024                'version'     => 'jetpack-11.0.0',
6025            ),
6026            'jetpack_dsp_promote_posts_enabled'            => array(
6027                'replacement' => null,
6028                'version'     => 'jetpack-11.8.0',
6029            ),
6030            'jetpack_are_blogging_prompts_enabled'         => array(
6031                'replacement' => null,
6032                'version'     => 'jetpack-11.8.0',
6033            ),
6034            'jetpack_subscriptions_modal_enabled'          => array(
6035                'replacement' => null,
6036                'version'     => 'jetpack-12.7.0',
6037            ),
6038            'jetpack_pre_connection_prompt_helpers'        => array(
6039                'replacement' => null,
6040                'version'     => 'jetpack-13.2.0',
6041            ),
6042            'jetpack_contact_form_use_package'             => array(
6043                'replacement' => null,
6044                'version'     => 'jetpack-13.4.0',
6045            ),
6046            // jetpack_implode_frontend_css has been removed, but is not listed here. The updated behavior is exactly the only use of the filter.
6047            // We can reassess formally deprecating it here later; for now, it would be noise with no functional difference.
6048        );
6049
6050        foreach ( $filter_deprecated_list as $tag => $args ) {
6051            if ( has_filter( $tag ) ) {
6052                apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6053            }
6054        }
6055
6056        $action_deprecated_list = array(
6057            'jetpack_updated_theme'        => array(
6058                'replacement' => 'jetpack_updated_themes',
6059                'version'     => 'jetpack-6.2.0',
6060            ),
6061            'atd_http_post_error'          => array(
6062                'replacement' => null,
6063                'version'     => 'jetpack-7.3.0',
6064            ),
6065            'mobile_reject_mobile'         => array(
6066                'replacement' => null,
6067                'version'     => 'jetpack-8.3.0',
6068            ),
6069            'mobile_force_mobile'          => array(
6070                'replacement' => null,
6071                'version'     => 'jetpack-8.3.0',
6072            ),
6073            'mobile_app_promo_download'    => array(
6074                'replacement' => null,
6075                'version'     => 'jetpack-8.3.0',
6076            ),
6077            'mobile_setup'                 => array(
6078                'replacement' => null,
6079                'version'     => 'jetpack-8.3.0',
6080            ),
6081            'jetpack_mobile_footer_before' => array(
6082                'replacement' => null,
6083                'version'     => 'jetpack-8.3.0',
6084            ),
6085            'wp_mobile_theme_footer'       => array(
6086                'replacement' => null,
6087                'version'     => 'jetpack-8.3.0',
6088            ),
6089            'minileven_credits'            => array(
6090                'replacement' => null,
6091                'version'     => 'jetpack-8.3.0',
6092            ),
6093            'jetpack_mobile_header_before' => array(
6094                'replacement' => null,
6095                'version'     => 'jetpack-8.3.0',
6096            ),
6097            'jetpack_mobile_header_after'  => array(
6098                'replacement' => null,
6099                'version'     => 'jetpack-8.3.0',
6100            ),
6101            'sharing_email_dialog'         => array(
6102                'replacement' => null,
6103                'version'     => 'jetpack-11.0.0',
6104            ),
6105            'sharing_email_send_post'      => array(
6106                'replacement' => null,
6107                'version'     => 'jetpack-11.0.0',
6108            ),
6109        );
6110
6111        foreach ( $action_deprecated_list as $tag => $args ) {
6112            if ( has_action( $tag ) ) {
6113                do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6114            }
6115        }
6116    }
6117
6118    /**
6119     * Converts any url in a stylesheet, to the correct absolute url.
6120     *
6121     * Considerations:
6122     *  - Normal, relative URLs     `feh.png`
6123     *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6124     *  - Schema-agnostic URLs      `//domain.com/feh.png`
6125     *  - Absolute URLs             `http://domain.com/feh.png`
6126     *  - Domain root relative URLs `/feh.png`
6127     *
6128     * @param string $css The raw CSS -- should be read in directly from the file.
6129     * @param string $css_file_url The URL that the file can be accessed at, for calculating paths from.
6130     *
6131     * @return mixed|string
6132     */
6133    public static function absolutize_css_urls( $css, $css_file_url ) {
6134        $pattern = '#url\((?P<path>[^)]*)\)#i';
6135        $css_dir = dirname( $css_file_url );
6136        $p       = wp_parse_url( $css_dir );
6137        $domain  = sprintf(
6138            '%1$s//%2$s%3$s%4$s',
6139            isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6140            isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6141            $p['host'],
6142            isset( $p['port'] ) ? ":{$p['port']}" : ''
6143        );
6144
6145        if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6146            $replace = array();
6147            $find    = array();
6148            foreach ( $matches as $match ) {
6149                $url = trim( $match['path'], "'\" \t" );
6150
6151                // If this is a data url, we don't want to mess with it.
6152                if ( str_starts_with( $url, 'data:' ) ) {
6153                    continue;
6154                }
6155
6156                // If this is an absolute or protocol-agnostic url,
6157                // we don't want to mess with it.
6158                if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6159                    continue;
6160                }
6161
6162                switch ( substr( $url, 0, 1 ) ) {
6163                    case '/':
6164                        $absolute = $domain . $url;
6165                        break;
6166                    default:
6167                        $absolute = $css_dir . '/' . $url;
6168                }
6169
6170                $find[]    = $match[0];
6171                $replace[] = sprintf( 'url("%s")', $absolute );
6172            }
6173            $css = str_replace( $find, $replace, $css );
6174        }
6175
6176        return $css;
6177    }
6178
6179    /**
6180     * Check the heartbeat data
6181     *
6182     * Organizes the heartbeat data by severity.  For example, if the site
6183     * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6184     *
6185     * Data will be added to "caution" array, if it either:
6186     *  - Out of date Jetpack version
6187     *  - Out of date WP version
6188     *  - Out of date PHP version
6189     *
6190     * $return array $filtered_data
6191     */
6192    public static function jetpack_check_heartbeat_data() {
6193        /*
6194         * Site environment stats (incl. wp-version/php-version checked below) now live in the Connection package,
6195         * and the IDC stat is contributed by the Connection package's `jetpack_heartbeat_stats_array` filter
6196         * callback. We rebuild the stat here rather than running that filter: the filter's callbacks have side
6197         * effects (Connection\Manager::add_stats_to_heartbeat() consumes and deletes the `xmlrpc_errors` option)
6198         * and return non-scalar values, neither of which is appropriate for this read-only diagnostic.
6199         */
6200        $raw_data = array_merge(
6201            Jetpack_Heartbeat::generate_stats_array(),
6202            Heartbeat::get_environment_stats(),
6203            array( 'identitycrisis' => Identity_Crisis::check_identity_crisis() ? 'yes' : 'no' )
6204        );
6205
6206        $good    = array();
6207        $caution = array();
6208        $bad     = array();
6209
6210        foreach ( $raw_data as $stat => $value ) {
6211
6212            // Check jetpack version.
6213            if ( 'version' === $stat ) {
6214                if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6215                    $caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6216                    continue;
6217                }
6218            }
6219
6220            // Check WP version.
6221            if ( 'wp-version' === $stat ) {
6222                if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6223                    $caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6224                    continue;
6225                }
6226            }
6227
6228            // Check PHP version.
6229            if ( 'php-version' === $stat ) {
6230                if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6231                    $caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6232                    continue;
6233                }
6234            }
6235
6236            // Check ID crisis.
6237            if ( 'identitycrisis' === $stat ) {
6238                if ( 'yes' === $value ) {
6239                    $bad[ $stat ] = $value;
6240                    continue;
6241                }
6242            }
6243
6244            // The rest are good :).
6245            $good[ $stat ] = $value;
6246        }
6247
6248        $filtered_data = array(
6249            'good'    => $good,
6250            'caution' => $caution,
6251            'bad'     => $bad,
6252        );
6253
6254        return $filtered_data;
6255    }
6256
6257    /**
6258     * This method is used to organize all options that can be reset
6259     * without disconnecting Jetpack.
6260     *
6261     * It is used in class.jetpack-cli.php to reset options
6262     *
6263     * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6264     *
6265     * @return array of options to delete.
6266     */
6267    public static function get_jetpack_options_for_reset() {
6268        return Jetpack_Options::get_options_for_reset();
6269    }
6270
6271    /**
6272     * Get the user's meta box order.
6273     *
6274     * @param array $sorted Value for the user's option.
6275     * @return mixed
6276     */
6277    public function get_user_option_meta_box_order_dashboard( $sorted ) {
6278        if ( ! is_array( $sorted ) ) {
6279            return $sorted;
6280        }
6281
6282        foreach ( $sorted as $box_context => $ids ) {
6283            if ( ! str_contains( $ids, 'dashboard_stats' ) ) {
6284                // If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6285                continue;
6286            }
6287
6288            $ids_array = explode( ',', $ids );
6289            $key       = array_search( 'dashboard_stats', $ids_array, true );
6290
6291            if ( false !== $key ) {
6292                // If we've found that exact value in the option (and not `google_dashboard_stats` for example).
6293                $ids_array[ $key ]      = 'jetpack_summary_widget';
6294                $sorted[ $box_context ] = implode( ',', $ids_array );
6295                // We've found it, stop searching, and just return.
6296                break;
6297            }
6298        }
6299
6300        return $sorted;
6301    }
6302    /**
6303     * Checks if Akismet is active and working.
6304     *
6305     * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6306     * that implied usage of methods present since more recent version.
6307     * See https://github.com/Automattic/jetpack/pull/9585
6308     *
6309     * @since  5.1.0
6310     *
6311     * @return bool True = Akismet available. False = Aksimet not available.
6312     */
6313    public static function is_akismet_active() {
6314        static $status = null;
6315
6316        if ( $status !== null ) {
6317            return $status;
6318        }
6319
6320        // Check if a modern version of Akismet is active.
6321        if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6322            $status = false;
6323            return $status;
6324        }
6325
6326        // Make sure there is a key known to Akismet at all before verifying key.
6327        $akismet_key = Akismet::get_api_key();
6328        if ( ! $akismet_key ) {
6329            $status = false;
6330            return $status;
6331        }
6332
6333        // Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6334        $akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6335
6336        // Do not used the cache result in wp-admin or REST API requests if the key isn't valid, in case someone is actively renewing, etc.
6337        $recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6338        // We cache the result of the Akismet key verification for ten minutes.
6339        if ( ! $akismet_key_state || $recheck ) {
6340            $akismet_key_state = Akismet::verify_key( $akismet_key );
6341            set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6342        }
6343
6344        $status = 'valid' === $akismet_key_state;
6345
6346        return $status;
6347    }
6348
6349    /**
6350     * Given a minified path, and a non-minified path, will return
6351     * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6352     *
6353     * Both `$min_base` and `$non_min_base` are expected to be relative to the
6354     * root Jetpack directory.
6355     *
6356     * @since 5.6.0
6357     *
6358     * @param string $min_path Minimized path.
6359     * @param string $non_min_path Non-minimized path.
6360     * @return string The URL to the file
6361     */
6362    public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6363        return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6364    }
6365
6366    /**
6367     * Checks for whether Jetpack Backup is enabled.
6368     * Will return true if the state of Backup is anything except "unavailable".
6369     *
6370     * @return bool|int|mixed
6371     */
6372    public static function is_rewind_enabled() {
6373        // Rewind is a paid feature, therefore requires a user-level connection.
6374        if ( ! static::connection()->has_connected_owner() ) {
6375            return false;
6376        }
6377        $rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6378        $recheck        = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && '0' === $rewind_enabled;
6379        if ( false === $rewind_enabled || $recheck ) {
6380            require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.core-rest-api-endpoints.php';
6381            $rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6382            $rewind_enabled = ( ! is_wp_error( $rewind_data )
6383                && ! empty( $rewind_data['state'] )
6384                && 'active' === $rewind_data['state'] )
6385                ? 1
6386                : 0;
6387            set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6388        }
6389        return $rewind_enabled;
6390    }
6391
6392    /**
6393     * Return Calypso environment value; used for developing Jetpack and pairing
6394     * it with different Calypso enrionments, such as localhost.
6395     *
6396     * @deprecated 12.4 Moved to the Status package.
6397     *
6398     * @return string Calypso environment
6399     */
6400    public static function get_calypso_env() {
6401        _deprecated_function( __METHOD__, 'jetpack-12.4', '\Automattic\Jetpack\Status\Host->get_calypso_env' );
6402        return ( new Host() )->get_calypso_env();
6403    }
6404
6405    /**
6406     * Returns the hostname with protocol for Calypso.
6407     * Used for developing Jetpack with Calypso.
6408     *
6409     * @since 8.4.0
6410     *
6411     * @return string Calypso host.
6412     */
6413    public static function get_calypso_host() {
6414        $calypso_env = ( new Host() )->get_calypso_env();
6415        switch ( $calypso_env ) {
6416            case 'development':
6417                return 'http://calypso.localhost:3000/';
6418            case 'wpcalypso':
6419                return 'https://wpcalypso.wordpress.com/';
6420            case 'horizon':
6421                return 'https://horizon.wordpress.com/';
6422            default:
6423                return 'https://wordpress.com/';
6424        }
6425    }
6426
6427    /**
6428     * Handles activating default modules as well general cleanup for the new connection.
6429     *
6430     * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6431     * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6432     * @param boolean $send_state_messages          Whether to send state messages.
6433     * @return void
6434     */
6435    public static function handle_post_authorization_actions(
6436        $activate_sso = false,
6437        $redirect_on_activation_error = false,
6438        $send_state_messages = true
6439    ) {
6440        $other_modules = $activate_sso
6441            ? array( 'sso' )
6442            : array();
6443
6444        if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
6445            $active_modules = self::get_active_modules();
6446            self::delete_active_modules();
6447
6448            self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
6449        } else {
6450            // Default modules that don't require a user were already activated on site_register.
6451            // This time let's activate only those that require a user, this assures we don't reactivate manually deactivated modules while the site was connected only at a site level.
6452            self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
6453            Jetpack_Options::update_option( 'active_modules_initialized', true );
6454        }
6455
6456        // Since this is a fresh connection, be sure to clear out IDC options.
6457        Identity_Crisis::clear_all_idc_options();
6458
6459        if ( $send_state_messages ) {
6460            self::state( 'message', 'authorized' );
6461        }
6462    }
6463
6464    /**
6465     * Whether UI for backups should be displayed.
6466     *
6467     * On WPCom platforms this is gated on the backups-self-serve site feature.
6468     * On self-hosted Jetpack sites it falls back to the jetpack_show_backups filter.
6469     *
6470     * @return bool Should backups UI be displayed?
6471     */
6472    public static function show_backups_ui() {
6473        if ( ( new \Automattic\Jetpack\Status\Host() )->is_wpcom_platform() ) {
6474            return function_exists( 'wpcom_site_has_feature' ) && wpcom_site_has_feature( 'backups-self-serve' );
6475        }
6476
6477        /**
6478         * Whether UI for backups should be displayed.
6479         *
6480         * @since 6.5.0
6481         *
6482         * @param bool $show_backups Should UI for backups be displayed? True by default.
6483         */
6484        return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6485    }
6486
6487    /**
6488     * Whether UI for security scanning should be displayed.
6489     *
6490     * On WPCom platforms this is gated on the scan-self-serve site feature.
6491     * On self-hosted Jetpack sites it always returns true.
6492     *
6493     * @return bool Should scan UI be displayed?
6494     */
6495    public static function show_scan_ui() {
6496        if ( ( new \Automattic\Jetpack\Status\Host() )->is_wpcom_platform() ) {
6497            return function_exists( 'wpcom_site_has_feature' ) && wpcom_site_has_feature( 'scan-self-serve' );
6498        }
6499
6500        return true;
6501    }
6502
6503    /**
6504     * Clean leftoveruser meta.
6505     *
6506     * Delete Jetpack-related user meta when it is no longer needed.
6507     *
6508     * @since 7.3.0
6509     *
6510     * @param int $user_id User ID being updated.
6511     */
6512    public static function user_meta_cleanup( $user_id ) {
6513        $meta_keys = array(
6514            // AtD removed from Jetpack 7.3.
6515            'AtD_options',
6516            'AtD_check_when',
6517            'AtD_guess_lang',
6518            'AtD_ignored_phrases',
6519        );
6520
6521        foreach ( $meta_keys as $meta_key ) {
6522            if ( get_user_meta( $user_id, $meta_key ) ) {
6523                delete_user_meta( $user_id, $meta_key );
6524            }
6525        }
6526    }
6527
6528    /**
6529     * Checks if a Jetpack site is both active and not in offline mode.
6530     *
6531     * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
6532     *
6533     * @since 8.8.0
6534     *
6535     * @return bool True if Jetpack is active and not in offline mode.
6536     */
6537    public static function is_active_and_not_offline_mode() {
6538        if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
6539            return false;
6540        }
6541        return true;
6542    }
6543
6544    /**
6545     * Returns the list of products that we have available for purchase.
6546     *
6547     * This method will not take current purchases or upgrades into account
6548     * but is instead a static list of products Jetpack offers with some
6549     * corresponding sales text/materials.
6550     *
6551     * @param bool $show_legacy Determine if we should include legacy product/plan details.
6552     * @return array
6553     */
6554    public static function get_products_for_purchase( $show_legacy = false ) {
6555        $products = array();
6556
6557        $products['backup'] = array(
6558            'title'             => __( 'Jetpack Backup', 'jetpack' ),
6559            'slug'              => 'jetpack_backup_t1_yearly',
6560            'description'       => __( 'Never lose a word, image, page, or time worrying about your site with automated backups & one-click restores.', 'jetpack' ),
6561            'show_promotion'    => true,
6562            'discount_percent'  => 50,
6563            'included_in_plans' => array( 'security' ),
6564            'features'          => array(
6565                _x( 'Real-time cloud backups', 'Backup Product Feature', 'jetpack' ),
6566                _x( '10GB of backup storage', 'Backup Product Feature', 'jetpack' ),
6567                _x( '30-day archive & activity log*', 'Backup Product Feature', 'jetpack' ),
6568                _x( 'One-click restores', 'Backup Product Feature', 'jetpack' ),
6569            ),
6570            'disclaimer'        => array(
6571                'text'      => __( '* Subject to your usage and storage limit.', 'jetpack' ),
6572                'link_text' => __( 'Learn more', 'jetpack' ),
6573                'url'       => Redirect::get_url( 'jetpack-faq-backup-disclaimer' ),
6574            ),
6575        );
6576
6577        $products['creator'] = array(
6578            'title'             => __( 'Jetpack Creator', 'jetpack' ),
6579            'slug'              => 'jetpack_creator_yearly',
6580            'description'       => __( 'Craft stunning content, boost your subscriber base, and monetize your online presence.', 'jetpack' ),
6581            'show_promotion'    => true,
6582            'discount_percent'  => 50,
6583            'included_in_plans' => array( 'complete' ),
6584            'features'          => array(
6585                _x( 'Unlimited subscriber imports', 'Creator Product Feature', 'jetpack' ),
6586                _x( 'Earn more from your content', 'Creator Product Feature', 'jetpack' ),
6587                _x( 'Accept payments with PayPal', 'Creator Product Feature', 'jetpack' ),
6588                _x( 'Increase earnings with WordAds', 'Creator Product Feature', 'jetpack' ),
6589            ),
6590        );
6591
6592        $products['growth'] = array(
6593            'title'             => __( 'Jetpack Growth', 'jetpack' ),
6594            'slug'              => 'jetpack_growth_yearly',
6595            'description'       => __( 'Essential tools to help you grow your audience, track visitor engagement, and turn leads into loyal customers and advocates.', 'jetpack' ),
6596            'show_promotion'    => true,
6597            'discount_percent'  => 50,
6598            'included_in_plans' => array( 'complete' ),
6599            'features'          => array(
6600                _x( 'Jetpack Social', 'Growth Product Feature', 'jetpack' ),
6601                _x( 'Jetpack Stats (10K site views, upgradeable)', 'Growth Product Feature', 'jetpack' ),
6602                _x( 'Unlimited subscriber imports', 'Growth Product Feature', 'jetpack' ),
6603                _x( 'Earn more from your content', 'Growth Product Feature', 'jetpack' ),
6604                _x( 'Accept payments with PayPal', 'Growth Product Feature', 'jetpack' ),
6605                _x( 'Increase earnings with WordAds', 'Growth Product Feature', 'jetpack' ),
6606            ),
6607        );
6608
6609        $products['scan'] = array(
6610            'title'             => __( 'Jetpack Scan', 'jetpack' ),
6611            'slug'              => 'jetpack_scan',
6612            'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats and malware.', 'jetpack' ),
6613            'show_promotion'    => true,
6614            'discount_percent'  => 50,
6615            'included_in_plans' => array( 'security' ),
6616            'features'          => array(
6617                _x( 'Automated daily scanning', 'Scan Product Feature', 'jetpack' ),
6618                _x( 'One-click fixes for most issues', 'Scan Product Feature', 'jetpack' ),
6619                _x( 'Instant email notifications', 'Scan Product Feature', 'jetpack' ),
6620                _x( 'Access to latest Firewall rules', 'Scan Product Feature', 'jetpack' ),
6621            ),
6622        );
6623
6624        $products['search'] = array(
6625            'title'             => __( 'Jetpack Site Search', 'jetpack' ),
6626            'slug'              => 'jetpack_search',
6627            'description'       => __( 'Help your site visitors find answers instantly so they keep reading and buying. Great for sites with a lot of content.', 'jetpack' ),
6628            'show_promotion'    => true,
6629            'discount_percent'  => 50,
6630            'included_in_plans' => array(),
6631            'features'          => array(
6632                _x( 'Instant search and indexing', 'Search Product Feature', 'jetpack' ),
6633                _x( 'Powerful filtering', 'Search Product Feature', 'jetpack' ),
6634                _x( 'Supports 38 languages', 'Search Product Feature', 'jetpack' ),
6635                _x( 'Spelling correction', 'Search Product Feature', 'jetpack' ),
6636            ),
6637        );
6638
6639        $products['akismet'] = array(
6640            'title'             => __( 'Akismet Anti-spam', 'jetpack' ),
6641            'slug'              => 'jetpack_anti_spam',
6642            'description'       => __( 'Save time and get better responses by automatically blocking spam from your comments and forms.', 'jetpack' ),
6643            'show_promotion'    => true,
6644            'discount_percent'  => 50,
6645            'included_in_plans' => array( 'security' ),
6646            'features'          => array(
6647                _x( 'Comment and form spam protection', 'Anti-Spam Product Feature', 'jetpack' ),
6648                _x( 'Block spam without CAPTCHAs', 'Anti-Spam Product Feature', 'jetpack' ),
6649                _x( 'Advanced stats', 'Anti-Spam Product Feature', 'jetpack' ),
6650            ),
6651        );
6652
6653        $products['security'] = array(
6654            'title'             => _x( 'Security', 'Jetpack product name', 'jetpack' ),
6655            'slug'              => 'jetpack_security_t1_yearly',
6656            'description'       => __( 'Comprehensive site security, including Backup, Scan, and Anti-spam.', 'jetpack' ),
6657            'show_promotion'    => true,
6658            'discount_percent'  => 50,
6659            'included_in_plans' => array(),
6660            'features'          => array(
6661                _x( 'Real-time cloud backups with 10GB storage', 'Security Tier 1 Feature', 'jetpack' ),
6662                _x( 'Automated real-time malware scan', 'Security Daily Plan Feature', 'jetpack' ),
6663                _x( 'One-click fixes for most threats', 'Security Daily Plan Feature', 'jetpack' ),
6664                _x( 'Comment & form spam protection', 'Security Daily Plan Feature', 'jetpack' ),
6665            ),
6666        );
6667
6668        $products['videopress'] = array(
6669            'title'             => __( 'Jetpack VideoPress', 'jetpack' ),
6670            'slug'              => 'jetpack_videopress',
6671            'description'       => __( 'High-quality, ad-free video built specifically for WordPress.', 'jetpack' ),
6672            'show_promotion'    => true,
6673            'discount_percent'  => 50,
6674            'included_in_plans' => array(),
6675            'features'          => array(
6676                _x( '1TB of storage', 'VideoPress Product Feature', 'jetpack' ),
6677                _x( 'Built into WordPress editor', 'VideoPress Product Feature', 'jetpack' ),
6678                _x( 'Ad-free and customizable player', 'VideoPress Product Feature', 'jetpack' ),
6679                _x( 'Unlimited users', 'VideoPress Product Feature', 'jetpack' ),
6680            ),
6681        );
6682
6683        if ( $show_legacy ) {
6684            $products['jetpack_backup_daily'] = array(
6685                'title'             => __( 'Jetpack Backup', 'jetpack' ),
6686                'slug'              => 'jetpack_backup_daily',
6687                'description'       => __( 'Never lose a word, image, page, or time worrying about your site with automated backups & one-click restores.', 'jetpack' ),
6688                'show_promotion'    => false,
6689                'discount_percent'  => 0,
6690                'included_in_plans' => array(),
6691                'features'          => array(
6692                    _x( 'Automated daily backups (off-site)', 'Backup Product Feature', 'jetpack' ),
6693                    _x( 'One-click restores', 'Backup Product Feature', 'jetpack' ),
6694                    _x( 'Unlimited backup storage', 'Backup Product Feature', 'jetpack' ),
6695                ),
6696            );
6697        }
6698
6699        return $products;
6700    }
6701
6702    /**
6703     * Register product descriptions for partner coupon usage.
6704     *
6705     * @since 10.4.0
6706     *
6707     * @param array $products An array of registered products.
6708     *
6709     * @return array
6710     */
6711    public function get_partner_coupon_product_descriptions( $products ) {
6712        return array_merge( $products, self::get_products_for_purchase( true ) );
6713    }
6714
6715    /**
6716     * Determine if the current user is allowed to make Jetpack purchases without
6717     * a WordPress.com account
6718     *
6719     * @return boolean True if the user can make purchases, false if not
6720     */
6721    public static function current_user_can_purchase() {
6722
6723        // The site must be site-connected to Jetpack (no users connected).
6724        if ( ! self::connection()->is_site_connection() ) {
6725            return false;
6726        }
6727
6728        // Make sure only administrators can make purchases.
6729        if ( ! current_user_can( 'manage_options' ) ) {
6730            return false;
6731        }
6732
6733        return true;
6734    }
6735
6736    /**
6737     * Add 5-star review link on the Jetpack Plugin meta, in the plugins list table (on the plugins page).
6738     *
6739     * @param array  $plugin_meta An array of the plugin's metadata.
6740     * @param string $plugin_file Path to the plugin file.
6741     *
6742     * @return array $plugin_meta An array of the plugin's metadata.
6743     */
6744    public function add_5_star_review_link( $plugin_meta, $plugin_file ) {
6745        if ( $plugin_file !== 'jetpack/jetpack.php' ) {
6746            return $plugin_meta;
6747        }
6748
6749        $u    = get_current_user_id();
6750        $site = get_site_url();
6751
6752        $plugin_meta[] = '<a href="https://jetpack.com/redirect?source=jetpack-plugin-review&site=' . esc_attr( $site ) . '&u=' . esc_attr( $u ) . '" target="_blank" rel="noopener noreferrer" title="' . esc_attr__( 'Rate Jetpack on WordPress.org', 'jetpack' ) . '" style="color: #ffb900">'
6753            . str_repeat( '<span class="dashicons dashicons-star-filled" style="font-size: 16px; width:16px; height: 16px"></span>', 5 )
6754            . '</a>';
6755
6756        return $plugin_meta;
6757    }
6758
6759    /**
6760     * Lazy instantiation of the Plugin_Tracking object.
6761     *
6762     * @since 13.9
6763     *
6764     * @return void
6765     */
6766    public function initialize_tracking() {
6767        if ( did_action( 'jetpack_initialize_tracking' ) > 1 ) {
6768            // Only need to run once.
6769            return;
6770        }
6771
6772        if ( ( new Tracking( 'jetpack', $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) || static::is_connection_ready() ) {
6773            ( new Plugin_Tracking() )->init();
6774        }
6775    }
6776
6777    /**
6778     * Run the "initialize tracking" hook.
6779     *
6780     * @since 13.9
6781     */
6782    public function run_initialize_tracking_action() {
6783        /**
6784         * Fires when the tracking needs to be initialized.
6785         * Doesn't necessarily mean that will actually happen, depends if the 'jetpack_tos_agreed' option is set.
6786         *
6787         * @since 13.9
6788         */
6789        do_action( 'jetpack_initialize_tracking' );
6790    }
6791
6792    /**
6793     * Initialize REST jsonAPI if needed.
6794     *
6795     * @return void
6796     */
6797    public function maybe_initialize_rest_jsonapi() {
6798        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
6799        if ( ! empty( $_GET['jsonapi'] ) && ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) ) {
6800            require_once ABSPATH . 'wp-admin/includes/admin.php'; // JSON API relies on WP functionality not autoloaded in REST.
6801
6802            define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' );
6803            require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php';
6804        }
6805    }
6806
6807    /**
6808     * Run plugin post-activation actions if we need to.
6809     *
6810     * @return void
6811     */
6812    private function plugin_post_activation() {
6813        if ( ( new Status() )->is_offline_mode() ) {
6814            return;
6815        }
6816
6817        if ( get_transient( 'activated_jetpack' ) ) {
6818            delete_transient( 'activated_jetpack' );
6819
6820            if ( ( new Host() )->is_woa_site() ) {
6821                $redirect_url = static::admin_url( 'page=jetpack' );
6822            } elseif ( is_network_admin() ) {
6823                $redirect_url = admin_url( 'network/admin.php?page=jetpack' );
6824            } elseif ( get_transient( 'my_jetpack_product_activated' ) ) {
6825                // don't redirect if this is an activation that just came from My Jetpack
6826                // My Jetpack has its own set of post-activation redirects
6827                return;
6828            } elseif ( My_Jetpack_Initializer::should_initialize() ) {
6829                $redirect_url = static::admin_url( 'page=my-jetpack' );
6830            } else {
6831                $redirect_url = static::admin_url( 'page=jetpack' );
6832            }
6833
6834            wp_safe_redirect( $redirect_url );
6835        }
6836    }
6837}