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