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