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