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