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