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