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