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