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