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