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