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