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