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