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