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