Completed
Push — renovate/slack-web-api-6.x ( 1d54b7...bfe495 )
by
unknown
193:23 queued 183:13
created

Jetpack   F

Complexity

Total Complexity 1001

Size/Duplication

Total Lines 7450
Duplicated Lines 4.26 %

Coupling/Cohesion

Components 3
Dependencies 45

Importance

Changes 0
Metric Value
wmc 1001
lcom 3
cbo 45
dl 317
loc 7450
rs 0.8
c 0
b 0
f 0

264 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 8 2
F plugin_upgrade() 0 88 17
A upgrade_on_load() 0 30 5
A update_active_modules() 0 53 3
A delete_active_modules() 0 3 1
A add_configure_hook() 0 21 4
B __construct() 0 158 6
B admin_notices() 0 125 7
A track_xmlrpc_error() 0 15 4
A initialize_stats() 0 5 2
A stat() 0 7 1
A do_stats() 0 11 2
A do_server_side_stat() 0 5 1
A build_stats_url() 0 6 1
A translate_current_user_to_role() 0 6 1
A translate_user_to_role() 0 6 1
A translate_role_to_cap() 0 6 1
A sign_role() 0 4 1
C build_connect_url() 0 62 12
D configure() 0 84 11
A late_initialization() 0 17 1
A setup_xmlrpc_handlers() 19 19 2
A initialize_rest_api_registration_connector() 9 9 2
A add_wpcom_to_allowed_redirect_hosts() 0 3 1
A allow_wpcom_domain() 0 7 2
A point_edit_post_links_to_calypso() 0 29 3
A point_edit_comment_links_to_calypso() 0 12 1
A jetpack_track_last_sync_callback() 0 22 5
A jetpack_connection_banner_callback() 0 14 3
A remove_non_jetpack_xmlrpc_methods() 9 9 2
A alternate_xmlrpc() 9 9 2
A jetpack_jitm_ajax_callback() 0 3 1
A push_stats() 0 5 2
B jetpack_custom_caps() 0 35 11
A require_jetpack_authentication() 9 9 2
B register_assets() 10 62 6
C guess_locale_from_lang() 39 39 12
A get_locale() 0 9 2
A jetpack_main_network_site_option() 0 3 1
A network_name() 0 4 1
A network_allow_new_registrations() 0 3 2
A network_add_new_users() 0 3 1
A network_site_upload_space() 0 4 2
A network_upload_file_types() 0 3 1
A network_max_upload_file_size() 0 4 1
A network_enable_administration_menus() 0 3 1
A maybe_clear_other_linked_admins_transient() 0 8 5
B get_other_linked_admins() 0 28 7
A is_main_network_option() 0 4 1
A is_multisite() 0 3 1
A is_multi_network() 15 15 3
A update_jetpack_main_network_site_option() 0 3 1
A update_jetpack_network_settings() 0 4 1
A is_single_user_site() 9 9 2
A file_system_write_access() 0 20 4
A is_version_controlled() 0 4 1
A featured_images_enabled() 0 4 2
A get_avatar_url() 0 11 1
A get_updates() 6 17 6
A get_update_details() 0 8 1
A refresh_update_data() 0 4 1
A refresh_theme_data() 0 3 1
A is_active() 0 3 1
A refresh_active_plan_from_wpcom() 0 4 1
A get_active_plan() 0 4 1
A active_plan_supports() 0 4 1
A is_development_mode() 0 3 1
A is_onboarding() 0 3 1
B development_mode_trigger_text() 0 23 9
A show_development_mode_notice() 17 28 4
A is_development_version() 0 15 1
A is_user_connected() 0 4 1
A get_connected_user_data() 0 4 1
A get_connected_user_email() 0 16 3
A get_master_user_email() 0 7 2
A current_user_is_connection_owner() 0 4 1
A current_user_ip() 0 20 5
A user_role_change() 0 4 1
D load_modules() 6 88 17
A check_rest_api_compat() 0 14 2
A get_active_plugins() 0 16 3
A get_parsed_plugin_data() 0 21 3
A get_parsed_theme_data() 0 22 3
A is_plugin_active() 0 3 1
B check_open_graph() 0 27 7
A check_twitter_tags() 0 24 5
A submit_security_report() 0 3 1
A get_option_names() 0 3 1
A get_option() 0 3 1
A update_option() 0 4 1
A update_options() 0 4 1
A delete_option() 0 4 1
A update_user_token() 0 4 1
B glob_php() 0 29 7
C activate_new_modules() 6 59 11
C get_available_modules() 0 60 13
B get_default_modules() 0 31 6
B handle_deprecated_modules() 0 27 8
B filter_default_modules() 0 24 6
A get_module_slug() 0 3 1
A get_module_path() 0 11 1
D get_module() 12 89 11
B get_file_data() 0 33 7
A translate_module_tag() 0 3 1
A get_translated_modules() 0 13 4
B get_active_modules() 0 32 7
A is_module_active() 0 3 1
A is_module() 0 3 2
A catch_errors() 0 13 2
A catch_errors_on_shutdown() 0 3 1
A alias_directories() 0 8 1
F activate_default_modules() 21 166 36
D activate_module() 0 93 17
A activate_module_actions() 0 3 1
A deactivate_module() 0 17 1
A enable_module_configurable() 0 4 1
A module_configuration_url() 0 14 1
B bail_on_activation() 0 40 5
A plugin_activation() 0 20 3
C get_activation_source() 0 49 14
A do_version_bump() 0 10 2
A set_update_modal_display() 0 3 1
A plugin_initialize() 6 17 3
A plugin_deactivation() 0 11 2
B disconnect() 0 45 6
A unlink_user() 0 4 1
B try_registration() 0 31 7
A log() 0 40 3
B get_log() 0 36 11
A log_settings_change() 0 7 2
A get_stat_data() 0 14 3
A get_additional_stat_data() 0 11 2
A get_site_user_count() 0 15 4
B admin_init() 0 44 11
A admin_body_class() 0 8 2
A add_jetpack_pagestyles() 0 3 1
B throw_error_on_activate_plugin() 0 24 7
A intercept_plugin_error_scrape_init() 0 3 1
A intercept_plugin_error_scrape() 0 11 4
B add_remote_request_handlers() 0 29 7
B remote_request_handlers() 0 40 7
F upload_handler() 0 131 24
A admin_help() 0 43 2
A admin_menu_css() 0 3 1
A admin_menu_order() 0 3 1
A jetpack_menu_order() 0 15 4
A admin_banner_styles() 8 21 4
A plugin_action_links() 0 15 4
B deactivate_dialog() 0 55 4
A deactivate_dialog_content() 0 5 1
A login_url() 0 7 2
A login_init() 0 17 2
F admin_page_load() 16 273 53
A build_authorize_url() 0 28 3
B filter_connect_request_body() 0 30 6
A filter_connect_processing_url() 0 6 1
A filter_connect_redirect_url() 0 12 3
A authorize_starting() 0 24 2
A authorize_ending_linked() 0 4 1
A authorize_ending_authorized() 0 20 3
A reconnection_completed() 0 3 1
A get_assumed_site_creation_date() 0 4 1
A apply_activation_source_to_args() 11 11 3
A build_reconnect_url() 0 4 2
A admin_url() 0 5 1
A nonce_url_no_esc() 0 4 1
A dismiss_jetpack_notice() 0 17 5
A sort_modules() 0 7 3
A ajax_recheck_ssl() 0 10 1
A api_url() 0 5 1
A fix_url_for_bad_hosts() 0 4 1
C verify_onboarding_token() 0 45 15
A create_onboarding_token() 0 8 2
A invalidate_onboarding_token() 0 3 1
A validate_onboarding_token_action() 0 18 3
B permit_ssl() 0 29 7
A alert_auto_ssl_fail() 0 54 2
A xmlrpc_api_url() 0 4 1
A connection() 0 10 2
A generate_secrets() 0 3 1
A get_secrets() 0 13 3
A delete_secrets() 0 3 1
A get_remote_query_timeout_limit() 0 4 1
A get_max_execution_time() 0 9 2
A set_min_time_limit() 8 8 2
A validate_remote_register_response() 0 3 1
A register() 0 17 3
A filter_register_request_body() 12 12 1
A filter_token_request_body() 12 12 1
A maybe_set_version_option() 0 14 3
A load_xml_rpc_client() 0 3 1
A reset_saved_auth_state() 0 4 1
A verify_xml_rpc_signature() 0 4 1
A internal_verify_xml_rpc_signature() 0 3 1
A authenticate_jetpack() 9 9 2
A wp_rest_authenticate() 0 4 1
A wp_rest_authentication_errors() 0 4 1
A xmlrpc_methods() 9 9 2
A public_xmlrpc_methods() 9 9 2
A jetpack_getOptions() 9 9 2
A xmlrpc_options() 9 9 2
F state() 0 56 20
A restate() 0 3 1
A should_set_cookie() 0 10 4
B check_privacy() 0 34 6
C xmlrpc_async_call() 0 42 12
A staticize_subdomain() 0 4 1
A login_form_json_api_authorization() 0 9 1
A post_login_form_to_signed_url() 0 14 5
A preserve_action_in_login_form_for_json_api_authorization() 0 4 1
A store_json_api_authorization_token() 0 6 1
A allow_wpcom_public_api_domain() 0 4 1
A is_redirect_encoded() 0 3 1
A allow_wpcom_environments() 0 7 1
A add_token_to_login_redirect_json_api_authorization() 0 12 1
F verify_json_api_authorization_request() 0 121 23
A login_message_json_api_authorization() 0 6 1
A get_content_width() 0 13 3
A get_cloud_site_options() 0 15 2
A check_identity_crisis() 0 7 4
A is_staging_site() 0 4 1
C validate_sync_error_idc_option() 0 42 15
A normalize_url_protocol_agnostic() 3 10 4
A get_sync_error_idc_option() 0 32 5
A sync_idc_optin() 0 18 3
B maybe_min_asset() 0 42 8
A set_suffix_on_min() 0 16 5
C maybe_inline_style() 0 50 13
A load_view() 0 11 2
B deprecated_hooks() 0 257 5
B absolutize_css_urls() 0 44 9
B implode_frontend_css() 0 57 10
A concat_remove_style_loader_tag() 0 10 4
A script_add_async() 0 3 1
B jetpack_check_heartbeat_data() 0 53 10
A get_jetpack_options_for_reset() 0 3 1
A build_raw_urls() 0 5 1
A dns_prefetch() 0 6 2
A wp_dashboard_setup() 0 38 5
A get_user_option_meta_box_order_dashboard() 0 25 5
A dashboard_widget() 0 8 1
B dashboard_widget_footer() 0 68 7
A jetpack_icon_user_connected() 0 4 1
A jetpack_show_user_connected_icon() 0 13 3
A jetpack_user_col_style() 0 19 3
B is_akismet_active() 0 35 9
A is_function_in_backtrace() 0 3 1
A get_file_url_for_environment() 0 3 1
A is_rewind_enabled() 0 19 6
A get_calypso_env() 0 15 5
A get_calypso_host() 0 13 4
A handle_post_authorization_actions() 0 24 4
A show_backups_ui() 0 10 2
A prepare_manage_jetpack_notice() 0 3 1
A manage_activate_screen() 0 3 1
A admin_jetpack_manage_notice() 0 3 1
A opt_out_jetpack_manage_url() 0 3 1
A opt_in_jetpack_manage_url() 0 3 1
A opt_in_jetpack_manage_notice() 0 3 1
A can_display_jetpack_manage_notice() 0 3 1
A user_meta_cleanup() 0 15 3
A is_active_and_not_development_mode() 0 7 3
A is_active_and_not_offline_mode() 0 6 3
B get_products_for_purchase() 0 94 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack, and based on these observations, apply Extract Interface, too.

1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
8
use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
9
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
10
use Automattic\Jetpack\Connection\Webhooks as Connection_Webhooks;
11
use Automattic\Jetpack\Constants;
12
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
13
use Automattic\Jetpack\Licensing;
14
use Automattic\Jetpack\Partner;
15
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
16
use Automattic\Jetpack\Redirect;
17
use Automattic\Jetpack\Roles;
18
use Automattic\Jetpack\Status;
19
use Automattic\Jetpack\Sync\Functions;
20
use Automattic\Jetpack\Sync\Health;
21
use Automattic\Jetpack\Sync\Sender;
22
use Automattic\Jetpack\Sync\Users;
23
use Automattic\Jetpack\Terms_Of_Service;
24
use Automattic\Jetpack\Tracking;
25
26
/*
27
Options:
28
jetpack_options (array)
29
	An array of options.
30
	@see Jetpack_Options::get_option_names()
31
32
jetpack_register (string)
33
	Temporary verification secrets.
34
35
jetpack_activated (int)
36
	1: the plugin was activated normally
37
	2: the plugin was activated on this site because of a network-wide activation
38
	3: the plugin was auto-installed
39
	4: the plugin was manually disconnected (but is still installed)
40
41
jetpack_active_modules (array)
42
	Array of active module slugs.
43
44
jetpack_do_activate (bool)
45
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
46
*/
47
48
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
49
50
class Jetpack {
51
	public $xmlrpc_server = null;
52
53
	/**
54
	 * @var array The handles of styles that are concatenated into jetpack.css.
55
	 *
56
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
57
	 */
58
	public $concatenated_style_handles = array(
59
		'jetpack-carousel',
60
		'grunion.css',
61
		'the-neverending-homepage',
62
		'jetpack_likes',
63
		'jetpack_related-posts',
64
		'sharedaddy',
65
		'jetpack-slideshow',
66
		'presentations',
67
		'quiz',
68
		'jetpack-subscriptions',
69
		'jetpack-responsive-videos-style',
70
		'jetpack-social-menu',
71
		'tiled-gallery',
72
		'jetpack_display_posts_widget',
73
		'gravatar-profile-widget',
74
		'goodreads-widget',
75
		'jetpack_social_media_icons_widget',
76
		'jetpack-top-posts-widget',
77
		'jetpack_image_widget',
78
		'jetpack-my-community-widget',
79
		'jetpack-authors-widget',
80
		'wordads',
81
		'eu-cookie-law-style',
82
		'flickr-widget-style',
83
		'jetpack-search-widget',
84
		'jetpack-simple-payments-widget-style',
85
		'jetpack-widget-social-icons-styles',
86
		'wpcom_instagram_widget',
87
	);
88
89
	/**
90
	 * Contains all assets that have had their URL rewritten to minified versions.
91
	 *
92
	 * @var array
93
	 */
94
	static $min_assets = array();
95
96
	public $plugins_to_deactivate = array(
97
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
98
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
99
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
100
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
101
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
102
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
103
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
104
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
105
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
106
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
107
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
108
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
109
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
110
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
111
	);
112
113
	/**
114
	 * Map of roles we care about, and their corresponding minimum capabilities.
115
	 *
116
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
117
	 *
118
	 * @access public
119
	 * @static
120
	 *
121
	 * @var array
122
	 */
123
	public static $capability_translations = array(
124
		'administrator' => 'manage_options',
125
		'editor'        => 'edit_others_posts',
126
		'author'        => 'publish_posts',
127
		'contributor'   => 'edit_posts',
128
		'subscriber'    => 'read',
129
	);
130
131
	/**
132
	 * Map of modules that have conflicts with plugins and should not be auto-activated
133
	 * if the plugins are active.  Used by filter_default_modules
134
	 *
135
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
136
	 * change `module-slug` and add this to your plugin:
137
	 *
138
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
139
	 * function my_jetpack_get_default_modules( $modules ) {
140
	 *     return array_diff( $modules, array( 'module-slug' ) );
141
	 * }
142
	 *
143
	 * @var array
144
	 */
145
	private $conflicting_plugins = array(
146
		'comments'           => array(
147
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
148
			'Disqus'                         => 'disqus-comment-system/disqus.php',
149
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
150
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
151
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
152
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
153
		),
154
		'comment-likes'      => array(
155
			'Epoch' => 'epoch/plugincore.php',
156
		),
157
		'contact-form'       => array(
158
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
159
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
160
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
161
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
162
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
163
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
164
		),
165
		'latex'              => array(
166
			'LaTeX for WordPress'     => 'latex/latex.php',
167
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
168
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
169
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
170
			'Enable Latex'            => 'enable-latex/enable-latex.php',
171
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
172
		),
173
		'protect'            => array(
174
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
175
			'Captcha'                           => 'captcha/captcha.php',
176
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
177
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
178
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
179
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
180
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
181
			'Security-protection'               => 'security-protection/security-protection.php',
182
			'Login Security'                    => 'login-security/login-security.php',
183
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
184
			'Wordfence Security'                => 'wordfence/wordfence.php',
185
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
186
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
187
		),
188
		'random-redirect'    => array(
189
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
190
		),
191
		'related-posts'      => array(
192
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
193
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
194
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
195
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
196
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
197
			'outbrain'                    => 'outbrain/outbrain.php',
198
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
199
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
200
		),
201
		'sharedaddy'         => array(
202
			'AddThis'     => 'addthis/addthis_social_widget.php',
203
			'Add To Any'  => 'add-to-any/add-to-any.php',
204
			'ShareThis'   => 'share-this/sharethis.php',
205
			'Shareaholic' => 'shareaholic/shareaholic.php',
206
		),
207
		'seo-tools'          => array(
208
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
209
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
210
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
211
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
212
			'The SEO Framework'              => 'autodescription/autodescription.php',
213
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
214
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
215
		),
216
		'verification-tools' => array(
217
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
218
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
219
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
220
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
221
			'The SEO Framework'              => 'autodescription/autodescription.php',
222
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
223
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
224
		),
225
		'widget-visibility'  => array(
226
			'Widget Logic'    => 'widget-logic/widget_logic.php',
227
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
228
		),
229
		'sitemaps'           => array(
230
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
231
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
232
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
233
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
234
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
235
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
236
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
237
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
238
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
239
			'The SEO Framework'                    => 'autodescription/autodescription.php',
240
			'Sitemap'                              => 'sitemap/sitemap.php',
241
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
242
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
243
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
244
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
245
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
246
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
247
		),
248
		'lazy-images'        => array(
249
			'Lazy Load'              => 'lazy-load/lazy-load.php',
250
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
251
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
252
		),
253
	);
254
255
	/**
256
	 * Plugins for which we turn off our Facebook OG Tags implementation.
257
	 *
258
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
259
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
260
	 *
261
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
262
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
263
	 */
264
	private $open_graph_conflicting_plugins = array(
265
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
266
		// 2 Click Social Media Buttons
267
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
268
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
269
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
270
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
271
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
272
		// Open Graph Meta Tags by Heateor
273
		'facebook/facebook.php',                                 // Facebook (official plugin)
274
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
275
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
276
		// Facebook Featured Image & OG Meta Tags
277
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
278
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
279
		// Facebook Open Graph Meta Tags for WordPress
280
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
281
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
282
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
283
		// Fedmich's Facebook Open Graph Meta
284
		'network-publisher/networkpub.php',                      // Network Publisher
285
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
286
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
287
		// NextScripts SNAP
288
		'og-tags/og-tags.php',                                   // OG Tags
289
		'opengraph/opengraph.php',                               // Open Graph
290
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
291
		// Open Graph Protocol Framework
292
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
293
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
294
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
295
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
296
		'sharepress/sharepress.php',                             // SharePress
297
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
298
		'social-discussions/social-discussions.php',             // Social Discussions
299
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
300
		'socialize/socialize.php',                               // Socialize
301
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
302
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
303
		// 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',
308
		// WP Facebook Like Send & Open Graph Meta
309
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
310
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
311
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
312
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
313
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
314
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
315
		'slim-seo/slim-seo.php',                                 // Slim SEO
316
	);
317
318
	/**
319
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
320
	 */
321
	private $twitter_cards_conflicting_plugins = array(
322
		// 'twitter/twitter.php',                       // The official one handles this on its own.
323
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
324
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
325
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
326
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
327
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
328
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
329
		'twitter-cards/twitter-cards.php',           // Twitter Cards
330
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
331
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
332
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
333
		'seo-by-rank-math/rank-math.php',            // Rank Math.
334
		'slim-seo/slim-seo.php',                     // Slim SEO
335
	);
336
337
	/**
338
	 * Message to display in admin_notice
339
	 *
340
	 * @var string
341
	 */
342
	public $message = '';
343
344
	/**
345
	 * Error to display in admin_notice
346
	 *
347
	 * @var string
348
	 */
349
	public $error = '';
350
351
	/**
352
	 * Modules that need more privacy description.
353
	 *
354
	 * @var string
355
	 */
356
	public $privacy_checks = '';
357
358
	/**
359
	 * Stats to record once the page loads
360
	 *
361
	 * @var array
362
	 */
363
	public $stats = array();
364
365
	/**
366
	 * Jetpack_Sync object
367
	 */
368
	public $sync;
369
370
	/**
371
	 * Verified data for JSON authorization request
372
	 */
373
	public $json_api_authorization_request = array();
374
375
	/**
376
	 * @var Automattic\Jetpack\Connection\Manager
377
	 */
378
	protected $connection_manager;
379
380
	/**
381
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
382
	 */
383
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
384
385
	/**
386
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
387
	 *
388
	 * @var Automattic\Jetpack\A8c_Mc_Stats
389
	 */
390
	public $a8c_mc_stats_instance;
391
392
	/**
393
	 * Constant for login redirect key.
394
	 *
395
	 * @var string
396
	 * @since 8.4.0
397
	 */
398
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
399
400
	/**
401
	 * Holds the singleton instance of this class
402
	 *
403
	 * @since 2.3.3
404
	 * @var Jetpack
405
	 */
406
	static $instance = false;
407
408
	/**
409
	 * Singleton
410
	 *
411
	 * @static
412
	 */
413
	public static function init() {
414
		if ( ! self::$instance ) {
415
			self::$instance = new Jetpack();
416
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
417
		}
418
419
		return self::$instance;
420
	}
421
422
	/**
423
	 * Must never be called statically
424
	 */
425
	function plugin_upgrade() {
426
		if ( self::is_active() ) {
427
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
428
			if ( JETPACK__VERSION != $version ) {
429
				// Prevent multiple upgrades at once - only a single process should trigger
430
				// an upgrade to avoid stampedes
431
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
432
					return;
433
				}
434
435
				// Set a short lock to prevent multiple instances of the upgrade
436
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
437
438
				// check which active modules actually exist and remove others from active_modules list
439
				$unfiltered_modules = self::get_active_modules();
440
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
441
				if ( array_diff( $unfiltered_modules, $modules ) ) {
442
					self::update_active_modules( $modules );
443
				}
444
445
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
446
447
				// Upgrade to 4.3.0
448
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
449
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
450
				}
451
452
				// Make sure Markdown for posts gets turned back on
453
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
454
					update_option( 'wpcom_publish_posts_with_markdown', true );
455
				}
456
457
				/*
458
				 * Minileven deprecation. 8.3.0.
459
				 * Only delete options if not using
460
				 * the replacement standalone Minileven plugin.
461
				 */
462
				if (
463
					! self::is_plugin_active( 'minileven-master/minileven.php' )
464
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
465
				) {
466
					if ( get_option( 'wp_mobile_custom_css' ) ) {
467
						delete_option( 'wp_mobile_custom_css' );
468
					}
469
					if ( get_option( 'wp_mobile_excerpt' ) ) {
470
						delete_option( 'wp_mobile_excerpt' );
471
					}
472
					if ( get_option( 'wp_mobile_featured_images' ) ) {
473
						delete_option( 'wp_mobile_featured_images' );
474
					}
475
					if ( get_option( 'wp_mobile_app_promos' ) ) {
476
						delete_option( 'wp_mobile_app_promos' );
477
					}
478
				}
479
480
				// Upgrade to 8.4.0.
481
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
482
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
483
				}
484
485
				// Update to 8.8.x (WordPress 5.5 Compatibility).
486
				if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
487
					$updated = update_site_option(
488
						'auto_update_plugins',
489
						array_unique(
490
							array_merge(
491
								(array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
492
								(array) get_site_option( 'auto_update_plugins', array() )
493
							)
494
						)
495
					);
496
497
					if ( $updated ) {
498
						Jetpack_Options::delete_option( 'autoupdate_plugins' );
499
					} // Should we have some type of fallback if something fails here?
500
				}
501
502
				if ( did_action( 'wp_loaded' ) ) {
503
					self::upgrade_on_load();
504
				} else {
505
					add_action(
506
						'wp_loaded',
507
						array( __CLASS__, 'upgrade_on_load' )
508
					);
509
				}
510
			}
511
		}
512
	}
513
514
	/**
515
	 * Runs upgrade routines that need to have modules loaded.
516
	 */
517
	static function upgrade_on_load() {
518
519
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
520
		// This can happen in case Jetpack has been just upgraded and is
521
		// being initialized late during the page load. In this case we wait
522
		// until the next proper admin page load with Jetpack active.
523
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
524
			delete_transient( self::$plugin_upgrade_lock_key );
525
526
			return;
527
		}
528
529
		self::maybe_set_version_option();
530
531
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
532
			Jetpack_Widget_Conditions::migrate_post_type_rules();
533
		}
534
535
		if (
536
			class_exists( 'Jetpack_Sitemap_Manager' )
537
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
538
		) {
539
			do_action( 'jetpack_sitemaps_purge_data' );
540
		}
541
542
		// Delete old stats cache
543
		delete_option( 'jetpack_restapi_stats_cache' );
544
545
		delete_transient( self::$plugin_upgrade_lock_key );
546
	}
547
548
	/**
549
	 * Saves all the currently active modules to options.
550
	 * Also fires Action hooks for each newly activated and deactivated module.
551
	 *
552
	 * @param $modules Array Array of active modules to be saved in options.
553
	 *
554
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
Documentation introduced by
The doc-type $success could not be parsed: Unknown type name "$success" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
555
	 */
556
	static function update_active_modules( $modules ) {
557
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
558
		$active_modules       = self::get_active_modules();
559
		$new_active_modules   = array_diff( $modules, $current_modules );
560
		$new_inactive_modules = array_diff( $active_modules, $modules );
561
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
562
		$reindexed_modules    = array_values( $new_current_modules );
563
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
564
565
		foreach ( $new_active_modules as $module ) {
566
			/**
567
			 * Fires when a specific module is activated.
568
			 *
569
			 * @since 1.9.0
570
			 *
571
			 * @param string $module Module slug.
572
			 * @param boolean $success whether the module was activated. @since 4.2
573
			 */
574
			do_action( 'jetpack_activate_module', $module, $success );
575
			/**
576
			 * Fires when a module is activated.
577
			 * The dynamic part of the filter, $module, is the module slug.
578
			 *
579
			 * @since 1.9.0
580
			 *
581
			 * @param string $module Module slug.
582
			 */
583
			do_action( "jetpack_activate_module_$module", $module );
584
		}
585
586
		foreach ( $new_inactive_modules as $module ) {
587
			/**
588
			 * Fired after a module has been deactivated.
589
			 *
590
			 * @since 4.2.0
591
			 *
592
			 * @param string $module Module slug.
593
			 * @param boolean $success whether the module was deactivated.
594
			 */
595
			do_action( 'jetpack_deactivate_module', $module, $success );
596
			/**
597
			 * Fires when a module is deactivated.
598
			 * The dynamic part of the filter, $module, is the module slug.
599
			 *
600
			 * @since 1.9.0
601
			 *
602
			 * @param string $module Module slug.
603
			 */
604
			do_action( "jetpack_deactivate_module_$module", $module );
605
		}
606
607
		return $success;
608
	}
609
610
	static function delete_active_modules() {
611
		self::update_active_modules( array() );
612
	}
613
614
	/**
615
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
616
	 * available.
617
	 */
618
	public function add_configure_hook() {
619
		global $wp_filter;
620
621
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
622
		if ( false !== $current_priority ) {
623
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
624
		}
625
626
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
627
		sort( $taken_priorities );
628
629
		$first_priority = array_shift( $taken_priorities );
630
631
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
632
			$new_priority = - PHP_INT_MAX;
633
		} else {
634
			$new_priority = $first_priority - 1;
635
		}
636
637
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
638
	}
639
640
	/**
641
	 * Constructor.  Initializes WordPress hooks
642
	 */
643
	private function __construct() {
644
		/*
645
		 * Check for and alert any deprecated hooks
646
		 */
647
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
648
649
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
650
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
651
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
652
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
653
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
654
655
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
656
657
		add_filter(
658
			'jetpack_signature_check_token',
659
			array( __CLASS__, 'verify_onboarding_token' ),
660
			10,
661
			3
662
		);
663
664
		/**
665
		 * Prepare Gutenberg Editor functionality
666
		 */
667
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
668
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
669
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
670
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
671
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
672
673
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
674
675
		// Unlink user before deleting the user from WP.com.
676
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
677
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
678
679
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
680
681
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
682
		add_action( 'login_init', array( $this, 'login_init' ) );
683
684
		// Set up the REST authentication hooks.
685
		Connection_Rest_Authentication::init();
686
687
		add_action( 'admin_init', array( $this, 'admin_init' ) );
688
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
689
690
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
691
692
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
693
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
694
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
695
696
		// returns HTTPS support status
697
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
698
699
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
700
701
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
702
703
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
704
705
		/**
706
		 * These actions run checks to load additional files.
707
		 * They check for external files or plugins, so they need to run as late as possible.
708
		 */
709
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
710
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
711
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
712
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
713
714
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
715
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
716
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
717
718
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
719
720
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
721
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
722
723
		// A filter to control all just in time messages
724
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
725
726
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
727
728
		/*
729
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
730
		 * We should make sure to only do this for front end links.
731
		 */
732
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
733
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
734
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
735
736
			/*
737
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
738
			 * so they point moderation links on emails to Calypso.
739
			 */
740
			jetpack_require_lib( 'functions.wp-notify' );
741
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
742
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
743
		}
744
745
		add_action(
746
			'plugins_loaded',
747
			function () {
748
				if ( User_Agent_Info::is_mobile_app() ) {
749
					add_filter( 'get_edit_post_link', '__return_empty_string' );
750
				}
751
			}
752
		);
753
754
		// Update the site's Jetpack plan and products from API on heartbeats.
755
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
756
757
		/**
758
		 * This is the hack to concatenate all css files into one.
759
		 * For description and reasoning see the implode_frontend_css method.
760
		 *
761
		 * Super late priority so we catch all the registered styles.
762
		 */
763
		if ( ! is_admin() ) {
764
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
765
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
766
		}
767
768
		/**
769
		 * These are sync actions that we need to keep track of for jitms
770
		 */
771
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
772
773
		// Actually push the stats on shutdown.
774
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
775
			add_action( 'shutdown', array( $this, 'push_stats' ) );
776
		}
777
778
		// Actions for Manager::authorize().
779
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
780
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
781
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
782
783
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
784
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
785
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
786
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
787
788
		// Filters for the Manager::get_token() urls and request body.
789
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
790
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
791
792
		// Actions for successful reconnect.
793
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
794
795
		// Actions for licensing.
796
		Licensing::instance()->initialize();
797
798
		// Make resources use static domain when possible.
799
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
800
	}
801
802
	/**
803
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
804
	 * Config object.
805
	 */
806
	public function configure() {
807
		$config = new Config();
808
809
		foreach (
810
			array(
811
				'sync',
812
			)
813
			as $feature
814
		) {
815
			$config->ensure( $feature );
816
		}
817
818
		$config->ensure(
819
			'connection',
820
			array(
821
				'slug' => 'jetpack',
822
				'name' => 'Jetpack',
823
			)
824
		);
825
826
		if ( is_admin() ) {
827
			$config->ensure( 'jitm' );
828
		}
829
830
		if ( ! $this->connection_manager ) {
831
			$this->connection_manager = new Connection_Manager( 'jetpack' );
832
833
			/**
834
			 * Filter to activate Jetpack Connection UI.
835
			 * INTERNAL USE ONLY.
836
			 *
837
			 * @since 9.5.0
838
			 *
839
			 * @param bool false Whether to activate the Connection UI.
840
			 */
841
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
842
				Automattic\Jetpack\ConnectionUI\Admin::init();
843
			}
844
		}
845
846
		/*
847
		 * Load things that should only be in Network Admin.
848
		 *
849
		 * For now blow away everything else until a more full
850
		 * understanding of what is needed at the network level is
851
		 * available
852
		 */
853
		if ( is_multisite() ) {
854
			$network = Jetpack_Network::init();
855
			$network->set_connection( $this->connection_manager );
856
		}
857
858
		if ( $this->connection_manager->is_active() ) {
859
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
860
861
			Jetpack_Heartbeat::init();
862
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
863
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
864
				Jetpack_Search_Performance_Logger::init();
865
			}
866
		}
867
868
		// Initialize remote file upload request handlers.
869
		$this->add_remote_request_handlers();
870
871
		/*
872
		 * Enable enhanced handling of previewing sites in Calypso
873
		 */
874
		if ( self::is_active() ) {
875
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
876
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
877
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
878
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
879
		}
880
881
		if ( ( new Tracking( $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
0 ignored issues
show
Documentation introduced by
$this->connection_manager is of type object<Automattic\Jetpack\Connection\Manager>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
new \Automattic\Jetpack\Terms_Of_Service() is of type object<Automattic\Jetpack\Terms_Of_Service>, but the function expects a object<Automattic\Jetpac...tpack\Terms_Of_Service>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
new \Automattic\Jetpack\Status() is of type object<Automattic\Jetpack\Status>, but the function expects a object<Automattic\Jetpac...omattic\Jetpack\Status>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
882
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
883
		} else {
884
			/**
885
			 * Initialize tracking right after the user agrees to the terms of service.
886
			 */
887
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
888
		}
889
	}
890
891
	/**
892
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
893
	 * initialization code.
894
	 *
895
	 * @action plugins_loaded
896
	 */
897
	public function late_initialization() {
898
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
899
900
		Partner::init();
901
902
		/**
903
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
904
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
905
		 *
906
		 * @since 8.1.0
907
		 *
908
		 * @param Jetpack $jetpack the main plugin class object.
909
		 */
910
		do_action( 'jetpack_loaded', $this );
911
912
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
913
	}
914
915
	/**
916
	 * Sets up the XMLRPC request handlers.
917
	 *
918
	 * @deprecated since 7.7.0
919
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
920
	 *
921
	 * @param array                 $request_params Incoming request parameters.
922
	 * @param Boolean               $is_active      Whether the connection is currently active.
923
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
924
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
925
	 */
926 View Code Duplication
	public function setup_xmlrpc_handlers(
927
		$request_params,
928
		$is_active,
929
		$is_signed,
930
		Jetpack_XMLRPC_Server $xmlrpc_server = null
931
	) {
932
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
933
934
		if ( ! $this->connection_manager ) {
935
			$this->connection_manager = new Connection_Manager();
936
		}
937
938
		return $this->connection_manager->setup_xmlrpc_handlers(
939
			$request_params,
940
			$is_active,
941
			$is_signed,
942
			$xmlrpc_server
943
		);
944
	}
945
946
	/**
947
	 * Initialize REST API registration connector.
948
	 *
949
	 * @deprecated since 7.7.0
950
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
951
	 */
952 View Code Duplication
	public function initialize_rest_api_registration_connector() {
953
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
954
955
		if ( ! $this->connection_manager ) {
956
			$this->connection_manager = new Connection_Manager();
957
		}
958
959
		$this->connection_manager->initialize_rest_api_registration_connector();
960
	}
961
962
	/**
963
	 * This is ported over from the manage module, which has been deprecated and baked in here.
964
	 *
965
	 * @param $domains
966
	 */
967
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
968
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
969
	}
970
971
	/**
972
	 * Return $domains, with 'wordpress.com' appended.
973
	 * This is ported over from the manage module, which has been deprecated and baked in here.
974
	 *
975
	 * @param $domains
976
	 * @return array
977
	 */
978
	function allow_wpcom_domain( $domains ) {
979
		if ( empty( $domains ) ) {
980
			$domains = array();
981
		}
982
		$domains[] = 'wordpress.com';
983
		return array_unique( $domains );
984
	}
985
986
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
987
		$post = get_post( $post_id );
988
989
		if ( empty( $post ) ) {
990
			return $default_url;
991
		}
992
993
		$post_type = $post->post_type;
994
995
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
996
		// https://en.support.wordpress.com/custom-post-types/
997
		$allowed_post_types = array(
998
			'post',
999
			'page',
1000
			'jetpack-portfolio',
1001
			'jetpack-testimonial',
1002
		);
1003
1004
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1005
			return $default_url;
1006
		}
1007
1008
		return Redirect::get_url(
1009
			'calypso-edit-' . $post_type,
1010
			array(
1011
				'path' => $post_id,
1012
			)
1013
		);
1014
	}
1015
1016
	function point_edit_comment_links_to_calypso( $url ) {
1017
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1018
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1019
1020
		return Redirect::get_url(
1021
			'calypso-edit-comment',
1022
			array(
1023
				'path' => $query_args['amp;c'],
1024
			)
1025
		);
1026
1027
	}
1028
1029
	function jetpack_track_last_sync_callback( $params ) {
1030
		/**
1031
		 * Filter to turn off jitm caching
1032
		 *
1033
		 * @since 5.4.0
1034
		 *
1035
		 * @param bool false Whether to cache just in time messages
1036
		 */
1037
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1038
			return $params;
1039
		}
1040
1041
		if ( is_array( $params ) && isset( $params[0] ) ) {
1042
			$option = $params[0];
1043
			if ( 'active_plugins' === $option ) {
1044
				// use the cache if we can, but not terribly important if it gets evicted
1045
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1046
			}
1047
		}
1048
1049
		return $params;
1050
	}
1051
1052
	function jetpack_connection_banner_callback() {
1053
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1054
1055
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1056
		if (
1057
			isset( $_REQUEST['dismissBanner'] ) &&
1058
			! Jetpack_Connection_Banner::force_display()
1059
		) {
1060
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1061
			wp_send_json_success();
1062
		}
1063
1064
		wp_die();
1065
	}
1066
1067
	/**
1068
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1069
	 * Only used in our alternate XML-RPC endpoint, where we want to
1070
	 * ensure that Core and other plugins' methods are not exposed.
1071
	 *
1072
	 * @deprecated since 7.7.0
1073
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1074
	 *
1075
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1076
	 * @return array Filtered $methods
1077
	 */
1078 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1079
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1080
1081
		if ( ! $this->connection_manager ) {
1082
			$this->connection_manager = new Connection_Manager();
1083
		}
1084
1085
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1086
	}
1087
1088
	/**
1089
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1090
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1091
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1092
	 * which is accessible via a different URI. Most of the below is copied directly
1093
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1094
	 *
1095
	 * @deprecated since 7.7.0
1096
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1097
	 */
1098 View Code Duplication
	public function alternate_xmlrpc() {
1099
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1100
1101
		if ( ! $this->connection_manager ) {
1102
			$this->connection_manager = new Connection_Manager();
1103
		}
1104
1105
		$this->connection_manager->alternate_xmlrpc();
1106
	}
1107
1108
	/**
1109
	 * The callback for the JITM ajax requests.
1110
	 *
1111
	 * @deprecated since 7.9.0
1112
	 */
1113
	function jetpack_jitm_ajax_callback() {
1114
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1115
	}
1116
1117
	/**
1118
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1119
	 */
1120
	function push_stats() {
1121
		if ( ! empty( $this->stats ) ) {
1122
			$this->do_stats( 'server_side' );
1123
		}
1124
	}
1125
1126
	/**
1127
	 * Sets the Jetpack custom capabilities.
1128
	 *
1129
	 * @param string[] $caps    Array of the user's capabilities.
1130
	 * @param string   $cap     Capability name.
1131
	 * @param int      $user_id The user ID.
1132
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1133
	 */
1134
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1135
		$is_offline_mode = ( new Status() )->is_offline_mode();
1136
		switch ( $cap ) {
1137
			case 'jetpack_manage_modules':
1138
			case 'jetpack_activate_modules':
1139
			case 'jetpack_deactivate_modules':
1140
				$caps = array( 'manage_options' );
1141
				break;
1142
			case 'jetpack_configure_modules':
1143
				$caps = array( 'manage_options' );
1144
				break;
1145
			case 'jetpack_manage_autoupdates':
1146
				$caps = array(
1147
					'manage_options',
1148
					'update_plugins',
1149
				);
1150
				break;
1151
			case 'jetpack_network_admin_page':
1152
			case 'jetpack_network_settings_page':
1153
				$caps = array( 'manage_network_plugins' );
1154
				break;
1155
			case 'jetpack_network_sites_page':
1156
				$caps = array( 'manage_sites' );
1157
				break;
1158
			case 'jetpack_admin_page':
1159
				if ( $is_offline_mode ) {
1160
					$caps = array( 'manage_options' );
1161
					break;
1162
				} else {
1163
					$caps = array( 'read' );
1164
				}
1165
				break;
1166
		}
1167
		return $caps;
1168
	}
1169
1170
	/**
1171
	 * Require a Jetpack authentication.
1172
	 *
1173
	 * @deprecated since 7.7.0
1174
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1175
	 */
1176 View Code Duplication
	public function require_jetpack_authentication() {
1177
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1178
1179
		if ( ! $this->connection_manager ) {
1180
			$this->connection_manager = new Connection_Manager();
1181
		}
1182
1183
		$this->connection_manager->require_jetpack_authentication();
1184
	}
1185
1186
	/**
1187
	 * Register assets for use in various modules and the Jetpack admin page.
1188
	 *
1189
	 * @uses wp_script_is, wp_register_script, plugins_url
1190
	 * @action wp_loaded
1191
	 * @return null
1192
	 */
1193
	public function register_assets() {
1194 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1195
			wp_register_script(
1196
				'jetpack-gallery-settings',
1197
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1198
				array( 'media-views' ),
1199
				'20121225'
1200
			);
1201
		}
1202
1203
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1204
			wp_register_script(
1205
				'jetpack-twitter-timeline',
1206
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1207
				array( 'jquery' ),
1208
				'4.0.0',
1209
				true
1210
			);
1211
		}
1212
1213
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1214
			wp_register_script(
1215
				'jetpack-facebook-embed',
1216
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1217
				array(),
1218
				null,
1219
				true
1220
			);
1221
1222
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1223
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1224
			if ( ! is_numeric( $fb_app_id ) ) {
1225
				$fb_app_id = '';
1226
			}
1227
			wp_localize_script(
1228
				'jetpack-facebook-embed',
1229
				'jpfbembed',
1230
				array(
1231
					'appid'  => $fb_app_id,
1232
					'locale' => $this->get_locale(),
1233
				)
1234
			);
1235
		}
1236
1237
		/**
1238
		 * As jetpack_register_genericons is by default fired off a hook,
1239
		 * the hook may have already fired by this point.
1240
		 * So, let's just trigger it manually.
1241
		 */
1242
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1243
		jetpack_register_genericons();
1244
1245
		/**
1246
		 * Register the social logos
1247
		 */
1248
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1249
		jetpack_register_social_logos();
1250
1251 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1252
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1253
		}
1254
	}
1255
1256
	/**
1257
	 * Guess locale from language code.
1258
	 *
1259
	 * @param string $lang Language code.
1260
	 * @return string|bool
1261
	 */
1262 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1263
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1264
			return 'en_US';
1265
		}
1266
1267
		if ( ! class_exists( 'GP_Locales' ) ) {
1268
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1269
				return false;
1270
			}
1271
1272
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1273
		}
1274
1275
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1276
			// WP.com: get_locale() returns 'it'
1277
			$locale = GP_Locales::by_slug( $lang );
1278
		} else {
1279
			// Jetpack: get_locale() returns 'it_IT';
1280
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1281
		}
1282
1283
		if ( ! $locale ) {
1284
			return false;
1285
		}
1286
1287
		if ( empty( $locale->facebook_locale ) ) {
1288
			if ( empty( $locale->wp_locale ) ) {
1289
				return false;
1290
			} else {
1291
				// Facebook SDK is smart enough to fall back to en_US if a
1292
				// locale isn't supported. Since supported Facebook locales
1293
				// can fall out of sync, we'll attempt to use the known
1294
				// wp_locale value and rely on said fallback.
1295
				return $locale->wp_locale;
1296
			}
1297
		}
1298
1299
		return $locale->facebook_locale;
1300
	}
1301
1302
	/**
1303
	 * Get the locale.
1304
	 *
1305
	 * @return string|bool
1306
	 */
1307
	function get_locale() {
1308
		$locale = $this->guess_locale_from_lang( get_locale() );
1309
1310
		if ( ! $locale ) {
1311
			$locale = 'en_US';
1312
		}
1313
1314
		return $locale;
1315
	}
1316
1317
	/**
1318
	 * Return the network_site_url so that .com knows what network this site is a part of.
1319
	 *
1320
	 * @param  bool $option
1321
	 * @return string
1322
	 */
1323
	public function jetpack_main_network_site_option( $option ) {
1324
		return network_site_url();
1325
	}
1326
	/**
1327
	 * Network Name.
1328
	 */
1329
	static function network_name( $option = null ) {
1330
		global $current_site;
1331
		return $current_site->site_name;
1332
	}
1333
	/**
1334
	 * Does the network allow new user and site registrations.
1335
	 *
1336
	 * @return string
1337
	 */
1338
	static function network_allow_new_registrations( $option = null ) {
1339
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1340
	}
1341
	/**
1342
	 * Does the network allow admins to add new users.
1343
	 *
1344
	 * @return boolian
1345
	 */
1346
	static function network_add_new_users( $option = null ) {
1347
		return (bool) get_site_option( 'add_new_users' );
1348
	}
1349
	/**
1350
	 * File upload psace left per site in MB.
1351
	 *  -1 means NO LIMIT.
1352
	 *
1353
	 * @return number
1354
	 */
1355
	static function network_site_upload_space( $option = null ) {
1356
		// value in MB
1357
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1358
	}
1359
1360
	/**
1361
	 * Network allowed file types.
1362
	 *
1363
	 * @return string
1364
	 */
1365
	static function network_upload_file_types( $option = null ) {
1366
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1367
	}
1368
1369
	/**
1370
	 * Maximum file upload size set by the network.
1371
	 *
1372
	 * @return number
1373
	 */
1374
	static function network_max_upload_file_size( $option = null ) {
1375
		// value in KB
1376
		return get_site_option( 'fileupload_maxk', 300 );
1377
	}
1378
1379
	/**
1380
	 * Lets us know if a site allows admins to manage the network.
1381
	 *
1382
	 * @return array
1383
	 */
1384
	static function network_enable_administration_menus( $option = null ) {
1385
		return get_site_option( 'menu_items' );
1386
	}
1387
1388
	/**
1389
	 * If a user has been promoted to or demoted from admin, we need to clear the
1390
	 * jetpack_other_linked_admins transient.
1391
	 *
1392
	 * @since 4.3.2
1393
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1394
	 *
1395
	 * @param int    $user_id   The user ID whose role changed.
1396
	 * @param string $role      The new role.
1397
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1398
	 */
1399
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1400
		if ( 'administrator' == $role
1401
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1402
			|| is_null( $old_roles )
1403
		) {
1404
			delete_transient( 'jetpack_other_linked_admins' );
1405
		}
1406
	}
1407
1408
	/**
1409
	 * Checks to see if there are any other users available to become primary
1410
	 * Users must both:
1411
	 * - Be linked to wpcom
1412
	 * - Be an admin
1413
	 *
1414
	 * @return mixed False if no other users are linked, Int if there are.
1415
	 */
1416
	static function get_other_linked_admins() {
1417
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1418
1419
		if ( false === $other_linked_users ) {
1420
			$admins = get_users( array( 'role' => 'administrator' ) );
1421
			if ( count( $admins ) > 1 ) {
1422
				$available = array();
1423
				foreach ( $admins as $admin ) {
1424
					if ( self::is_user_connected( $admin->ID ) ) {
1425
						$available[] = $admin->ID;
1426
					}
1427
				}
1428
1429
				$count_connected_admins = count( $available );
1430
				if ( count( $available ) > 1 ) {
1431
					$other_linked_users = $count_connected_admins;
1432
				} else {
1433
					$other_linked_users = 0;
1434
				}
1435
			} else {
1436
				$other_linked_users = 0;
1437
			}
1438
1439
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1440
		}
1441
1442
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1443
	}
1444
1445
	/**
1446
	 * Return whether we are dealing with a multi network setup or not.
1447
	 * The reason we are type casting this is because we want to avoid the situation where
1448
	 * the result is false since when is_main_network_option return false it cases
1449
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1450
	 * database which could be set to anything as opposed to what this function returns.
1451
	 *
1452
	 * @param  bool $option
1453
	 *
1454
	 * @return boolean
1455
	 */
1456
	public function is_main_network_option( $option ) {
1457
		// return '1' or ''
1458
		return (string) (bool) self::is_multi_network();
1459
	}
1460
1461
	/**
1462
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1463
	 *
1464
	 * @param  string $option
1465
	 * @return boolean
1466
	 */
1467
	public function is_multisite( $option ) {
1468
		return (string) (bool) is_multisite();
1469
	}
1470
1471
	/**
1472
	 * Implemented since there is no core is multi network function
1473
	 * Right now there is no way to tell if we which network is the dominant network on the system
1474
	 *
1475
	 * @since  3.3
1476
	 * @return boolean
1477
	 */
1478 View Code Duplication
	public static function is_multi_network() {
1479
		global  $wpdb;
1480
1481
		// if we don't have a multi site setup no need to do any more
1482
		if ( ! is_multisite() ) {
1483
			return false;
1484
		}
1485
1486
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1487
		if ( $num_sites > 1 ) {
1488
			return true;
1489
		} else {
1490
			return false;
1491
		}
1492
	}
1493
1494
	/**
1495
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1496
	 *
1497
	 * @return null
1498
	 */
1499
	function update_jetpack_main_network_site_option() {
1500
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1501
	}
1502
	/**
1503
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1504
	 */
1505
	function update_jetpack_network_settings() {
1506
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1507
		// Only sync this info for the main network site.
1508
	}
1509
1510
	/**
1511
	 * Get back if the current site is single user site.
1512
	 *
1513
	 * @return bool
1514
	 */
1515 View Code Duplication
	public static function is_single_user_site() {
1516
		global $wpdb;
1517
1518
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1519
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1520
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1521
		}
1522
		return 1 === (int) $some_users;
1523
	}
1524
1525
	/**
1526
	 * Returns true if the site has file write access false otherwise.
1527
	 *
1528
	 * @return string ( '1' | '0' )
1529
	 **/
1530
	public static function file_system_write_access() {
1531
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1532
			require_once ABSPATH . 'wp-admin/includes/file.php';
1533
		}
1534
1535
		require_once ABSPATH . 'wp-admin/includes/template.php';
1536
1537
		$filesystem_method = get_filesystem_method();
1538
		if ( $filesystem_method === 'direct' ) {
1539
			return 1;
1540
		}
1541
1542
		ob_start();
1543
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1544
		ob_end_clean();
1545
		if ( $filesystem_credentials_are_stored ) {
1546
			return 1;
1547
		}
1548
		return 0;
1549
	}
1550
1551
	/**
1552
	 * Finds out if a site is using a version control system.
1553
	 *
1554
	 * @return string ( '1' | '0' )
1555
	 **/
1556
	public static function is_version_controlled() {
1557
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1558
		return (string) (int) Functions::is_version_controlled();
1559
	}
1560
1561
	/**
1562
	 * Determines whether the current theme supports featured images or not.
1563
	 *
1564
	 * @return string ( '1' | '0' )
1565
	 */
1566
	public static function featured_images_enabled() {
1567
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1568
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1569
	}
1570
1571
	/**
1572
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1573
	 *
1574
	 * @deprecated 4.7 use get_avatar_url instead.
1575
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1576
	 * @param int               $size Size of the avatar image
1577
	 * @param string            $default URL to a default image to use if no avatar is available
1578
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1579
	 *
1580
	 * @return array
1581
	 */
1582
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1583
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1584
		return get_avatar_url(
1585
			$id_or_email,
1586
			array(
1587
				'size'          => $size,
1588
				'default'       => $default,
1589
				'force_default' => $force_display,
1590
			)
1591
		);
1592
	}
1593
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1594
	/**
1595
	 * jetpack_updates is saved in the following schema:
1596
	 *
1597
	 * array (
1598
	 *      'plugins'                       => (int) Number of plugin updates available.
1599
	 *      'themes'                        => (int) Number of theme updates available.
1600
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1601
	 *      'translations'                  => (int) Number of translation updates available.
1602
	 *      'total'                         => (int) Total of all available updates.
1603
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1604
	 * )
1605
	 *
1606
	 * @return array
1607
	 */
1608
	public static function get_updates() {
1609
		$update_data = wp_get_update_data();
1610
1611
		// Stores the individual update counts as well as the total count.
1612
		if ( isset( $update_data['counts'] ) ) {
1613
			$updates = $update_data['counts'];
1614
		}
1615
1616
		// If we need to update WordPress core, let's find the latest version number.
1617 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1618
			$cur = get_preferred_from_update_core();
1619
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1620
				$updates['wp_update_version'] = $cur->current;
1621
			}
1622
		}
1623
		return isset( $updates ) ? $updates : array();
1624
	}
1625
	// phpcs:enable
1626
1627
	public static function get_update_details() {
1628
		$update_details = array(
1629
			'update_core'    => get_site_transient( 'update_core' ),
1630
			'update_plugins' => get_site_transient( 'update_plugins' ),
1631
			'update_themes'  => get_site_transient( 'update_themes' ),
1632
		);
1633
		return $update_details;
1634
	}
1635
1636
	public static function refresh_update_data() {
1637
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1638
1639
	}
1640
1641
	public static function refresh_theme_data() {
1642
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1643
	}
1644
1645
	/**
1646
	 * Is Jetpack active?
1647
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1648
	 *
1649
	 * @return bool
1650
	 */
1651
	public static function is_active() {
1652
		return self::connection()->is_active();
1653
	}
1654
1655
	/**
1656
	 * Make an API call to WordPress.com for plan status
1657
	 *
1658
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1659
	 *
1660
	 * @return bool True if plan is updated, false if no update
1661
	 */
1662
	public static function refresh_active_plan_from_wpcom() {
1663
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1664
		return Jetpack_Plan::refresh_from_wpcom();
1665
	}
1666
1667
	/**
1668
	 * Get the plan that this Jetpack site is currently using
1669
	 *
1670
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1671
	 * @return array Active Jetpack plan details.
1672
	 */
1673
	public static function get_active_plan() {
1674
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1675
		return Jetpack_Plan::get();
1676
	}
1677
1678
	/**
1679
	 * Determine whether the active plan supports a particular feature
1680
	 *
1681
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1682
	 * @return bool True if plan supports feature, false if not.
1683
	 */
1684
	public static function active_plan_supports( $feature ) {
1685
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1686
		return Jetpack_Plan::supports( $feature );
1687
	}
1688
1689
	/**
1690
	 * Deprecated: Is Jetpack in development (offline) mode?
1691
	 *
1692
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1693
	 * and themes still use it, and we do not want to flood them with notices.
1694
	 *
1695
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1696
	 *
1697
	 * @deprecated since 8.0.
1698
	 */
1699
	public static function is_development_mode() {
1700
		return ( new Status() )->is_offline_mode();
1701
	}
1702
1703
	/**
1704
	 * Whether the site is currently onboarding or not.
1705
	 * A site is considered as being onboarded if it currently has an onboarding token.
1706
	 *
1707
	 * @since 5.8
1708
	 *
1709
	 * @access public
1710
	 * @static
1711
	 *
1712
	 * @return bool True if the site is currently onboarding, false otherwise
1713
	 */
1714
	public static function is_onboarding() {
1715
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1716
	}
1717
1718
	/**
1719
	 * Determines reason for Jetpack offline mode.
1720
	 */
1721
	public static function development_mode_trigger_text() {
1722
		$status = new Status();
1723
1724
		if ( ! $status->is_offline_mode() ) {
1725
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1726
		}
1727
1728
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1729
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1730
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1731
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1732
		} elseif ( $status->is_local_site() ) {
1733
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1734
			/** This filter is documented in packages/status/src/class-status.php */
1735
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1736
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1737
		} else {
1738
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1739
		}
1740
1741
		return $notice;
1742
1743
	}
1744
	/**
1745
	 * Get Jetpack offline mode notice text and notice class.
1746
	 *
1747
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1748
	 */
1749
	public static function show_development_mode_notice() {
1750 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1751
			$notice = sprintf(
1752
				/* translators: %s is a URL */
1753
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1754
				Redirect::get_url( 'jetpack-support-development-mode' )
1755
			);
1756
1757
			$notice .= ' ' . self::development_mode_trigger_text();
1758
1759
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1760
		}
1761
1762
		// Throw up a notice if using a development version and as for feedback.
1763
		if ( self::is_development_version() ) {
1764
			/* translators: %s is a URL */
1765
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), Redirect::get_url( 'jetpack-contact-support-beta-group' ) );
1766
1767
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1768
		}
1769
		// Throw up a notice if using staging mode
1770 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1771
			/* translators: %s is a URL */
1772
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1773
1774
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1775
		}
1776
	}
1777
1778
	/**
1779
	 * Whether Jetpack's version maps to a public release, or a development version.
1780
	 */
1781
	public static function is_development_version() {
1782
		/**
1783
		 * Allows filtering whether this is a development version of Jetpack.
1784
		 *
1785
		 * This filter is especially useful for tests.
1786
		 *
1787
		 * @since 4.3.0
1788
		 *
1789
		 * @param bool $development_version Is this a develoment version of Jetpack?
1790
		 */
1791
		return (bool) apply_filters(
1792
			'jetpack_development_version',
1793
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1794
		);
1795
	}
1796
1797
	/**
1798
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1799
	 */
1800
	public static function is_user_connected( $user_id = false ) {
1801
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1802
		return self::connection()->is_user_connected( $user_id );
0 ignored issues
show
Documentation introduced by
$user_id is of type boolean, but the function expects a false|integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1803
	}
1804
1805
	/**
1806
	 * Get the wpcom user data of the current|specified connected user.
1807
	 */
1808
	public static function get_connected_user_data( $user_id = null ) {
1809
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1810
		return self::connection()->get_connected_user_data( $user_id );
1811
	}
1812
1813
	/**
1814
	 * Get the wpcom email of the current|specified connected user.
1815
	 */
1816
	public static function get_connected_user_email( $user_id = null ) {
1817
		if ( ! $user_id ) {
1818
			$user_id = get_current_user_id();
1819
		}
1820
1821
		$xml = new Jetpack_IXR_Client(
1822
			array(
1823
				'user_id' => $user_id,
1824
			)
1825
		);
1826
		$xml->query( 'wpcom.getUserEmail' );
1827
		if ( ! $xml->isError() ) {
1828
			return $xml->getResponse();
1829
		}
1830
		return false;
1831
	}
1832
1833
	/**
1834
	 * Get the wpcom email of the master user.
1835
	 */
1836
	public static function get_master_user_email() {
1837
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1838
		if ( $master_user_id ) {
1839
			return self::get_connected_user_email( $master_user_id );
1840
		}
1841
		return '';
1842
	}
1843
1844
	/**
1845
	 * Whether the current user is the connection owner.
1846
	 *
1847
	 * @deprecated since 7.7
1848
	 *
1849
	 * @return bool Whether the current user is the connection owner.
1850
	 */
1851
	public function current_user_is_connection_owner() {
1852
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1853
		return self::connection()->is_connection_owner();
1854
	}
1855
1856
	/**
1857
	 * Gets current user IP address.
1858
	 *
1859
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1860
	 *
1861
	 * @return string                  Current user IP address.
1862
	 */
1863
	public static function current_user_ip( $check_all_headers = false ) {
1864
		if ( $check_all_headers ) {
1865
			foreach ( array(
1866
				'HTTP_CF_CONNECTING_IP',
1867
				'HTTP_CLIENT_IP',
1868
				'HTTP_X_FORWARDED_FOR',
1869
				'HTTP_X_FORWARDED',
1870
				'HTTP_X_CLUSTER_CLIENT_IP',
1871
				'HTTP_FORWARDED_FOR',
1872
				'HTTP_FORWARDED',
1873
				'HTTP_VIA',
1874
			) as $key ) {
1875
				if ( ! empty( $_SERVER[ $key ] ) ) {
1876
					return $_SERVER[ $key ];
1877
				}
1878
			}
1879
		}
1880
1881
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1882
	}
1883
1884
	/**
1885
	 * Synchronize connected user role changes
1886
	 */
1887
	function user_role_change( $user_id ) {
1888
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1889
		Users::user_role_change( $user_id );
1890
	}
1891
1892
	/**
1893
	 * Loads the currently active modules.
1894
	 */
1895
	public static function load_modules() {
1896
		$is_offline_mode = ( new Status() )->is_offline_mode();
1897
		if (
1898
			! self::is_active()
1899
			&& ! $is_offline_mode
1900
			&& ! self::is_onboarding()
1901
			&& (
1902
				! is_multisite()
1903
				|| ! get_site_option( 'jetpack_protect_active' )
1904
			)
1905
		) {
1906
			return;
1907
		}
1908
1909
		$version = Jetpack_Options::get_option( 'version' );
1910 View Code Duplication
		if ( ! $version ) {
1911
			$version = $old_version = JETPACK__VERSION . ':' . time();
1912
			/** This action is documented in class.jetpack.php */
1913
			do_action( 'updating_jetpack_version', $version, false );
1914
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1915
		}
1916
		list( $version ) = explode( ':', $version );
1917
1918
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1919
1920
		$modules_data = array();
1921
1922
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1923
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1924
			$updated_modules = array();
1925
			foreach ( $modules as $module ) {
1926
				$modules_data[ $module ] = self::get_module( $module );
1927
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1928
					continue;
1929
				}
1930
1931
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1932
					continue;
1933
				}
1934
1935
				$updated_modules[] = $module;
1936
			}
1937
1938
			$modules = array_diff( $modules, $updated_modules );
1939
		}
1940
1941
		foreach ( $modules as $index => $module ) {
1942
			// If we're in offline mode, disable modules requiring a connection.
1943
			if ( $is_offline_mode ) {
1944
				// Prime the pump if we need to
1945
				if ( empty( $modules_data[ $module ] ) ) {
1946
					$modules_data[ $module ] = self::get_module( $module );
1947
				}
1948
				// If the module requires a connection, but we're in local mode, don't include it.
1949
				if ( $modules_data[ $module ]['requires_connection'] ) {
1950
					continue;
1951
				}
1952
			}
1953
1954
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1955
				continue;
1956
			}
1957
1958
			if ( ! include_once self::get_module_path( $module ) ) {
1959
				unset( $modules[ $index ] );
1960
				self::update_active_modules( array_values( $modules ) );
1961
				continue;
1962
			}
1963
1964
			/**
1965
			 * Fires when a specific module is loaded.
1966
			 * The dynamic part of the hook, $module, is the module slug.
1967
			 *
1968
			 * @since 1.1.0
1969
			 */
1970
			do_action( 'jetpack_module_loaded_' . $module );
1971
		}
1972
1973
		/**
1974
		 * Fires when all the modules are loaded.
1975
		 *
1976
		 * @since 1.1.0
1977
		 */
1978
		do_action( 'jetpack_modules_loaded' );
1979
1980
		// 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.
1981
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1982
	}
1983
1984
	/**
1985
	 * Check if Jetpack's REST API compat file should be included
1986
	 *
1987
	 * @action plugins_loaded
1988
	 * @return null
1989
	 */
1990
	public function check_rest_api_compat() {
1991
		/**
1992
		 * Filters the list of REST API compat files to be included.
1993
		 *
1994
		 * @since 2.2.5
1995
		 *
1996
		 * @param array $args Array of REST API compat files to include.
1997
		 */
1998
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1999
2000
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2001
			require_once $_jetpack_rest_api_compat_include;
2002
		}
2003
	}
2004
2005
	/**
2006
	 * Gets all plugins currently active in values, regardless of whether they're
2007
	 * traditionally activated or network activated.
2008
	 *
2009
	 * @todo Store the result in core's object cache maybe?
2010
	 */
2011
	public static function get_active_plugins() {
2012
		$active_plugins = (array) get_option( 'active_plugins', array() );
2013
2014
		if ( is_multisite() ) {
2015
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2016
			// whereas active_plugins stores them in the values.
2017
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2018
			if ( $network_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $network_plugins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2019
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2020
			}
2021
		}
2022
2023
		sort( $active_plugins );
2024
2025
		return array_unique( $active_plugins );
2026
	}
2027
2028
	/**
2029
	 * Gets and parses additional plugin data to send with the heartbeat data
2030
	 *
2031
	 * @since 3.8.1
2032
	 *
2033
	 * @return array Array of plugin data
2034
	 */
2035
	public static function get_parsed_plugin_data() {
2036
		if ( ! function_exists( 'get_plugins' ) ) {
2037
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2038
		}
2039
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2040
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2041
		$active_plugins = self::get_active_plugins();
2042
2043
		$plugins = array();
2044
		foreach ( $all_plugins as $path => $plugin_data ) {
2045
			$plugins[ $path ] = array(
2046
				'is_active' => in_array( $path, $active_plugins ),
2047
				'file'      => $path,
2048
				'name'      => $plugin_data['Name'],
2049
				'version'   => $plugin_data['Version'],
2050
				'author'    => $plugin_data['Author'],
2051
			);
2052
		}
2053
2054
		return $plugins;
2055
	}
2056
2057
	/**
2058
	 * Gets and parses theme data to send with the heartbeat data
2059
	 *
2060
	 * @since 3.8.1
2061
	 *
2062
	 * @return array Array of theme data
2063
	 */
2064
	public static function get_parsed_theme_data() {
2065
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2066
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2067
2068
		$themes = array();
2069
		foreach ( $all_themes as $slug => $theme_data ) {
2070
			$theme_headers = array();
2071
			foreach ( $header_keys as $header_key ) {
2072
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2073
			}
2074
2075
			$themes[ $slug ] = array(
2076
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2077
				'slug'            => $slug,
2078
				'theme_root'      => $theme_data->get_theme_root_uri(),
2079
				'parent'          => $theme_data->parent(),
2080
				'headers'         => $theme_headers,
2081
			);
2082
		}
2083
2084
		return $themes;
2085
	}
2086
2087
	/**
2088
	 * Checks whether a specific plugin is active.
2089
	 *
2090
	 * We don't want to store these in a static variable, in case
2091
	 * there are switch_to_blog() calls involved.
2092
	 */
2093
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2094
		return in_array( $plugin, self::get_active_plugins() );
2095
	}
2096
2097
	/**
2098
	 * Check if Jetpack's Open Graph tags should be used.
2099
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2100
	 *
2101
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2102
	 * @action plugins_loaded
2103
	 * @return null
2104
	 */
2105
	public function check_open_graph() {
2106
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2107
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2108
		}
2109
2110
		$active_plugins = self::get_active_plugins();
2111
2112
		if ( ! empty( $active_plugins ) ) {
2113
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2114
				if ( in_array( $plugin, $active_plugins ) ) {
2115
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2116
					break;
2117
				}
2118
			}
2119
		}
2120
2121
		/**
2122
		 * Allow the addition of Open Graph Meta Tags to all pages.
2123
		 *
2124
		 * @since 2.0.3
2125
		 *
2126
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2127
		 */
2128
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2129
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2130
		}
2131
	}
2132
2133
	/**
2134
	 * Check if Jetpack's Twitter tags should be used.
2135
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2136
	 *
2137
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2138
	 * @action plugins_loaded
2139
	 * @return null
2140
	 */
2141
	public function check_twitter_tags() {
2142
2143
		$active_plugins = self::get_active_plugins();
2144
2145
		if ( ! empty( $active_plugins ) ) {
2146
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2147
				if ( in_array( $plugin, $active_plugins ) ) {
2148
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2149
					break;
2150
				}
2151
			}
2152
		}
2153
2154
		/**
2155
		 * Allow Twitter Card Meta tags to be disabled.
2156
		 *
2157
		 * @since 2.6.0
2158
		 *
2159
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2160
		 */
2161
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2162
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2163
		}
2164
	}
2165
2166
	/**
2167
	 * Allows plugins to submit security reports.
2168
	 *
2169
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2170
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2171
	 * @param array  $args         See definitions above
2172
	 */
2173
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2174
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2175
	}
2176
2177
	/* Jetpack Options API */
2178
2179
	public static function get_option_names( $type = 'compact' ) {
2180
		return Jetpack_Options::get_option_names( $type );
2181
	}
2182
2183
	/**
2184
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2185
	 *
2186
	 * @param string $name    Option name
2187
	 * @param mixed  $default (optional)
2188
	 */
2189
	public static function get_option( $name, $default = false ) {
2190
		return Jetpack_Options::get_option( $name, $default );
2191
	}
2192
2193
	/**
2194
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2195
	 *
2196
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2197
	 * @param string $name  Option name
2198
	 * @param mixed  $value Option value
2199
	 */
2200
	public static function update_option( $name, $value ) {
2201
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2202
		return Jetpack_Options::update_option( $name, $value );
2203
	}
2204
2205
	/**
2206
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2207
	 *
2208
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2209
	 * @param array $array array( option name => option value, ... )
2210
	 */
2211
	public static function update_options( $array ) {
2212
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2213
		return Jetpack_Options::update_options( $array );
2214
	}
2215
2216
	/**
2217
	 * Deletes the given option.  May be passed multiple option names as an array.
2218
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2219
	 *
2220
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2221
	 * @param string|array $names
2222
	 */
2223
	public static function delete_option( $names ) {
2224
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2225
		return Jetpack_Options::delete_option( $names );
2226
	}
2227
2228
	/**
2229
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2230
	 *
2231
	 * Enters a user token into the user_tokens option
2232
	 *
2233
	 * @param int    $user_id The user id.
2234
	 * @param string $token The user token.
2235
	 * @param bool   $is_master_user Whether the user is the master user.
2236
	 * @return bool
2237
	 */
2238
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2239
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2240
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2241
	}
2242
2243
	/**
2244
	 * Returns an array of all PHP files in the specified absolute path.
2245
	 * Equivalent to glob( "$absolute_path/*.php" ).
2246
	 *
2247
	 * @param string $absolute_path The absolute path of the directory to search.
2248
	 * @return array Array of absolute paths to the PHP files.
2249
	 */
2250
	public static function glob_php( $absolute_path ) {
2251
		if ( function_exists( 'glob' ) ) {
2252
			return glob( "$absolute_path/*.php" );
2253
		}
2254
2255
		$absolute_path = untrailingslashit( $absolute_path );
2256
		$files         = array();
2257
		if ( ! $dir = @opendir( $absolute_path ) ) {
2258
			return $files;
2259
		}
2260
2261
		while ( false !== $file = readdir( $dir ) ) {
2262
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2263
				continue;
2264
			}
2265
2266
			$file = "$absolute_path/$file";
2267
2268
			if ( ! is_file( $file ) ) {
2269
				continue;
2270
			}
2271
2272
			$files[] = $file;
2273
		}
2274
2275
		closedir( $dir );
2276
2277
		return $files;
2278
	}
2279
2280
	public static function activate_new_modules( $redirect = false ) {
2281
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2282
			return;
2283
		}
2284
2285
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2286 View Code Duplication
		if ( ! $jetpack_old_version ) {
2287
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2288
			/** This action is documented in class.jetpack.php */
2289
			do_action( 'updating_jetpack_version', $version, false );
2290
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2291
		}
2292
2293
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2294
2295
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2296
			return;
2297
		}
2298
2299
		$active_modules     = self::get_active_modules();
2300
		$reactivate_modules = array();
2301
		foreach ( $active_modules as $active_module ) {
2302
			$module = self::get_module( $active_module );
2303
			if ( ! isset( $module['changed'] ) ) {
2304
				continue;
2305
			}
2306
2307
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2308
				continue;
2309
			}
2310
2311
			$reactivate_modules[] = $active_module;
2312
			self::deactivate_module( $active_module );
2313
		}
2314
2315
		$new_version = JETPACK__VERSION . ':' . time();
2316
		/** This action is documented in class.jetpack.php */
2317
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2318
		Jetpack_Options::update_options(
2319
			array(
2320
				'version'     => $new_version,
2321
				'old_version' => $jetpack_old_version,
2322
			)
2323
		);
2324
2325
		self::state( 'message', 'modules_activated' );
2326
2327
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2328
2329
		if ( $redirect ) {
2330
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2331
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2332
				$page = $_GET['page'];
2333
			}
2334
2335
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2336
			exit;
2337
		}
2338
	}
2339
2340
	/**
2341
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2342
	 * Make sure to tuck away module "library" files in a sub-directory.
2343
	 */
2344
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2345
		static $modules = null;
2346
2347
		if ( ! isset( $modules ) ) {
2348
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2349
			// Use the cache if we're on the front-end and it's available...
2350
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2351
				$modules = $available_modules_option[ JETPACK__VERSION ];
2352
			} else {
2353
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2354
2355
				$modules = array();
2356
2357
				foreach ( $files as $file ) {
2358
					if ( ! $headers = self::get_module( $file ) ) {
2359
						continue;
2360
					}
2361
2362
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2363
				}
2364
2365
				Jetpack_Options::update_option(
2366
					'available_modules',
2367
					array(
2368
						JETPACK__VERSION => $modules,
2369
					)
2370
				);
2371
			}
2372
		}
2373
2374
		/**
2375
		 * Filters the array of modules available to be activated.
2376
		 *
2377
		 * @since 2.4.0
2378
		 *
2379
		 * @param array $modules Array of available modules.
2380
		 * @param string $min_version Minimum version number required to use modules.
2381
		 * @param string $max_version Maximum version number required to use modules.
2382
		 */
2383
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2384
2385
		if ( ! $min_version && ! $max_version ) {
2386
			return array_keys( $mods );
2387
		}
2388
2389
		$r = array();
2390
		foreach ( $mods as $slug => $introduced ) {
2391
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2392
				continue;
2393
			}
2394
2395
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2396
				continue;
2397
			}
2398
2399
			$r[] = $slug;
2400
		}
2401
2402
		return $r;
2403
	}
2404
2405
	/**
2406
	 * Default modules loaded on activation.
2407
	 */
2408
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2409
		$return = array();
2410
2411
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2412
			$module_data = self::get_module( $module );
2413
2414
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2415
				case 'yes':
2416
					$return[] = $module;
2417
					break;
2418
				case 'public':
2419
					if ( Jetpack_Options::get_option( 'public' ) ) {
2420
						$return[] = $module;
2421
					}
2422
					break;
2423
				case 'no':
2424
				default:
2425
					break;
2426
			}
2427
		}
2428
		/**
2429
		 * Filters the array of default modules.
2430
		 *
2431
		 * @since 2.5.0
2432
		 *
2433
		 * @param array $return Array of default modules.
2434
		 * @param string $min_version Minimum version number required to use modules.
2435
		 * @param string $max_version Maximum version number required to use modules.
2436
		 */
2437
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2438
	}
2439
2440
	/**
2441
	 * Checks activated modules during auto-activation to determine
2442
	 * if any of those modules are being deprecated.  If so, close
2443
	 * them out, and add any replacement modules.
2444
	 *
2445
	 * Runs at priority 99 by default.
2446
	 *
2447
	 * This is run late, so that it can still activate a module if
2448
	 * the new module is a replacement for another that the user
2449
	 * currently has active, even if something at the normal priority
2450
	 * would kibosh everything.
2451
	 *
2452
	 * @since 2.6
2453
	 * @uses jetpack_get_default_modules filter
2454
	 * @param array $modules
2455
	 * @return array
2456
	 */
2457
	function handle_deprecated_modules( $modules ) {
2458
		$deprecated_modules = array(
2459
			'debug'            => null,  // Closed out and moved to the debugger library.
2460
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2461
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2462
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2463
		);
2464
2465
		// Don't activate SSO if they never completed activating WPCC.
2466
		if ( self::is_module_active( 'wpcc' ) ) {
2467
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2468
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2469
				$deprecated_modules['wpcc'] = null;
2470
			}
2471
		}
2472
2473
		foreach ( $deprecated_modules as $module => $replacement ) {
2474
			if ( self::is_module_active( $module ) ) {
2475
				self::deactivate_module( $module );
2476
				if ( $replacement ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $replacement of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2477
					$modules[] = $replacement;
2478
				}
2479
			}
2480
		}
2481
2482
		return array_unique( $modules );
2483
	}
2484
2485
	/**
2486
	 * Checks activated plugins during auto-activation to determine
2487
	 * if any of those plugins are in the list with a corresponding module
2488
	 * that is not compatible with the plugin. The module will not be allowed
2489
	 * to auto-activate.
2490
	 *
2491
	 * @since 2.6
2492
	 * @uses jetpack_get_default_modules filter
2493
	 * @param array $modules
2494
	 * @return array
2495
	 */
2496
	function filter_default_modules( $modules ) {
2497
2498
		$active_plugins = self::get_active_plugins();
2499
2500
		if ( ! empty( $active_plugins ) ) {
2501
2502
			// For each module we'd like to auto-activate...
2503
			foreach ( $modules as $key => $module ) {
2504
				// If there are potential conflicts for it...
2505
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2506
					// For each potential conflict...
2507
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2508
						// If that conflicting plugin is active...
2509
						if ( in_array( $plugin, $active_plugins ) ) {
2510
							// Remove that item from being auto-activated.
2511
							unset( $modules[ $key ] );
2512
						}
2513
					}
2514
				}
2515
			}
2516
		}
2517
2518
		return $modules;
2519
	}
2520
2521
	/**
2522
	 * Extract a module's slug from its full path.
2523
	 */
2524
	public static function get_module_slug( $file ) {
2525
		return str_replace( '.php', '', basename( $file ) );
2526
	}
2527
2528
	/**
2529
	 * Generate a module's path from its slug.
2530
	 */
2531
	public static function get_module_path( $slug ) {
2532
		/**
2533
		 * Filters the path of a modules.
2534
		 *
2535
		 * @since 7.4.0
2536
		 *
2537
		 * @param array $return The absolute path to a module's root php file
2538
		 * @param string $slug The module slug
2539
		 */
2540
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $slug.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2541
	}
2542
2543
	/**
2544
	 * Load module data from module file. Headers differ from WordPress
2545
	 * plugin headers to avoid them being identified as standalone
2546
	 * plugins on the WordPress plugins page.
2547
	 */
2548
	public static function get_module( $module ) {
2549
		$headers = array(
2550
			'name'                      => 'Module Name',
2551
			'description'               => 'Module Description',
2552
			'sort'                      => 'Sort Order',
2553
			'recommendation_order'      => 'Recommendation Order',
2554
			'introduced'                => 'First Introduced',
2555
			'changed'                   => 'Major Changes In',
2556
			'deactivate'                => 'Deactivate',
2557
			'free'                      => 'Free',
2558
			'requires_connection'       => 'Requires Connection',
2559
			'auto_activate'             => 'Auto Activate',
2560
			'module_tags'               => 'Module Tags',
2561
			'feature'                   => 'Feature',
2562
			'additional_search_queries' => 'Additional Search Queries',
2563
			'plan_classes'              => 'Plans',
2564
		);
2565
2566
		$file = self::get_module_path( self::get_module_slug( $module ) );
2567
2568
		$mod = self::get_file_data( $file, $headers );
2569
		if ( empty( $mod['name'] ) ) {
2570
			return false;
2571
		}
2572
2573
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2574
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2575
		$mod['deactivate']           = empty( $mod['deactivate'] );
2576
		$mod['free']                 = empty( $mod['free'] );
2577
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2578
2579
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2580
			$mod['auto_activate'] = 'No';
2581
		} else {
2582
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2583
		}
2584
2585
		if ( $mod['module_tags'] ) {
2586
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2587
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2588
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2589
		} else {
2590
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2591
		}
2592
2593 View Code Duplication
		if ( $mod['plan_classes'] ) {
2594
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2595
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2596
		} else {
2597
			$mod['plan_classes'] = array( 'free' );
2598
		}
2599
2600 View Code Duplication
		if ( $mod['feature'] ) {
2601
			$mod['feature'] = explode( ',', $mod['feature'] );
2602
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2603
		} else {
2604
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2605
		}
2606
2607
		/**
2608
		 * Filters the feature array on a module.
2609
		 *
2610
		 * This filter allows you to control where each module is filtered: Recommended,
2611
		 * and the default "Other" listing.
2612
		 *
2613
		 * @since 3.5.0
2614
		 *
2615
		 * @param array   $mod['feature'] The areas to feature this module:
2616
		 *     'Recommended' shows on the main Jetpack admin screen.
2617
		 *     'Other' should be the default if no other value is in the array.
2618
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2619
		 * @param array   $mod All the currently assembled module data.
2620
		 */
2621
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2622
2623
		/**
2624
		 * Filter the returned data about a module.
2625
		 *
2626
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2627
		 * so please be careful.
2628
		 *
2629
		 * @since 3.6.0
2630
		 *
2631
		 * @param array   $mod    The details of the requested module.
2632
		 * @param string  $module The slug of the module, e.g. sharedaddy
2633
		 * @param string  $file   The path to the module source file.
2634
		 */
2635
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2636
	}
2637
2638
	/**
2639
	 * Like core's get_file_data implementation, but caches the result.
2640
	 */
2641
	public static function get_file_data( $file, $headers ) {
2642
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2643
		$file_name = basename( $file );
2644
2645
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2646
2647
		$file_data_option = get_transient( $cache_key );
2648
2649
		if ( ! is_array( $file_data_option ) ) {
2650
			delete_transient( $cache_key );
2651
			$file_data_option = false;
2652
		}
2653
2654
		if ( false === $file_data_option ) {
2655
			$file_data_option = array();
2656
		}
2657
2658
		$key           = md5( $file_name . serialize( $headers ) );
2659
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2660
2661
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2662
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2663
			return $file_data_option[ $key ];
2664
		}
2665
2666
		$data = get_file_data( $file, $headers );
2667
2668
		$file_data_option[ $key ] = $data;
2669
2670
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2671
2672
		return $data;
2673
	}
2674
2675
	/**
2676
	 * Return translated module tag.
2677
	 *
2678
	 * @param string $tag Tag as it appears in each module heading.
2679
	 *
2680
	 * @return mixed
2681
	 */
2682
	public static function translate_module_tag( $tag ) {
2683
		return jetpack_get_module_i18n_tag( $tag );
2684
	}
2685
2686
	/**
2687
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2688
	 *
2689
	 * @since 3.9.2
2690
	 *
2691
	 * @param array $modules
2692
	 *
2693
	 * @return string|void
2694
	 */
2695
	public static function get_translated_modules( $modules ) {
2696
		foreach ( $modules as $index => $module ) {
2697
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2698
			if ( isset( $module['name'] ) ) {
2699
				$modules[ $index ]['name'] = $i18n_module['name'];
2700
			}
2701
			if ( isset( $module['description'] ) ) {
2702
				$modules[ $index ]['description']       = $i18n_module['description'];
2703
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2704
			}
2705
		}
2706
		return $modules;
2707
	}
2708
2709
	/**
2710
	 * Get a list of activated modules as an array of module slugs.
2711
	 */
2712
	public static function get_active_modules() {
2713
		$active = Jetpack_Options::get_option( 'active_modules' );
2714
2715
		if ( ! is_array( $active ) ) {
2716
			$active = array();
2717
		}
2718
2719
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2720
			$active[] = 'vaultpress';
2721
		} else {
2722
			$active = array_diff( $active, array( 'vaultpress' ) );
2723
		}
2724
2725
		// If protect is active on the main site of a multisite, it should be active on all sites.
2726
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2727
			$active[] = 'protect';
2728
		}
2729
2730
		/**
2731
		 * Allow filtering of the active modules.
2732
		 *
2733
		 * Gives theme and plugin developers the power to alter the modules that
2734
		 * are activated on the fly.
2735
		 *
2736
		 * @since 5.8.0
2737
		 *
2738
		 * @param array $active Array of active module slugs.
2739
		 */
2740
		$active = apply_filters( 'jetpack_active_modules', $active );
2741
2742
		return array_unique( $active );
2743
	}
2744
2745
	/**
2746
	 * Check whether or not a Jetpack module is active.
2747
	 *
2748
	 * @param string $module The slug of a Jetpack module.
2749
	 * @return bool
2750
	 *
2751
	 * @static
2752
	 */
2753
	public static function is_module_active( $module ) {
2754
		return in_array( $module, self::get_active_modules() );
2755
	}
2756
2757
	public static function is_module( $module ) {
2758
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2759
	}
2760
2761
	/**
2762
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2763
	 *
2764
	 * @param bool $catch True to start catching, False to stop.
2765
	 *
2766
	 * @static
2767
	 */
2768
	public static function catch_errors( $catch ) {
2769
		static $display_errors, $error_reporting;
2770
2771
		if ( $catch ) {
2772
			$display_errors  = @ini_set( 'display_errors', 1 );
2773
			$error_reporting = @error_reporting( E_ALL );
2774
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2775
		} else {
2776
			@ini_set( 'display_errors', $display_errors );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2777
			@error_reporting( $error_reporting );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2778
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2779
		}
2780
	}
2781
2782
	/**
2783
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2784
	 */
2785
	public static function catch_errors_on_shutdown() {
2786
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2787
	}
2788
2789
	/**
2790
	 * Rewrite any string to make paths easier to read.
2791
	 *
2792
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2793
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2794
	 *
2795
	 * @param $string
2796
	 * @return mixed
2797
	 */
2798
	public static function alias_directories( $string ) {
2799
		// ABSPATH has a trailing slash.
2800
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2801
		// WP_CONTENT_DIR does not have a trailing slash.
2802
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2803
2804
		return $string;
2805
	}
2806
2807
	public static function activate_default_modules(
2808
		$min_version = false,
2809
		$max_version = false,
2810
		$other_modules = array(),
2811
		$redirect = null,
2812
		$send_state_messages = null
2813
	) {
2814
		$jetpack = self::init();
2815
2816
		if ( is_null( $redirect ) ) {
2817
			if (
2818
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2819
			||
2820
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2821
			||
2822
				( defined( 'WP_CLI' ) && WP_CLI )
2823
			||
2824
				( defined( 'DOING_CRON' ) && DOING_CRON )
2825
			||
2826
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2827
			) {
2828
				$redirect = false;
2829
			} elseif ( is_admin() ) {
2830
				$redirect = true;
2831
			} else {
2832
				$redirect = false;
2833
			}
2834
		}
2835
2836
		if ( is_null( $send_state_messages ) ) {
2837
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2838
		}
2839
2840
		$modules = self::get_default_modules( $min_version, $max_version );
2841
		$modules = array_merge( $other_modules, $modules );
2842
2843
		// Look for standalone plugins and disable if active.
2844
2845
		$to_deactivate = array();
2846
		foreach ( $modules as $module ) {
2847
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2848
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2849
			}
2850
		}
2851
2852
		$deactivated = array();
2853
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2854
			list( $probable_file, $probable_title ) = $deactivate_me;
2855
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2856
				$deactivated[] = $module;
2857
			}
2858
		}
2859
2860
		if ( $deactivated ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2861
			if ( $send_state_messages ) {
2862
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2863
			}
2864
2865
			if ( $redirect ) {
2866
				$url = add_query_arg(
2867
					array(
2868
						'action'   => 'activate_default_modules',
2869
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2870
					),
2871
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2872
				);
2873
				wp_safe_redirect( $url );
2874
				exit;
2875
			}
2876
		}
2877
2878
		/**
2879
		 * Fires before default modules are activated.
2880
		 *
2881
		 * @since 1.9.0
2882
		 *
2883
		 * @param string $min_version Minimum version number required to use modules.
2884
		 * @param string $max_version Maximum version number required to use modules.
2885
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2886
		 */
2887
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2888
2889
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2890
		if ( $send_state_messages ) {
2891
			self::restate();
2892
			self::catch_errors( true );
2893
		}
2894
2895
		$active = self::get_active_modules();
2896
2897
		foreach ( $modules as $module ) {
2898
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2899
				$active[] = $module;
2900
				self::update_active_modules( $active );
2901
				continue;
2902
			}
2903
2904
			if ( $send_state_messages && in_array( $module, $active ) ) {
2905
				$module_info = self::get_module( $module );
2906 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2907
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2908
					if ( $active_state = self::state( $state ) ) {
2909
						$active_state = explode( ',', $active_state );
2910
					} else {
2911
						$active_state = array();
2912
					}
2913
					$active_state[] = $module;
2914
					self::state( $state, implode( ',', $active_state ) );
2915
				}
2916
				continue;
2917
			}
2918
2919
			$file = self::get_module_path( $module );
2920
			if ( ! file_exists( $file ) ) {
2921
				continue;
2922
			}
2923
2924
			// we'll override this later if the plugin can be included without fatal error
2925
			if ( $redirect ) {
2926
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2927
			}
2928
2929
			if ( $send_state_messages ) {
2930
				self::state( 'error', 'module_activation_failed' );
2931
				self::state( 'module', $module );
2932
			}
2933
2934
			ob_start();
2935
			require_once $file;
2936
2937
			$active[] = $module;
2938
2939 View Code Duplication
			if ( $send_state_messages ) {
2940
2941
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2942
				if ( $active_state = self::state( $state ) ) {
2943
					$active_state = explode( ',', $active_state );
2944
				} else {
2945
					$active_state = array();
2946
				}
2947
				$active_state[] = $module;
2948
				self::state( $state, implode( ',', $active_state ) );
2949
			}
2950
2951
			self::update_active_modules( $active );
2952
2953
			ob_end_clean();
2954
		}
2955
2956
		if ( $send_state_messages ) {
2957
			self::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2958
			self::state( 'module', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2959
		}
2960
2961
		self::catch_errors( false );
2962
		/**
2963
		 * Fires when default modules are activated.
2964
		 *
2965
		 * @since 1.9.0
2966
		 *
2967
		 * @param string $min_version Minimum version number required to use modules.
2968
		 * @param string $max_version Maximum version number required to use modules.
2969
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2970
		 */
2971
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2972
	}
2973
2974
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2975
		/**
2976
		 * Fires before a module is activated.
2977
		 *
2978
		 * @since 2.6.0
2979
		 *
2980
		 * @param string $module Module slug.
2981
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2982
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2983
		 */
2984
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2985
2986
		$jetpack = self::init();
2987
2988
		if ( ! strlen( $module ) ) {
2989
			return false;
2990
		}
2991
2992
		if ( ! self::is_module( $module ) ) {
2993
			return false;
2994
		}
2995
2996
		// If it's already active, then don't do it again
2997
		$active = self::get_active_modules();
2998
		foreach ( $active as $act ) {
2999
			if ( $act == $module ) {
3000
				return true;
3001
			}
3002
		}
3003
3004
		$module_data = self::get_module( $module );
3005
3006
		$is_offline_mode = ( new Status() )->is_offline_mode();
3007
		if ( ! self::is_active() ) {
3008
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3009
				return false;
3010
			}
3011
3012
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3013
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3014
				return false;
3015
			}
3016
		}
3017
3018
		// Check and see if the old plugin is active
3019
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3020
			// Deactivate the old plugin
3021
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3022
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3023
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3024
				self::state( 'deactivated_plugins', $module );
3025
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3026
				exit;
3027
			}
3028
		}
3029
3030
		// Protect won't work with mis-configured IPs
3031
		if ( 'protect' === $module ) {
3032
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3033
			if ( ! jetpack_protect_get_ip() ) {
3034
				self::state( 'message', 'protect_misconfigured_ip' );
3035
				return false;
3036
			}
3037
		}
3038
3039
		if ( ! Jetpack_Plan::supports( $module ) ) {
3040
			return false;
3041
		}
3042
3043
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3044
		self::state( 'module', $module );
3045
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3046
3047
		self::catch_errors( true );
3048
		ob_start();
3049
		require self::get_module_path( $module );
3050
		/** This action is documented in class.jetpack.php */
3051
		do_action( 'jetpack_activate_module', $module );
3052
		$active[] = $module;
3053
		self::update_active_modules( $active );
3054
3055
		self::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3056
		ob_end_clean();
3057
		self::catch_errors( false );
3058
3059
		if ( $redirect ) {
3060
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3061
		}
3062
		if ( $exit ) {
3063
			exit;
3064
		}
3065
		return true;
3066
	}
3067
3068
	function activate_module_actions( $module ) {
3069
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3070
	}
3071
3072
	public static function deactivate_module( $module ) {
3073
		/**
3074
		 * Fires when a module is deactivated.
3075
		 *
3076
		 * @since 1.9.0
3077
		 *
3078
		 * @param string $module Module slug.
3079
		 */
3080
		do_action( 'jetpack_pre_deactivate_module', $module );
3081
3082
		$jetpack = self::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3083
3084
		$active = self::get_active_modules();
3085
		$new    = array_filter( array_diff( $active, (array) $module ) );
3086
3087
		return self::update_active_modules( $new );
3088
	}
3089
3090
	public static function enable_module_configurable( $module ) {
3091
		$module = self::get_module_slug( $module );
3092
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3093
	}
3094
3095
	/**
3096
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3097
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3098
	 *
3099
	 * @param string $module Module slug
3100
	 * @return string $url module configuration URL
3101
	 */
3102
	public static function module_configuration_url( $module ) {
3103
		$module      = self::get_module_slug( $module );
3104
		$default_url = self::admin_url() . "#/settings?term=$module";
3105
		/**
3106
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3107
		 *
3108
		 * @since 6.9.0
3109
		 *
3110
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3111
		 */
3112
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3113
3114
		return $url;
3115
	}
3116
3117
	/* Installation */
3118
	public static function bail_on_activation( $message, $deactivate = true ) {
3119
		?>
3120
<!doctype html>
3121
<html>
3122
<head>
3123
<meta charset="<?php bloginfo( 'charset' ); ?>">
3124
<style>
3125
* {
3126
	text-align: center;
3127
	margin: 0;
3128
	padding: 0;
3129
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3130
}
3131
p {
3132
	margin-top: 1em;
3133
	font-size: 18px;
3134
}
3135
</style>
3136
<body>
3137
<p><?php echo esc_html( $message ); ?></p>
3138
</body>
3139
</html>
3140
		<?php
3141
		if ( $deactivate ) {
3142
			$plugins = get_option( 'active_plugins' );
3143
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3144
			$update  = false;
3145
			foreach ( $plugins as $i => $plugin ) {
3146
				if ( $plugin === $jetpack ) {
3147
					$plugins[ $i ] = false;
3148
					$update        = true;
3149
				}
3150
			}
3151
3152
			if ( $update ) {
3153
				update_option( 'active_plugins', array_filter( $plugins ) );
3154
			}
3155
		}
3156
		exit;
3157
	}
3158
3159
	/**
3160
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3161
	 *
3162
	 * @static
3163
	 */
3164
	public static function plugin_activation( $network_wide ) {
3165
		Jetpack_Options::update_option( 'activated', 1 );
3166
3167
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3168
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3169
		}
3170
3171
		if ( $network_wide ) {
3172
			self::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3173
		}
3174
3175
		// For firing one-off events (notices) immediately after activation
3176
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3177
3178
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3179
3180
		Health::on_jetpack_activated();
3181
3182
		self::plugin_initialize();
3183
	}
3184
3185
	public static function get_activation_source( $referer_url ) {
3186
3187
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3188
			return array( 'wp-cli', null );
3189
		}
3190
3191
		$referer = wp_parse_url( $referer_url );
3192
3193
		$source_type  = 'unknown';
3194
		$source_query = null;
3195
3196
		if ( ! is_array( $referer ) ) {
3197
			return array( $source_type, $source_query );
3198
		}
3199
3200
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3201
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3202
3203
		if ( isset( $referer['query'] ) ) {
3204
			parse_str( $referer['query'], $query_parts );
3205
		} else {
3206
			$query_parts = array();
3207
		}
3208
3209
		if ( $plugins_path === $referer['path'] ) {
3210
			$source_type = 'list';
3211
		} elseif ( $plugins_install_path === $referer['path'] ) {
3212
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3213
			switch ( $tab ) {
3214
				case 'popular':
3215
					$source_type = 'popular';
3216
					break;
3217
				case 'recommended':
3218
					$source_type = 'recommended';
3219
					break;
3220
				case 'favorites':
3221
					$source_type = 'favorites';
3222
					break;
3223
				case 'search':
3224
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3225
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3226
					break;
3227
				default:
3228
					$source_type = 'featured';
3229
			}
3230
		}
3231
3232
		return array( $source_type, $source_query );
3233
	}
3234
3235
	/**
3236
	 * Runs before bumping version numbers up to a new version
3237
	 *
3238
	 * @param string $version    Version:timestamp.
3239
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3240
	 */
3241
	public static function do_version_bump( $version, $old_version ) {
3242
		if ( $old_version ) { // For existing Jetpack installations.
3243
3244
			// If a front end page is visited after the update, the 'wp' action will fire.
3245
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3246
3247
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3248
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3249
		}
3250
	}
3251
3252
	/**
3253
	 * Sets the display_update_modal state.
3254
	 */
3255
	public static function set_update_modal_display() {
3256
		self::state( 'display_update_modal', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3257
	}
3258
3259
	/**
3260
	 * Sets the internal version number and activation state.
3261
	 *
3262
	 * @static
3263
	 */
3264
	public static function plugin_initialize() {
3265
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3266
			Jetpack_Options::update_option( 'activated', 2 );
3267
		}
3268
3269 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3270
			$version = $old_version = JETPACK__VERSION . ':' . time();
3271
			/** This action is documented in class.jetpack.php */
3272
			do_action( 'updating_jetpack_version', $version, false );
3273
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3274
		}
3275
3276
		self::load_modules();
3277
3278
		Jetpack_Options::delete_option( 'do_activate' );
3279
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3280
	}
3281
3282
	/**
3283
	 * Removes all connection options
3284
	 *
3285
	 * @static
3286
	 */
3287
	public static function plugin_deactivation() {
3288
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3289
		$tracking = new Tracking();
3290
		$tracking->record_user_event( 'deactivate_plugin', array() );
3291
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3292
			Jetpack_Network::init()->deactivate();
3293
		} else {
3294
			self::disconnect( false );
3295
			// Jetpack_Heartbeat::init()->deactivate();
3296
		}
3297
	}
3298
3299
	/**
3300
	 * Disconnects from the Jetpack servers.
3301
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3302
	 *
3303
	 * @static
3304
	 */
3305
	public static function disconnect( $update_activated_state = true ) {
3306
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3307
3308
		$connection = self::connection();
3309
		$connection->clean_nonces( true );
3310
3311
		// If the site is in an IDC because sync is not allowed,
3312
		// let's make sure to not disconnect the production site.
3313
		if ( ! self::validate_sync_error_idc_option() ) {
3314
			$tracking = new Tracking();
3315
			$tracking->record_user_event( 'disconnect_site', array() );
3316
3317
			$connection->disconnect_site_wpcom( true );
3318
		}
3319
3320
		$connection->delete_all_connection_tokens( true );
3321
		Jetpack_IDC::clear_all_idc_options();
3322
3323
		if ( $update_activated_state ) {
3324
			Jetpack_Options::update_option( 'activated', 4 );
3325
		}
3326
3327
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3328
			// Check then record unique disconnection if site has never been disconnected previously
3329
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3330
				$jetpack_unique_connection['disconnected'] = 1;
3331
			} else {
3332
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3333
					// track unique disconnect
3334
					$jetpack = self::init();
3335
3336
					$jetpack->stat( 'connections', 'unique-disconnect' );
3337
					$jetpack->do_stats( 'server_side' );
3338
				}
3339
				// increment number of times disconnected
3340
				$jetpack_unique_connection['disconnected'] += 1;
3341
			}
3342
3343
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3344
		}
3345
3346
		// Delete all the sync related data. Since it could be taking up space.
3347
		Sender::get_instance()->uninstall();
3348
3349
	}
3350
3351
	/**
3352
	 * Unlinks the current user from the linked WordPress.com user.
3353
	 *
3354
	 * @deprecated since 7.7
3355
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3356
	 *
3357
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
3358
	 * @return Boolean Whether the disconnection of the user was successful.
3359
	 */
3360
	public static function unlink_user( $user_id = null ) {
3361
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3362
		return Connection_Manager::disconnect_user( $user_id );
3363
	}
3364
3365
	/**
3366
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3367
	 */
3368
	public static function try_registration() {
3369
		$terms_of_service = new Terms_Of_Service();
3370
		// The user has agreed to the TOS at some point by now.
3371
		$terms_of_service->agree();
3372
3373
		// Let's get some testing in beta versions and such.
3374
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3375
			// Before attempting to connect, let's make sure that the domains are viable.
3376
			$domains_to_check = array_unique(
3377
				array(
3378
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3379
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3380
				)
3381
			);
3382
			foreach ( $domains_to_check as $domain ) {
3383
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3382 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
3384
				if ( is_wp_error( $result ) ) {
3385
					return $result;
3386
				}
3387
			}
3388
		}
3389
3390
		$result = self::register();
3391
3392
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3393
		if ( ! $result || is_wp_error( $result ) ) {
3394
			return $result;
3395
		} else {
3396
			return true;
3397
		}
3398
	}
3399
3400
	/**
3401
	 * Tracking an internal event log. Try not to put too much chaff in here.
3402
	 *
3403
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3404
	 */
3405
	public static function log( $code, $data = null ) {
3406
		// only grab the latest 200 entries
3407
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3408
3409
		// Append our event to the log
3410
		$log_entry = array(
3411
			'time'    => time(),
3412
			'user_id' => get_current_user_id(),
3413
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3414
			'code'    => $code,
3415
		);
3416
		// Don't bother storing it unless we've got some.
3417
		if ( ! is_null( $data ) ) {
3418
			$log_entry['data'] = $data;
3419
		}
3420
		$log[] = $log_entry;
3421
3422
		// Try add_option first, to make sure it's not autoloaded.
3423
		// @todo: Add an add_option method to Jetpack_Options
3424
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3425
			Jetpack_Options::update_option( 'log', $log );
3426
		}
3427
3428
		/**
3429
		 * Fires when Jetpack logs an internal event.
3430
		 *
3431
		 * @since 3.0.0
3432
		 *
3433
		 * @param array $log_entry {
3434
		 *  Array of details about the log entry.
3435
		 *
3436
		 *  @param string time Time of the event.
3437
		 *  @param int user_id ID of the user who trigerred the event.
3438
		 *  @param int blog_id Jetpack Blog ID.
3439
		 *  @param string code Unique name for the event.
3440
		 *  @param string data Data about the event.
3441
		 * }
3442
		 */
3443
		do_action( 'jetpack_log_entry', $log_entry );
3444
	}
3445
3446
	/**
3447
	 * Get the internal event log.
3448
	 *
3449
	 * @param $event (string) - only return the specific log events
3450
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3451
	 *
3452
	 * @return array of log events || WP_Error for invalid params
3453
	 */
3454
	public static function get_log( $event = false, $num = false ) {
3455
		if ( $event && ! is_string( $event ) ) {
3456
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3457
		}
3458
3459
		if ( $num && ! is_numeric( $num ) ) {
3460
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3461
		}
3462
3463
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3464
3465
		// If nothing set - act as it did before, otherwise let's start customizing the output
3466
		if ( ! $num && ! $event ) {
3467
			return $entire_log;
3468
		} else {
3469
			$entire_log = array_reverse( $entire_log );
3470
		}
3471
3472
		$custom_log_output = array();
3473
3474
		if ( $event ) {
3475
			foreach ( $entire_log as $log_event ) {
3476
				if ( $event == $log_event['code'] ) {
3477
					$custom_log_output[] = $log_event;
3478
				}
3479
			}
3480
		} else {
3481
			$custom_log_output = $entire_log;
3482
		}
3483
3484
		if ( $num ) {
3485
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3486
		}
3487
3488
		return $custom_log_output;
3489
	}
3490
3491
	/**
3492
	 * Log modification of important settings.
3493
	 */
3494
	public static function log_settings_change( $option, $old_value, $value ) {
3495
		switch ( $option ) {
3496
			case 'jetpack_sync_non_public_post_stati':
3497
				self::log( $option, $value );
3498
				break;
3499
		}
3500
	}
3501
3502
	/**
3503
	 * Return stat data for WPCOM sync
3504
	 */
3505
	public static function get_stat_data( $encode = true, $extended = true ) {
3506
		$data = Jetpack_Heartbeat::generate_stats_array();
3507
3508
		if ( $extended ) {
3509
			$additional_data = self::get_additional_stat_data();
3510
			$data            = array_merge( $data, $additional_data );
3511
		}
3512
3513
		if ( $encode ) {
3514
			return json_encode( $data );
3515
		}
3516
3517
		return $data;
3518
	}
3519
3520
	/**
3521
	 * Get additional stat data to sync to WPCOM
3522
	 */
3523
	public static function get_additional_stat_data( $prefix = '' ) {
3524
		$return[ "{$prefix}themes" ]        = self::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3525
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3526
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3527
		$return[ "{$prefix}site-count" ]    = 0;
3528
3529
		if ( function_exists( 'get_blog_count' ) ) {
3530
			$return[ "{$prefix}site-count" ] = get_blog_count();
3531
		}
3532
		return $return;
3533
	}
3534
3535
	private static function get_site_user_count() {
3536
		global $wpdb;
3537
3538
		if ( function_exists( 'wp_is_large_network' ) ) {
3539
			if ( wp_is_large_network( 'users' ) ) {
3540
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3541
			}
3542
		}
3543
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3544
			// It wasn't there, so regenerate the data and save the transient
3545
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3546
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3547
		}
3548
		return $user_count;
3549
	}
3550
3551
	/* Admin Pages */
3552
3553
	function admin_init() {
3554
		// If the plugin is not connected, display a connect message.
3555
		if (
3556
			// the plugin was auto-activated and needs its candy
3557
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3558
		||
3559
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3560
			! Jetpack_Options::get_option( 'activated' )
3561
		) {
3562
			self::plugin_initialize();
3563
		}
3564
3565
		$is_offline_mode = ( new Status() )->is_offline_mode();
3566
		if ( ! self::is_active() && ! $is_offline_mode ) {
3567
			Jetpack_Connection_Banner::init();
3568
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3569
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3570
			// Upgrade: 1.1 -> 1.1.1
3571
			// Check and see if host can verify the Jetpack servers' SSL certificate
3572
			$args = array();
3573
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3574
		}
3575
3576
		Jetpack_Wizard_Banner::init();
3577
3578
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3579
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3580
		}
3581
3582
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3583
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3584
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3585
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3586
3587
		if ( self::is_active() || $is_offline_mode ) {
3588
			// Artificially throw errors in certain specific cases during plugin activation.
3589
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3590
		}
3591
3592
		// Add custom column in wp-admin/users.php to show whether user is linked.
3593
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3594
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3595
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3596
	}
3597
3598
	function admin_body_class( $admin_body_class = '' ) {
3599
		$classes = explode( ' ', trim( $admin_body_class ) );
3600
3601
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3602
3603
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3604
		return " $admin_body_class ";
3605
	}
3606
3607
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3608
		return $admin_body_class . ' jetpack-pagestyles ';
3609
	}
3610
3611
	/**
3612
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3613
	 * This function artificially throws errors for such cases (per a specific list).
3614
	 *
3615
	 * @param string $plugin The activated plugin.
3616
	 */
3617
	function throw_error_on_activate_plugin( $plugin ) {
3618
		$active_modules = self::get_active_modules();
3619
3620
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3621
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3622
			$throw = false;
3623
3624
			// Try and make sure it really was the stats plugin
3625
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3626
				if ( 'stats.php' == basename( $plugin ) ) {
3627
					$throw = true;
3628
				}
3629
			} else {
3630
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3631
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3632
					$throw = true;
3633
				}
3634
			}
3635
3636
			if ( $throw ) {
3637
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3638
			}
3639
		}
3640
	}
3641
3642
	function intercept_plugin_error_scrape_init() {
3643
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3644
	}
3645
3646
	function intercept_plugin_error_scrape( $action, $result ) {
3647
		if ( ! $result ) {
3648
			return;
3649
		}
3650
3651
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3652
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3653
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3654
			}
3655
		}
3656
	}
3657
3658
	/**
3659
	 * Register the remote file upload request handlers, if needed.
3660
	 *
3661
	 * @access public
3662
	 */
3663
	public function add_remote_request_handlers() {
3664
		// Remote file uploads are allowed only via AJAX requests.
3665
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3666
			return;
3667
		}
3668
3669
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3670
		$remote_request_actions = array(
3671
			'jetpack_upload_file',
3672
			'jetpack_update_file',
3673
		);
3674
3675
		// phpcs:ignore WordPress.Security.NonceVerification
3676
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3677
			return;
3678
		}
3679
3680
		// Require Jetpack authentication for the remote file upload AJAX requests.
3681
		if ( ! $this->connection_manager ) {
3682
			$this->connection_manager = new Connection_Manager();
3683
		}
3684
3685
		$this->connection_manager->require_jetpack_authentication();
3686
3687
		// Register the remote file upload AJAX handlers.
3688
		foreach ( $remote_request_actions as $action ) {
3689
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3690
		}
3691
	}
3692
3693
	/**
3694
	 * Handler for Jetpack remote file uploads.
3695
	 *
3696
	 * @access public
3697
	 */
3698
	public function remote_request_handlers() {
3699
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3700
3701
		switch ( current_filter() ) {
3702
			case 'wp_ajax_nopriv_jetpack_upload_file':
3703
				$response = $this->upload_handler();
3704
				break;
3705
3706
			case 'wp_ajax_nopriv_jetpack_update_file':
3707
				$response = $this->upload_handler( true );
3708
				break;
3709
			default:
3710
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_handler'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3711
				break;
3712
		}
3713
3714
		if ( ! $response ) {
3715
			$response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3716
		}
3717
3718
		if ( is_wp_error( $response ) ) {
3719
			$status_code       = $response->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3720
			$error             = $response->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3721
			$error_description = $response->get_error_message();
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3722
3723
			if ( ! is_int( $status_code ) ) {
3724
				$status_code = 400;
3725
			}
3726
3727
			status_header( $status_code );
3728
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3729
		}
3730
3731
		status_header( 200 );
3732
		if ( true === $response ) {
3733
			exit;
3734
		}
3735
3736
		die( json_encode( (object) $response ) );
3737
	}
3738
3739
	/**
3740
	 * Uploads a file gotten from the global $_FILES.
3741
	 * If `$update_media_item` is true and `post_id` is defined
3742
	 * the attachment file of the media item (gotten through of the post_id)
3743
	 * will be updated instead of add a new one.
3744
	 *
3745
	 * @param  boolean $update_media_item - update media attachment
3746
	 * @return array - An array describing the uploadind files process
3747
	 */
3748
	function upload_handler( $update_media_item = false ) {
3749
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3750
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 405.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3751
		}
3752
3753
		$user = wp_authenticate( '', '' );
3754
		if ( ! $user || is_wp_error( $user ) ) {
3755
			return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 403.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3756
		}
3757
3758
		wp_set_current_user( $user->ID );
3759
3760
		if ( ! current_user_can( 'upload_files' ) ) {
3761
			return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3762
		}
3763
3764
		if ( empty( $_FILES ) ) {
3765
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3766
		}
3767
3768
		foreach ( array_keys( $_FILES ) as $files_key ) {
3769
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3770
				return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_hmac'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3771
			}
3772
		}
3773
3774
		$media_keys = array_keys( $_FILES['media'] );
3775
3776
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3777
		if ( ! $token || is_wp_error( $token ) ) {
3778
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3779
		}
3780
3781
		$uploaded_files = array();
3782
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3783
		unset( $GLOBALS['post'] );
3784
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3785
			$file = array();
3786
			foreach ( $media_keys as $media_key ) {
3787
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3788
			}
3789
3790
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3791
3792
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3793
			if ( $hmac_provided !== $hmac_file ) {
3794
				$uploaded_files[ $index ] = (object) array(
3795
					'error'             => 'invalid_hmac',
3796
					'error_description' => 'The corresponding HMAC for this file does not match',
3797
				);
3798
				continue;
3799
			}
3800
3801
			$_FILES['.jetpack.upload.'] = $file;
3802
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3803
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3804
				$post_id = 0;
3805
			}
3806
3807
			if ( $update_media_item ) {
3808
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3809
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_input'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3810
				}
3811
3812
				$media_array = $_FILES['media'];
3813
3814
				$file_array['name']     = $media_array['name'][0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$file_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $file_array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3815
				$file_array['type']     = $media_array['type'][0];
3816
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3817
				$file_array['error']    = $media_array['error'][0];
3818
				$file_array['size']     = $media_array['size'][0];
3819
3820
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3821
3822
				if ( is_wp_error( $edited_media_item ) ) {
3823
					return $edited_media_item;
3824
				}
3825
3826
				$response = (object) array(
3827
					'id'   => (string) $post_id,
3828
					'file' => (string) $edited_media_item->post_title,
3829
					'url'  => (string) wp_get_attachment_url( $post_id ),
3830
					'type' => (string) $edited_media_item->post_mime_type,
3831
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3832
				);
3833
3834
				return (array) array( $response );
3835
			}
3836
3837
			$attachment_id = media_handle_upload(
3838
				'.jetpack.upload.',
3839
				$post_id,
3840
				array(),
3841
				array(
3842
					'action' => 'jetpack_upload_file',
3843
				)
3844
			);
3845
3846
			if ( ! $attachment_id ) {
3847
				$uploaded_files[ $index ] = (object) array(
3848
					'error'             => 'unknown',
3849
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3850
				);
3851
			} elseif ( is_wp_error( $attachment_id ) ) {
3852
				$uploaded_files[ $index ] = (object) array(
3853
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3854
					'error_description' => $attachment_id->get_error_message(),
3855
				);
3856
			} else {
3857
				$attachment               = get_post( $attachment_id );
3858
				$uploaded_files[ $index ] = (object) array(
3859
					'id'   => (string) $attachment_id,
3860
					'file' => $attachment->post_title,
3861
					'url'  => wp_get_attachment_url( $attachment_id ),
3862
					'type' => $attachment->post_mime_type,
3863
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3864
				);
3865
				// Zip files uploads are not supported unless they are done for installation purposed
3866
				// lets delete them in case something goes wrong in this whole process
3867
				if ( 'application/zip' === $attachment->post_mime_type ) {
3868
					// Schedule a cleanup for 2 hours from now in case of failed install.
3869
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3870
				}
3871
			}
3872
		}
3873
		if ( ! is_null( $global_post ) ) {
3874
			$GLOBALS['post'] = $global_post;
3875
		}
3876
3877
		return $uploaded_files;
3878
	}
3879
3880
	/**
3881
	 * Add help to the Jetpack page
3882
	 *
3883
	 * @since Jetpack (1.2.3)
3884
	 * @return false if not the Jetpack page
3885
	 */
3886
	function admin_help() {
3887
		$current_screen = get_current_screen();
3888
3889
		// Overview
3890
		$current_screen->add_help_tab(
3891
			array(
3892
				'id'      => 'home',
3893
				'title'   => __( 'Home', 'jetpack' ),
3894
				'content' =>
3895
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3896
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3897
					'<p>' . __( 'On this page, you are able to view the modules available within Jetpack, learn more about them, and activate or deactivate them as needed.', 'jetpack' ) . '</p>',
3898
			)
3899
		);
3900
3901
		// Screen Content
3902
		if ( current_user_can( 'manage_options' ) ) {
3903
			$current_screen->add_help_tab(
3904
				array(
3905
					'id'      => 'settings',
3906
					'title'   => __( 'Settings', 'jetpack' ),
3907
					'content' =>
3908
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3909
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3910
						'<ol>' .
3911
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3912
							'<li>' . __( 'Using the checkboxes next to each module, you can select multiple modules to toggle via the Bulk Actions menu at the top of the list.', 'jetpack' ) . '</li>' .
3913
						'</ol>' .
3914
						'<p>' . __( 'Using the tools on the right, you can search for specific modules, filter by module categories or which are active, or change the sorting order.', 'jetpack' ) . '</p>',
3915
				)
3916
			);
3917
		}
3918
3919
		// Help Sidebar
3920
		$support_url = Redirect::get_url( 'jetpack-support' );
3921
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3922
		$current_screen->set_help_sidebar(
3923
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3924
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3925
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3926
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3927
		);
3928
	}
3929
3930
	function admin_menu_css() {
3931
		wp_enqueue_style( 'jetpack-icons' );
3932
	}
3933
3934
	function admin_menu_order() {
3935
		return true;
3936
	}
3937
3938
	function jetpack_menu_order( $menu_order ) {
3939
		$jp_menu_order = array();
3940
3941
		foreach ( $menu_order as $index => $item ) {
3942
			if ( $item != 'jetpack' ) {
3943
				$jp_menu_order[] = $item;
3944
			}
3945
3946
			if ( $index == 0 ) {
3947
				$jp_menu_order[] = 'jetpack';
3948
			}
3949
		}
3950
3951
		return $jp_menu_order;
3952
	}
3953
3954
	function admin_banner_styles() {
3955
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3956
3957 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3958
			wp_register_style(
3959
				'jetpack-dops-style',
3960
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3961
				array(),
3962
				JETPACK__VERSION
3963
			);
3964
		}
3965
3966
		wp_enqueue_style(
3967
			'jetpack',
3968
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3969
			array( 'jetpack-dops-style' ),
3970
			JETPACK__VERSION . '-20121016'
3971
		);
3972
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3973
		wp_style_add_data( 'jetpack', 'suffix', $min );
3974
	}
3975
3976
	function plugin_action_links( $actions ) {
3977
3978
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3979
3980
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
3981
			return array_merge(
3982
				$jetpack_home,
3983
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3984
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3985
				$actions
3986
			);
3987
		}
3988
3989
		return array_merge( $jetpack_home, $actions );
3990
	}
3991
3992
	/**
3993
	 * Adds the deactivation warning modal if there are other active plugins using the connection
3994
	 *
3995
	 * @param string $hook The current admin page.
3996
	 *
3997
	 * @return void
3998
	 */
3999
	public function deactivate_dialog( $hook ) {
4000
		if (
4001
			'plugins.php' === $hook
4002
			&& self::is_active()
4003
		) {
4004
4005
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4006
4007
			if ( count( $active_plugins_using_connection ) > 1 ) {
4008
4009
				add_thickbox();
4010
4011
				wp_register_script(
4012
					'jp-tracks',
4013
					'//stats.wp.com/w.js',
4014
					array(),
4015
					gmdate( 'YW' ),
4016
					true
4017
				);
4018
4019
				wp_register_script(
4020
					'jp-tracks-functions',
4021
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4022
					array( 'jp-tracks' ),
4023
					JETPACK__VERSION,
4024
					false
4025
				);
4026
4027
				wp_enqueue_script(
4028
					'jetpack-deactivate-dialog-js',
4029
					Assets::get_file_url_for_environment(
4030
						'_inc/build/jetpack-deactivate-dialog.min.js',
4031
						'_inc/jetpack-deactivate-dialog.js'
4032
					),
4033
					array( 'jquery', 'jp-tracks-functions' ),
4034
					JETPACK__VERSION,
4035
					true
4036
				);
4037
4038
				wp_localize_script(
4039
					'jetpack-deactivate-dialog-js',
4040
					'deactivate_dialog',
4041
					array(
4042
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4043
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4044
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4045
					)
4046
				);
4047
4048
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4049
4050
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4051
			}
4052
		}
4053
	}
4054
4055
	/**
4056
	 * Outputs the content of the deactivation modal
4057
	 *
4058
	 * @return void
4059
	 */
4060
	public function deactivate_dialog_content() {
4061
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4062
		unset( $active_plugins_using_connection['jetpack'] );
4063
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
Bug introduced by
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4061 can also be of type object<WP_Error>; however, Jetpack::load_view() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4064
	}
4065
4066
	/**
4067
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4068
	 *
4069
	 * @param string $login_url The wp-login URL.
4070
	 * @param string $redirect  URL to redirect users after logging in.
4071
	 * @since Jetpack 8.4
4072
	 * @return string
4073
	 */
4074
	public function login_url( $login_url, $redirect ) {
4075
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4076
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4077
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4078
		}
4079
		return $login_url;
4080
	}
4081
4082
	/**
4083
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4084
	 *
4085
	 * @since Jetpack 8.4
4086
	 */
4087
	public function login_init() {
4088
		// phpcs:ignore WordPress.Security.NonceVerification
4089
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4090
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4091
			wp_safe_redirect(
4092
				add_query_arg(
4093
					array(
4094
						'forceInstall' => 1,
4095
						'url'          => rawurlencode( get_site_url() ),
4096
					),
4097
					// @todo provide way to go to specific calypso env.
4098
					self::get_calypso_host() . 'jetpack/connect'
4099
				)
4100
			);
4101
			exit;
4102
		}
4103
	}
4104
4105
	/*
4106
	 * Registration flow:
4107
	 * 1 - ::admin_page_load() action=register
4108
	 * 2 - ::try_registration()
4109
	 * 3 - ::register()
4110
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4111
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4112
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4113
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4114
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4115
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4116
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4117
	 *       jetpack_id, jetpack_secret, jetpack_public
4118
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4119
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4120
	 * 5 - user logs in with WP.com account
4121
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4122
	 *		- Manager::authorize()
4123
	 *		- Manager::get_token()
4124
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4125
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4126
	 *			- which responds with access_token, token_type, scope
4127
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4128
	 *		- Jetpack::activate_default_modules()
4129
	 *     		- Deactivates deprecated plugins
4130
	 *     		- Activates all default modules
4131
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4132
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4133
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4134
	 *     Done!
4135
	 */
4136
4137
	/**
4138
	 * Handles the page load events for the Jetpack admin page
4139
	 */
4140
	function admin_page_load() {
4141
		$error = false;
4142
4143
		// Make sure we have the right body class to hook stylings for subpages off of.
4144
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4145
4146
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4147
			// Should only be used in intermediate redirects to preserve state across redirects
4148
			self::restate();
4149
		}
4150
4151
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4152
			// @todo: Add validation against a known allowed list.
4153
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4154
			// User clicked in the iframe to link their accounts
4155
			if ( ! self::is_user_connected() ) {
4156
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4157
4158
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4159
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4160
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4161
4162
				if ( isset( $_GET['notes_iframe'] ) ) {
4163
					$connect_url .= '&notes_iframe';
4164
				}
4165
				wp_redirect( $connect_url );
4166
				exit;
4167
			} else {
4168
				if ( ! isset( $_GET['calypso_env'] ) ) {
4169
					self::state( 'message', 'already_authorized' );
4170
					wp_safe_redirect( self::admin_url() );
4171
					exit;
4172
				} else {
4173
					$connect_url  = $this->build_connect_url( true, false, $from );
4174
					$connect_url .= '&already_authorized=true';
4175
					wp_redirect( $connect_url );
4176
					exit;
4177
				}
4178
			}
4179
		}
4180
4181
		if ( isset( $_GET['action'] ) ) {
4182
			switch ( $_GET['action'] ) {
4183
				case 'authorize':
4184
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4185
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4186
					exit;
4187
				case 'register':
4188
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4189
						$error = 'cheatin';
4190
						break;
4191
					}
4192
					check_admin_referer( 'jetpack-register' );
4193
					self::log( 'register' );
4194
					self::maybe_set_version_option();
4195
					$registered = self::try_registration();
4196
					if ( is_wp_error( $registered ) ) {
4197
						$error = $registered->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4198
						self::state( 'error', $error );
4199
						self::state( 'error', $registered->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4200
4201
						/**
4202
						 * Jetpack registration Error.
4203
						 *
4204
						 * @since 7.5.0
4205
						 *
4206
						 * @param string|int $error The error code.
4207
						 * @param \WP_Error $registered The error object.
4208
						 */
4209
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4210
						break;
4211
					}
4212
4213
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4214
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4215
4216
					/**
4217
					 * Jetpack registration Success.
4218
					 *
4219
					 * @since 7.5.0
4220
					 *
4221
					 * @param string $from 'from' GET parameter;
4222
					 */
4223
					do_action( 'jetpack_connection_register_success', $from );
4224
4225
					$url = $this->build_connect_url( true, $redirect, $from );
4226
4227
					if ( ! empty( $_GET['onboarding'] ) ) {
4228
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4229
					}
4230
4231
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4232
						$url = add_query_arg( 'auth_approved', 'true', $url );
4233
					}
4234
4235
					wp_redirect( $url );
4236
					exit;
4237
				case 'activate':
4238
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4239
						$error = 'cheatin';
4240
						break;
4241
					}
4242
4243
					$module = stripslashes( $_GET['module'] );
4244
					check_admin_referer( "jetpack_activate-$module" );
4245
					self::log( 'activate', $module );
4246
					if ( ! self::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::activate_module($module) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
4247
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4248
					}
4249
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4250
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4251
					exit;
4252
				case 'activate_default_modules':
4253
					check_admin_referer( 'activate_default_modules' );
4254
					self::log( 'activate_default_modules' );
4255
					self::restate();
4256
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4257
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4258
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4259
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4260
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4261
					exit;
4262
				case 'disconnect':
4263
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4264
						$error = 'cheatin';
4265
						break;
4266
					}
4267
4268
					check_admin_referer( 'jetpack-disconnect' );
4269
					self::log( 'disconnect' );
4270
					self::disconnect();
4271
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4272
					exit;
4273
				case 'reconnect':
4274
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4275
						$error = 'cheatin';
4276
						break;
4277
					}
4278
4279
					check_admin_referer( 'jetpack-reconnect' );
4280
					self::log( 'reconnect' );
4281
					$this->disconnect();
4282
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4283
					exit;
4284 View Code Duplication
				case 'deactivate':
4285
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4286
						$error = 'cheatin';
4287
						break;
4288
					}
4289
4290
					$modules = stripslashes( $_GET['module'] );
4291
					check_admin_referer( "jetpack_deactivate-$modules" );
4292
					foreach ( explode( ',', $modules ) as $module ) {
4293
						self::log( 'deactivate', $module );
4294
						self::deactivate_module( $module );
4295
						self::state( 'message', 'module_deactivated' );
4296
					}
4297
					self::state( 'module', $modules );
4298
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4299
					exit;
4300
				case 'unlink':
4301
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4302
					check_admin_referer( 'jetpack-unlink' );
4303
					self::log( 'unlink' );
4304
					Connection_Manager::disconnect_user();
4305
					self::state( 'message', 'unlinked' );
4306
					if ( 'sub-unlink' == $redirect ) {
4307
						wp_safe_redirect( admin_url() );
4308
					} else {
4309
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4310
					}
4311
					exit;
4312
				case 'onboard':
4313
					if ( ! current_user_can( 'manage_options' ) ) {
4314
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4315
					} else {
4316
						self::create_onboarding_token();
4317
						$url = $this->build_connect_url( true );
4318
4319
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4320
							$url = add_query_arg( 'onboarding', $token, $url );
4321
						}
4322
4323
						$calypso_env = $this->get_calypso_env();
4324
						if ( ! empty( $calypso_env ) ) {
4325
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4326
						}
4327
4328
						wp_redirect( $url );
4329
						exit;
4330
					}
4331
					exit;
4332
				default:
4333
					/**
4334
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4335
					 *
4336
					 * @since 2.6.0
4337
					 *
4338
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4339
					 */
4340
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4341
			}
4342
		}
4343
4344
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4345
			self::activate_new_modules( true );
4346
		}
4347
4348
		$message_code = self::state( 'message' );
4349
		if ( self::state( 'optin-manage' ) ) {
4350
			$activated_manage = $message_code;
4351
			$message_code     = 'jetpack-manage';
4352
		}
4353
4354
		switch ( $message_code ) {
4355
			case 'jetpack-manage':
4356
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4357
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4358
				$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>';
4359
				if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4360
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4361
				}
4362
				break;
4363
4364
		}
4365
4366
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4367
4368
		if ( ! empty( $deactivated_plugins ) ) {
4369
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4370
			$deactivated_titles  = array();
4371
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4372
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4373
					continue;
4374
				}
4375
4376
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4377
			}
4378
4379
			if ( $deactivated_titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated_titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
4380
				if ( $this->message ) {
4381
					$this->message .= "<br /><br />\n";
4382
				}
4383
4384
				$this->message .= wp_sprintf(
4385
					_n(
4386
						'Jetpack contains the most recent version of the old %l plugin.',
4387
						'Jetpack contains the most recent versions of the old %l plugins.',
4388
						count( $deactivated_titles ),
4389
						'jetpack'
4390
					),
4391
					$deactivated_titles
4392
				);
4393
4394
				$this->message .= "<br />\n";
4395
4396
				$this->message .= _n(
4397
					'The old version has been deactivated and can be removed from your site.',
4398
					'The old versions have been deactivated and can be removed from your site.',
4399
					count( $deactivated_titles ),
4400
					'jetpack'
4401
				);
4402
			}
4403
		}
4404
4405
		$this->privacy_checks = self::state( 'privacy_checks' );
4406
4407
		if ( $this->message || $this->error || $this->privacy_checks ) {
4408
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4409
		}
4410
4411
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4412
	}
4413
4414
	function admin_notices() {
4415
4416
		if ( $this->error ) {
4417
			?>
4418
<div id="message" class="jetpack-message jetpack-err">
4419
	<div class="squeezer">
4420
		<h2>
4421
			<?php
4422
			echo wp_kses(
4423
				$this->error,
4424
				array(
4425
					'a'      => array( 'href' => array() ),
4426
					'small'  => true,
4427
					'code'   => true,
4428
					'strong' => true,
4429
					'br'     => true,
4430
					'b'      => true,
4431
				)
4432
			);
4433
			?>
4434
			</h2>
4435
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4436
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4437
<?php	endif; ?>
4438
	</div>
4439
</div>
4440
			<?php
4441
		}
4442
4443
		if ( $this->message ) {
4444
			?>
4445
<div id="message" class="jetpack-message">
4446
	<div class="squeezer">
4447
		<h2>
4448
			<?php
4449
			echo wp_kses(
4450
				$this->message,
4451
				array(
4452
					'strong' => array(),
4453
					'a'      => array( 'href' => true ),
4454
					'br'     => true,
4455
				)
4456
			);
4457
			?>
4458
			</h2>
4459
	</div>
4460
</div>
4461
			<?php
4462
		}
4463
4464
		if ( $this->privacy_checks ) :
4465
			$module_names = $module_slugs = array();
4466
4467
			$privacy_checks = explode( ',', $this->privacy_checks );
4468
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4469
			foreach ( $privacy_checks as $module_slug ) {
4470
				$module = self::get_module( $module_slug );
4471
				if ( ! $module ) {
4472
					continue;
4473
				}
4474
4475
				$module_slugs[] = $module_slug;
4476
				$module_names[] = "<strong>{$module['name']}</strong>";
4477
			}
4478
4479
			$module_slugs = join( ',', $module_slugs );
4480
			?>
4481
<div id="message" class="jetpack-message jetpack-err">
4482
	<div class="squeezer">
4483
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4484
		<p>
4485
			<?php
4486
			echo wp_kses(
4487
				wptexturize(
4488
					wp_sprintf(
4489
						_nx(
4490
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4491
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4492
							count( $privacy_checks ),
4493
							'%l = list of Jetpack module/feature names',
4494
							'jetpack'
4495
						),
4496
						$module_names
4497
					)
4498
				),
4499
				array( 'strong' => true )
4500
			);
4501
4502
			echo "\n<br />\n";
4503
4504
			echo wp_kses(
4505
				sprintf(
4506
					_nx(
4507
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4508
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4509
						count( $privacy_checks ),
4510
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4511
						'jetpack'
4512
					),
4513
					wp_nonce_url(
4514
						self::admin_url(
4515
							array(
4516
								'page'   => 'jetpack',
4517
								'action' => 'deactivate',
4518
								'module' => urlencode( $module_slugs ),
4519
							)
4520
						),
4521
						"jetpack_deactivate-$module_slugs"
4522
					),
4523
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4524
				),
4525
				array(
4526
					'a' => array(
4527
						'href'  => true,
4528
						'title' => true,
4529
					),
4530
				)
4531
			);
4532
			?>
4533
		</p>
4534
	</div>
4535
</div>
4536
			<?php
4537
endif;
4538
	}
4539
4540
	/**
4541
	 * We can't always respond to a signed XML-RPC request with a
4542
	 * helpful error message. In some circumstances, doing so could
4543
	 * leak information.
4544
	 *
4545
	 * Instead, track that the error occurred via a Jetpack_Option,
4546
	 * and send that data back in the heartbeat.
4547
	 * All this does is increment a number, but it's enough to find
4548
	 * trends.
4549
	 *
4550
	 * @param WP_Error $xmlrpc_error The error produced during
4551
	 *                               signature validation.
4552
	 */
4553
	function track_xmlrpc_error( $xmlrpc_error ) {
4554
		$code = is_wp_error( $xmlrpc_error )
4555
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4556
			: 'should-not-happen';
4557
4558
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4559
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4560
			// No need to update the option if we already have
4561
			// this code stored.
4562
			return;
4563
		}
4564
		$xmlrpc_errors[ $code ] = true;
4565
4566
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4567
	}
4568
4569
	/**
4570
	 * Initialize the jetpack stats instance only when needed
4571
	 *
4572
	 * @return void
4573
	 */
4574
	private function initialize_stats() {
4575
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4576
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4577
		}
4578
	}
4579
4580
	/**
4581
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4582
	 */
4583
	function stat( $group, $detail ) {
4584
		$this->initialize_stats();
4585
		$this->a8c_mc_stats_instance->add( $group, $detail );
4586
4587
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4588
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4589
	}
4590
4591
	/**
4592
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4593
	 */
4594
	function do_stats( $method = '' ) {
4595
		$this->initialize_stats();
4596
		if ( 'server_side' === $method ) {
4597
			$this->a8c_mc_stats_instance->do_server_side_stats();
4598
		} else {
4599
			$this->a8c_mc_stats_instance->do_stats();
4600
		}
4601
4602
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4603
		$this->stats = array();
4604
	}
4605
4606
	/**
4607
	 * Runs stats code for a one-off, server-side.
4608
	 *
4609
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4610
	 *
4611
	 * @return bool If it worked.
4612
	 */
4613
	static function do_server_side_stat( $args ) {
4614
		$url                   = self::build_stats_url( $args );
4615
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4616
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4617
	}
4618
4619
	/**
4620
	 * Builds the stats url.
4621
	 *
4622
	 * @param $args array|string The arguments to append to the URL.
4623
	 *
4624
	 * @return string The URL to be pinged.
4625
	 */
4626
	static function build_stats_url( $args ) {
4627
4628
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4629
		return $a8c_mc_stats_instance->build_stats_url( $args );
4630
4631
	}
4632
4633
	/**
4634
	 * Get the role of the current user.
4635
	 *
4636
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4637
	 *
4638
	 * @access public
4639
	 * @static
4640
	 *
4641
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4642
	 */
4643
	public static function translate_current_user_to_role() {
4644
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4645
4646
		$roles = new Roles();
4647
		return $roles->translate_current_user_to_role();
4648
	}
4649
4650
	/**
4651
	 * Get the role of a particular user.
4652
	 *
4653
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4654
	 *
4655
	 * @access public
4656
	 * @static
4657
	 *
4658
	 * @param \WP_User $user User object.
4659
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4660
	 */
4661
	public static function translate_user_to_role( $user ) {
4662
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4663
4664
		$roles = new Roles();
4665
		return $roles->translate_user_to_role( $user );
4666
	}
4667
4668
	/**
4669
	 * Get the minimum capability for a role.
4670
	 *
4671
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4672
	 *
4673
	 * @access public
4674
	 * @static
4675
	 *
4676
	 * @param string $role Role name.
4677
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4678
	 */
4679
	public static function translate_role_to_cap( $role ) {
4680
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4681
4682
		$roles = new Roles();
4683
		return $roles->translate_role_to_cap( $role );
4684
	}
4685
4686
	/**
4687
	 * Sign a user role with the master access token.
4688
	 * If not specified, will default to the current user.
4689
	 *
4690
	 * @deprecated since 7.7
4691
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4692
	 *
4693
	 * @access public
4694
	 * @static
4695
	 *
4696
	 * @param string $role    User role.
4697
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
4698
	 * @return string Signed user role.
4699
	 */
4700
	public static function sign_role( $role, $user_id = null ) {
4701
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4702
		return self::connection()->sign_role( $role, $user_id );
4703
	}
4704
4705
	/**
4706
	 * Builds a URL to the Jetpack connection auth page
4707
	 *
4708
	 * @since 3.9.5
4709
	 *
4710
	 * @param bool        $raw If true, URL will not be escaped.
4711
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4712
	 *                              If string, will be a custom redirect.
4713
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4714
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4715
	 *
4716
	 * @return string Connect URL
4717
	 */
4718
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4719
		$site_id    = Jetpack_Options::get_option( 'id' );
4720
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4721
4722
		if ( $register || ! $blog_token || ! $site_id ) {
4723
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4724
4725
			if ( ! empty( $redirect ) ) {
4726
				$url = add_query_arg(
4727
					'redirect',
4728
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4729
					$url
4730
				);
4731
			}
4732
4733
			if ( is_network_admin() ) {
4734
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4735
			}
4736
4737
			$calypso_env = self::get_calypso_env();
4738
4739
			if ( ! empty( $calypso_env ) ) {
4740
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4741
			}
4742
		} else {
4743
4744
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4745
			// because otherwise this logic can get us in to a loop.
4746
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4747
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4748
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4749
4750
				$response = Client::wpcom_json_api_request_as_blog(
4751
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4752
					'1.1'
4753
				);
4754
4755
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4756
4757
					// Generating a register URL instead to refresh the existing token
4758
					return $this->build_connect_url( $raw, $redirect, $from, true );
4759
				}
4760
			}
4761
4762
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4718 can also be of type string; however, Jetpack::build_authorize_url() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
4763
		}
4764
4765
		if ( $from ) {
4766
			$url = add_query_arg( 'from', $from, $url );
4767
		}
4768
4769
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4770
		/**
4771
		 * Filter the URL used when connecting a user to a WordPress.com account.
4772
		 *
4773
		 * @since 8.1.0
4774
		 *
4775
		 * @param string $url Connection URL.
4776
		 * @param bool   $raw If true, URL will not be escaped.
4777
		 */
4778
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $raw.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4779
	}
4780
4781
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4782
4783
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4784
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4785
4786
		if ( $iframe ) {
4787
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4788
		}
4789
4790
		$c8n = self::connection();
4791
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
Documentation introduced by
$redirect is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4792
4793
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4794
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4795
4796
		if ( $iframe ) {
4797
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4798
		}
4799
4800
		/**
4801
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4802
		 *
4803
		 * @since 8.9.0
4804
		 *
4805
		 * @param string $url Connection URL.
4806
		 */
4807
		return apply_filters( 'jetpack_build_authorize_url', $url );
4808
	}
4809
4810
	/**
4811
	 * Filters the connection URL parameter array.
4812
	 *
4813
	 * @param array $args default URL parameters used by the package.
4814
	 * @return array the modified URL arguments array.
4815
	 */
4816
	public static function filter_connect_request_body( $args ) {
4817
		if (
4818
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4819
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4820
		) {
4821
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4822
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4823
				? $gp_locale->slug
4824
				: '';
4825
		}
4826
4827
		$tracking        = new Tracking();
4828
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4829
4830
		$args = array_merge(
4831
			$args,
4832
			array(
4833
				'_ui' => $tracks_identity['_ui'],
4834
				'_ut' => $tracks_identity['_ut'],
4835
			)
4836
		);
4837
4838
		$calypso_env = self::get_calypso_env();
4839
4840
		if ( ! empty( $calypso_env ) ) {
4841
			$args['calypso_env'] = $calypso_env;
4842
		}
4843
4844
		return $args;
4845
	}
4846
4847
	/**
4848
	 * Filters the URL that will process the connection data. It can be different from the URL
4849
	 * that we send the user to after everything is done.
4850
	 *
4851
	 * @param String $processing_url the default redirect URL used by the package.
4852
	 * @return String the modified URL.
4853
	 *
4854
	 * @deprecated since Jetpack 9.5.0
4855
	 */
4856
	public static function filter_connect_processing_url( $processing_url ) {
4857
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4858
4859
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4860
		return $processing_url;
4861
	}
4862
4863
	/**
4864
	 * Filters the redirection URL that is used for connect requests. The redirect
4865
	 * URL should return the user back to the Jetpack console.
4866
	 *
4867
	 * @param String $redirect the default redirect URL used by the package.
4868
	 * @return String the modified URL.
4869
	 */
4870
	public static function filter_connect_redirect_url( $redirect ) {
4871
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4872
		$redirect           = $redirect
4873
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4874
			: $jetpack_admin_page;
4875
4876
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4877
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4878
		}
4879
4880
		return $redirect;
4881
	}
4882
4883
	/**
4884
	 * This action fires at the beginning of the Manager::authorize method.
4885
	 */
4886
	public static function authorize_starting() {
4887
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4888
		// Checking if site has been active/connected previously before recording unique connection.
4889
		if ( ! $jetpack_unique_connection ) {
4890
			// jetpack_unique_connection option has never been set.
4891
			$jetpack_unique_connection = array(
4892
				'connected'    => 0,
4893
				'disconnected' => 0,
4894
				'version'      => '3.6.1',
4895
			);
4896
4897
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4898
4899
			// Track unique connection.
4900
			$jetpack = self::init();
4901
4902
			$jetpack->stat( 'connections', 'unique-connection' );
4903
			$jetpack->do_stats( 'server_side' );
4904
		}
4905
4906
		// Increment number of times connected.
4907
		$jetpack_unique_connection['connected'] += 1;
4908
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4909
	}
4910
4911
	/**
4912
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4913
	 * linked.
4914
	 */
4915
	public static function authorize_ending_linked() {
4916
		// Don't activate anything since we are just connecting a user.
4917
		self::state( 'message', 'linked' );
4918
	}
4919
4920
	/**
4921
	 * This action fires at the end of the Manager::authorize method when the master user is
4922
	 * authorized.
4923
	 *
4924
	 * @param array $data The request data.
4925
	 */
4926
	public static function authorize_ending_authorized( $data ) {
4927
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4928
		self::invalidate_onboarding_token();
4929
4930
		// If redirect_uri is SSO, ensure SSO module is enabled.
4931
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4932
4933
		/** This filter is documented in class.jetpack-cli.php */
4934
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4935
4936
		$activate_sso = (
4937
			isset( $redirect_options['action'] ) &&
4938
			'jetpack-sso' === $redirect_options['action'] &&
4939
			$jetpack_start_enable_sso
4940
		);
4941
4942
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4943
4944
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4945
	}
4946
4947
	/**
4948
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
4949
	 * reconnect process is completed.
4950
	 * Note that this currently only happens when we don't need the user to re-authorize
4951
	 * their WP.com account, eg in cases where we are restoring a connection with
4952
	 * unhealthy blog token.
4953
	 */
4954
	public static function reconnection_completed() {
4955
		self::state( 'message', 'reconnection_completed' );
4956
	}
4957
4958
	/**
4959
	 * Get our assumed site creation date.
4960
	 * Calculated based on the earlier date of either:
4961
	 * - Earliest admin user registration date.
4962
	 * - Earliest date of post of any post type.
4963
	 *
4964
	 * @since 7.2.0
4965
	 * @deprecated since 7.8.0
4966
	 *
4967
	 * @return string Assumed site creation date and time.
4968
	 */
4969
	public static function get_assumed_site_creation_date() {
4970
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4971
		return self::connection()->get_assumed_site_creation_date();
4972
	}
4973
4974 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4975
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4976
4977
		if ( $activation_source_name ) {
4978
			$args['_as'] = urlencode( $activation_source_name );
4979
		}
4980
4981
		if ( $activation_source_keyword ) {
4982
			$args['_ak'] = urlencode( $activation_source_keyword );
4983
		}
4984
	}
4985
4986
	function build_reconnect_url( $raw = false ) {
4987
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4988
		return $raw ? $url : esc_url( $url );
4989
	}
4990
4991
	public static function admin_url( $args = null ) {
4992
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
Documentation introduced by
array('page' => 'jetpack') is of type array<string,string,{"page":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4993
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4994
		return $url;
4995
	}
4996
4997
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4998
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4999
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5000
	}
5001
5002
	function dismiss_jetpack_notice() {
5003
5004
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5005
			return;
5006
		}
5007
5008
		switch ( $_GET['jetpack-notice'] ) {
5009
			case 'dismiss':
5010
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5011
5012
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5013
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5014
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5015
				}
5016
				break;
5017
		}
5018
	}
5019
5020
	public static function sort_modules( $a, $b ) {
5021
		if ( $a['sort'] == $b['sort'] ) {
5022
			return 0;
5023
		}
5024
5025
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5026
	}
5027
5028
	function ajax_recheck_ssl() {
5029
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5030
		$result = self::permit_ssl( true );
5031
		wp_send_json(
5032
			array(
5033
				'enabled' => $result,
5034
				'message' => get_transient( 'jetpack_https_test_message' ),
5035
			)
5036
		);
5037
	}
5038
5039
	/* Client API */
5040
5041
	/**
5042
	 * Returns the requested Jetpack API URL
5043
	 *
5044
	 * @deprecated since 7.7
5045
	 * @return string
5046
	 */
5047
	public static function api_url( $relative_url ) {
5048
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5049
		$connection = self::connection();
5050
		return $connection->api_url( $relative_url );
5051
	}
5052
5053
	/**
5054
	 * @deprecated 8.0
5055
	 *
5056
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5057
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5058
	 */
5059
	public static function fix_url_for_bad_hosts( $url ) {
5060
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5061
		return $url;
5062
	}
5063
5064
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5065
		// Default to a blog token.
5066
		$token_type = 'blog';
5067
5068
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5069
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5070
			if ( ! empty( $_GET['onboarding'] ) ) {
5071
				$jpo = $_GET;
5072
			} else {
5073
				$jpo = json_decode( $request_data, true );
5074
			}
5075
5076
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5077
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5078
5079
			if (
5080
				isset( $jpo_user )
5081
				&& isset( $jpo_token )
5082
				&& is_email( $jpo_user )
5083
				&& ctype_alnum( $jpo_token )
5084
				&& isset( $_GET['rest_route'] )
5085
				&& self::validate_onboarding_token_action(
5086
					$jpo_token,
5087
					$_GET['rest_route']
5088
				)
5089
			) {
5090
				$jp_user = get_user_by( 'email', $jpo_user );
5091
				if ( is_a( $jp_user, 'WP_User' ) ) {
5092
					wp_set_current_user( $jp_user->ID );
5093
					$user_can = is_multisite()
5094
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5095
						: current_user_can( 'manage_options' );
5096
					if ( $user_can ) {
5097
						$token_type              = 'user';
5098
						$token->external_user_id = $jp_user->ID;
5099
					}
5100
				}
5101
			}
5102
5103
			$token_data['type']    = $token_type;
5104
			$token_data['user_id'] = $token->external_user_id;
5105
		}
5106
5107
		return $token_data;
5108
	}
5109
5110
	/**
5111
	 * Create a random secret for validating onboarding payload
5112
	 *
5113
	 * @return string Secret token
5114
	 */
5115
	public static function create_onboarding_token() {
5116
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5117
			$token = wp_generate_password( 32, false );
5118
			Jetpack_Options::update_option( 'onboarding', $token );
5119
		}
5120
5121
		return $token;
5122
	}
5123
5124
	/**
5125
	 * Remove the onboarding token
5126
	 *
5127
	 * @return bool True on success, false on failure
5128
	 */
5129
	public static function invalidate_onboarding_token() {
5130
		return Jetpack_Options::delete_option( 'onboarding' );
5131
	}
5132
5133
	/**
5134
	 * Validate an onboarding token for a specific action
5135
	 *
5136
	 * @return boolean True if token/action pair is accepted, false if not
5137
	 */
5138
	public static function validate_onboarding_token_action( $token, $action ) {
5139
		// Compare tokens, bail if tokens do not match
5140
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5141
			return false;
5142
		}
5143
5144
		// List of valid actions we can take
5145
		$valid_actions = array(
5146
			'/jetpack/v4/settings',
5147
		);
5148
5149
		// Only allow valid actions.
5150
		if ( ! in_array( $action, $valid_actions ) ) {
5151
			return false;
5152
		}
5153
5154
		return true;
5155
	}
5156
5157
	/**
5158
	 * Checks to see if the URL is using SSL to connect with Jetpack
5159
	 *
5160
	 * @since 2.3.3
5161
	 * @return boolean
5162
	 */
5163
	public static function permit_ssl( $force_recheck = false ) {
5164
		// Do some fancy tests to see if ssl is being supported
5165
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5166
			$message = '';
5167
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5168
				$ssl = 0;
5169
			} else {
5170
				$ssl = 1;
5171
5172
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5173
					$ssl     = 0;
5174
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5175
				} else {
5176
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5177
					if ( is_wp_error( $response ) ) {
5178
						$ssl     = 0;
5179
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5180
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5181
						$ssl     = 0;
5182
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5183
					}
5184
				}
5185
			}
5186
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5187
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5188
		}
5189
5190
		return (bool) $ssl;
5191
	}
5192
5193
	/*
5194
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5195
	 */
5196
	public function alert_auto_ssl_fail() {
5197
		if ( ! current_user_can( 'manage_options' ) ) {
5198
			return;
5199
		}
5200
5201
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5202
		?>
5203
5204
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5205
			<div class="jp-banner__content">
5206
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5207
				<p><?php _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>
5208
				<p>
5209
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5210
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5211
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5212
				</p>
5213
				<p>
5214
					<?php
5215
					printf(
5216
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5217
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5218
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5219
					);
5220
					?>
5221
				</p>
5222
			</div>
5223
		</div>
5224
		<style>
5225
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5226
		</style>
5227
		<script type="text/javascript">
5228
			jQuery( document ).ready( function( $ ) {
5229
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5230
					var $this = $( this );
5231
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5232
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5233
					e.preventDefault();
5234
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5235
					$.post( ajaxurl, data )
5236
					  .done( function( response ) {
5237
						  if ( response.enabled ) {
5238
							  $( '#jetpack-ssl-warning' ).hide();
5239
						  } else {
5240
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5241
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5242
						  }
5243
					  }.bind( $this ) );
5244
				} );
5245
			} );
5246
		</script>
5247
5248
		<?php
5249
	}
5250
5251
	/**
5252
	 * Returns the Jetpack XML-RPC API
5253
	 *
5254
	 * @deprecated 8.0 Use Connection_Manager instead.
5255
	 * @return string
5256
	 */
5257
	public static function xmlrpc_api_url() {
5258
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5259
		return self::connection()->xmlrpc_api_url();
5260
	}
5261
5262
	/**
5263
	 * Returns the connection manager object.
5264
	 *
5265
	 * @return Automattic\Jetpack\Connection\Manager
5266
	 */
5267
	public static function connection() {
5268
		$jetpack = static::init();
5269
5270
		// If the connection manager hasn't been instantiated, do that now.
5271
		if ( ! $jetpack->connection_manager ) {
5272
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5273
		}
5274
5275
		return $jetpack->connection_manager;
5276
	}
5277
5278
	/**
5279
	 * Creates two secret tokens and the end of life timestamp for them.
5280
	 *
5281
	 * Note these tokens are unique per call, NOT static per site for connecting.
5282
	 *
5283
	 * @since 2.6
5284
	 * @param String  $action  The action name.
5285
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be false|integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5286
	 * @param Integer $exp     Expiration time in seconds.
5287
	 * @return array
5288
	 */
5289
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5290
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5291
	}
5292
5293
	public static function get_secrets( $action, $user_id ) {
5294
		$secrets = self::connection()->get_secrets( $action, $user_id );
5295
5296
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5297
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5298
		}
5299
5300
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5301
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5302
		}
5303
5304
		return $secrets;
5305
	}
5306
5307
	/**
5308
	 * @deprecated 7.5 Use Connection_Manager instead.
5309
	 *
5310
	 * @param $action
5311
	 * @param $user_id
5312
	 */
5313
	public static function delete_secrets( $action, $user_id ) {
5314
		return self::connection()->delete_secrets( $action, $user_id );
5315
	}
5316
5317
	/**
5318
	 * Builds the timeout limit for queries talking with the wpcom servers.
5319
	 *
5320
	 * Based on local php max_execution_time in php.ini
5321
	 *
5322
	 * @since 2.6
5323
	 * @return int
5324
	 * @deprecated
5325
	 **/
5326
	public function get_remote_query_timeout_limit() {
5327
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5328
		return self::get_max_execution_time();
5329
	}
5330
5331
	/**
5332
	 * Builds the timeout limit for queries talking with the wpcom servers.
5333
	 *
5334
	 * Based on local php max_execution_time in php.ini
5335
	 *
5336
	 * @since 5.4
5337
	 * @return int
5338
	 **/
5339
	public static function get_max_execution_time() {
5340
		$timeout = (int) ini_get( 'max_execution_time' );
5341
5342
		// Ensure exec time set in php.ini
5343
		if ( ! $timeout ) {
5344
			$timeout = 30;
5345
		}
5346
		return $timeout;
5347
	}
5348
5349
	/**
5350
	 * Sets a minimum request timeout, and returns the current timeout
5351
	 *
5352
	 * @since 5.4
5353
	 **/
5354 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5355
		$timeout = self::get_max_execution_time();
5356
		if ( $timeout < $min_timeout ) {
5357
			$timeout = $min_timeout;
5358
			set_time_limit( $timeout );
5359
		}
5360
		return $timeout;
5361
	}
5362
5363
	/**
5364
	 * Takes the response from the Jetpack register new site endpoint and
5365
	 * verifies it worked properly.
5366
	 *
5367
	 * @since 2.6
5368
	 * @deprecated since 7.7.0
5369
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5370
	 **/
5371
	public function validate_remote_register_response() {
5372
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5373
	}
5374
5375
	/**
5376
	 * @return bool|WP_Error
5377
	 */
5378
	public static function register() {
5379
		$tracking = new Tracking();
5380
		$tracking->record_user_event( 'jpc_register_begin' );
5381
5382
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5383
5384
		$connection   = self::connection();
5385
		$registration = $connection->register();
5386
5387
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5388
5389
		if ( ! $registration || is_wp_error( $registration ) ) {
5390
			return $registration;
5391
		}
5392
5393
		return true;
5394
	}
5395
5396
	/**
5397
	 * Filters the registration request body to include tracking properties.
5398
	 *
5399
	 * @param array $properties
5400
	 * @return array amended properties.
5401
	 */
5402 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5403
		$tracking        = new Tracking();
5404
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5405
5406
		return array_merge(
5407
			$properties,
5408
			array(
5409
				'_ui' => $tracks_identity['_ui'],
5410
				'_ut' => $tracks_identity['_ut'],
5411
			)
5412
		);
5413
	}
5414
5415
	/**
5416
	 * Filters the token request body to include tracking properties.
5417
	 *
5418
	 * @param array $properties
5419
	 * @return array amended properties.
5420
	 */
5421 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5422
		$tracking        = new Tracking();
5423
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5424
5425
		return array_merge(
5426
			$properties,
5427
			array(
5428
				'_ui' => $tracks_identity['_ui'],
5429
				'_ut' => $tracks_identity['_ut'],
5430
			)
5431
		);
5432
	}
5433
5434
	/**
5435
	 * If the db version is showing something other that what we've got now, bump it to current.
5436
	 *
5437
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
5438
	 */
5439
	public static function maybe_set_version_option() {
5440
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5441
		if ( JETPACK__VERSION != $version ) {
5442
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5443
5444
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5445
				/** This action is documented in class.jetpack.php */
5446
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5447
			}
5448
5449
			return true;
5450
		}
5451
		return false;
5452
	}
5453
5454
	/* Client Server API */
5455
5456
	/**
5457
	 * Loads the Jetpack XML-RPC client.
5458
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5459
	 *
5460
	 * @deprecated since 7.7.0
5461
	 */
5462
	public static function load_xml_rpc_client() {
5463
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5464
	}
5465
5466
	/**
5467
	 * Resets the saved authentication state in between testing requests.
5468
	 *
5469
	 * @deprecated since 8.9.0
5470
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5471
	 */
5472
	public function reset_saved_auth_state() {
5473
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5474
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5475
	}
5476
5477
	/**
5478
	 * Verifies the signature of the current request.
5479
	 *
5480
	 * @deprecated since 7.7.0
5481
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5482
	 *
5483
	 * @return false|array
5484
	 */
5485
	public function verify_xml_rpc_signature() {
5486
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5487
		return self::connection()->verify_xml_rpc_signature();
5488
	}
5489
5490
	/**
5491
	 * Verifies the signature of the current request.
5492
	 *
5493
	 * This function has side effects and should not be used. Instead,
5494
	 * use the memoized version `->verify_xml_rpc_signature()`.
5495
	 *
5496
	 * @deprecated since 7.7.0
5497
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5498
	 * @internal
5499
	 */
5500
	private function internal_verify_xml_rpc_signature() {
5501
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5502
	}
5503
5504
	/**
5505
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5506
	 *
5507
	 * @deprecated since 7.7.0
5508
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5509
	 *
5510
	 * @param \WP_User|mixed $user     User object if authenticated.
5511
	 * @param string         $username Username.
5512
	 * @param string         $password Password string.
5513
	 * @return \WP_User|mixed Authenticated user or error.
5514
	 */
5515 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5516
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5517
5518
		if ( ! $this->connection_manager ) {
5519
			$this->connection_manager = new Connection_Manager();
5520
		}
5521
5522
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5523
	}
5524
5525
	/**
5526
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5527
	 * Uses the existing XMLRPC request signing implementation.
5528
	 *
5529
	 * @deprecated since 8.9.0
5530
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5531
	 */
5532
	function wp_rest_authenticate( $user ) {
5533
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5534
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5535
	}
5536
5537
	/**
5538
	 * Report authentication status to the WP REST API.
5539
	 *
5540
	 * @deprecated since 8.9.0
5541
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5542
	 *
5543
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
5544
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5545
	 */
5546
	public function wp_rest_authentication_errors( $value ) {
5547
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5548
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5549
	}
5550
5551
	/**
5552
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5553
	 * Capture it here so we can verify the signature later.
5554
	 *
5555
	 * @deprecated since 7.7.0
5556
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5557
	 *
5558
	 * @param array $methods XMLRPC methods.
5559
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5560
	 */
5561 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5562
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5563
5564
		if ( ! $this->connection_manager ) {
5565
			$this->connection_manager = new Connection_Manager();
5566
		}
5567
5568
		return $this->connection_manager->xmlrpc_methods( $methods );
5569
	}
5570
5571
	/**
5572
	 * Register additional public XMLRPC methods.
5573
	 *
5574
	 * @deprecated since 7.7.0
5575
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5576
	 *
5577
	 * @param array $methods Public XMLRPC methods.
5578
	 * @return array Public XMLRPC methods, with the getOptions one.
5579
	 */
5580 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5581
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5582
5583
		if ( ! $this->connection_manager ) {
5584
			$this->connection_manager = new Connection_Manager();
5585
		}
5586
5587
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5588
	}
5589
5590
	/**
5591
	 * Handles a getOptions XMLRPC method call.
5592
	 *
5593
	 * @deprecated since 7.7.0
5594
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5595
	 *
5596
	 * @param array $args method call arguments.
5597
	 * @return array an amended XMLRPC server options array.
5598
	 */
5599 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5600
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5601
5602
		if ( ! $this->connection_manager ) {
5603
			$this->connection_manager = new Connection_Manager();
5604
		}
5605
5606
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
Bug introduced by
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
5607
	}
5608
5609
	/**
5610
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5611
	 *
5612
	 * @deprecated since 7.7.0
5613
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5614
	 *
5615
	 * @param array $options Standard Core options.
5616
	 * @return array Amended options.
5617
	 */
5618 View Code Duplication
	public function xmlrpc_options( $options ) {
5619
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5620
5621
		if ( ! $this->connection_manager ) {
5622
			$this->connection_manager = new Connection_Manager();
5623
		}
5624
5625
		return $this->connection_manager->xmlrpc_options( $options );
5626
	}
5627
5628
	/**
5629
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5630
	 * SET: state( $key, $value );
5631
	 * GET: $value = state( $key );
5632
	 *
5633
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5634
	 * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5635
	 * @param bool   $restate private
5636
	 */
5637
	public static function state( $key = null, $value = null, $restate = false ) {
5638
		static $state = array();
5639
		static $path, $domain;
5640
		if ( ! isset( $path ) ) {
5641
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5642
			$admin_url = self::admin_url();
5643
			$bits      = wp_parse_url( $admin_url );
5644
5645
			if ( is_array( $bits ) ) {
5646
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5647
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5648
			} else {
5649
				$path = $domain = null;
5650
			}
5651
		}
5652
5653
		// Extract state from cookies and delete cookies
5654
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5655
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5656
			unset( $_COOKIE['jetpackState'] );
5657
			foreach ( $yum as $k => $v ) {
0 ignored issues
show
Bug introduced by
The expression $yum of type string|array<integer,string> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5658
				if ( strlen( $v ) ) {
5659
					$state[ $k ] = $v;
5660
				}
5661
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5662
			}
5663
		}
5664
5665
		if ( $restate ) {
5666
			foreach ( $state as $k => $v ) {
5667
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5668
			}
5669
			return;
5670
		}
5671
5672
		// Get a state variable.
5673
		if ( isset( $key ) && ! isset( $value ) ) {
5674
			if ( array_key_exists( $key, $state ) ) {
5675
				return $state[ $key ];
5676
			}
5677
			return null;
5678
		}
5679
5680
		// Set a state variable.
5681
		if ( isset( $key ) && isset( $value ) ) {
5682
			if ( is_array( $value ) && isset( $value[0] ) ) {
5683
				$value = $value[0];
5684
			}
5685
			$state[ $key ] = $value;
5686
			if ( ! headers_sent() ) {
5687
				if ( self::should_set_cookie( $key ) ) {
5688
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5689
				}
5690
			}
5691
		}
5692
	}
5693
5694
	public static function restate() {
5695
		self::state( null, null, true );
5696
	}
5697
5698
	/**
5699
	 * Determines whether the jetpackState[$key] value should be added to the
5700
	 * cookie.
5701
	 *
5702
	 * @param string $key The state key.
5703
	 *
5704
	 * @return boolean Whether the value should be added to the cookie.
5705
	 */
5706
	public static function should_set_cookie( $key ) {
5707
		global $current_screen;
5708
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5709
5710
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5711
			return false;
5712
		}
5713
5714
		return true;
5715
	}
5716
5717
	public static function check_privacy( $file ) {
5718
		static $is_site_publicly_accessible = null;
5719
5720
		if ( is_null( $is_site_publicly_accessible ) ) {
5721
			$is_site_publicly_accessible = false;
5722
5723
			$rpc = new Jetpack_IXR_Client();
5724
5725
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5726
			if ( $success ) {
5727
				$response = $rpc->getResponse();
5728
				if ( $response ) {
5729
					$is_site_publicly_accessible = true;
5730
				}
5731
			}
5732
5733
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5734
		}
5735
5736
		if ( $is_site_publicly_accessible ) {
5737
			return;
5738
		}
5739
5740
		$module_slug = self::get_module_slug( $file );
5741
5742
		$privacy_checks = self::state( 'privacy_checks' );
5743
		if ( ! $privacy_checks ) {
5744
			$privacy_checks = $module_slug;
5745
		} else {
5746
			$privacy_checks .= ",$module_slug";
5747
		}
5748
5749
		self::state( 'privacy_checks', $privacy_checks );
5750
	}
5751
5752
	/**
5753
	 * Helper method for multicall XMLRPC.
5754
	 *
5755
	 * @deprecated since 8.9.0
5756
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5757
	 *
5758
	 * @param ...$args Args for the async_call.
5759
	 */
5760
	public static function xmlrpc_async_call( ...$args ) {
5761
5762
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5763
5764
		global $blog_id;
5765
		static $clients = array();
5766
5767
		$client_blog_id = is_multisite() ? $blog_id : 0;
5768
5769
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5770
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => Connection_Manager::CONNECTION_OWNER ) );
5771
			if ( function_exists( 'ignore_user_abort' ) ) {
5772
				ignore_user_abort( true );
5773
			}
5774
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5775
		}
5776
5777
		if ( ! empty( $args[0] ) ) {
5778
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5779
		} elseif ( is_multisite() ) {
5780
			foreach ( $clients as $client_blog_id => $client ) {
5781
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5782
					continue;
5783
				}
5784
5785
				$switch_success = switch_to_blog( $client_blog_id, true );
5786
				if ( ! $switch_success ) {
5787
					continue;
5788
				}
5789
5790
				flush();
5791
				$client->query();
5792
5793
				restore_current_blog();
5794
			}
5795
		} else {
5796
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5797
				flush();
5798
				$clients[0]->query();
5799
			}
5800
		}
5801
	}
5802
5803
	/**
5804
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5805
	 *
5806
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5807
	 *
5808
	 * @param string $url WordPress.com static resource URL.
5809
	 */
5810
	public static function staticize_subdomain( $url ) {
5811
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5812
		return Assets::staticize_subdomain( $url );
5813
	}
5814
5815
	/* JSON API Authorization */
5816
5817
	/**
5818
	 * Handles the login action for Authorizing the JSON API
5819
	 */
5820
	function login_form_json_api_authorization() {
5821
		$this->verify_json_api_authorization_request();
5822
5823
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5824
5825
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5826
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5827
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5828
	}
5829
5830
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5831
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5832
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5833
			return $url;
5834
		}
5835
5836
		$parsed_url = wp_parse_url( $url );
5837
		$url        = strtok( $url, '?' );
5838
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5839
		if ( ! empty( $parsed_url['query'] ) ) {
5840
			$url .= "&{$parsed_url['query']}";
5841
		}
5842
5843
		return $url;
5844
	}
5845
5846
	// Make sure the POSTed request is handled by the same action
5847
	function preserve_action_in_login_form_for_json_api_authorization() {
5848
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5849
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5850
	}
5851
5852
	// If someone logs in to approve API access, store the Access Code in usermeta
5853
	function store_json_api_authorization_token( $user_login, $user ) {
5854
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5855
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5856
		$token = wp_generate_password( 32, false );
5857
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5858
	}
5859
5860
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5861
	function allow_wpcom_public_api_domain( $domains ) {
5862
		$domains[] = 'public-api.wordpress.com';
5863
		return $domains;
5864
	}
5865
5866
	static function is_redirect_encoded( $redirect_url ) {
5867
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5868
	}
5869
5870
	// Add all wordpress.com environments to the safe redirect allowed list.
5871
	function allow_wpcom_environments( $domains ) {
5872
		$domains[] = 'wordpress.com';
5873
		$domains[] = 'wpcalypso.wordpress.com';
5874
		$domains[] = 'horizon.wordpress.com';
5875
		$domains[] = 'calypso.localhost';
5876
		return $domains;
5877
	}
5878
5879
	// Add the Access Code details to the public-api.wordpress.com redirect
5880
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5881
		return add_query_arg(
5882
			urlencode_deep(
5883
				array(
5884
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5885
					'jetpack-user-id' => (int) $user->ID,
5886
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5887
				)
5888
			),
5889
			$redirect_to
5890
		);
5891
	}
5892
5893
	/**
5894
	 * Verifies the request by checking the signature
5895
	 *
5896
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5897
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5898
	 *
5899
	 * @param null|array $environment
5900
	 */
5901
	function verify_json_api_authorization_request( $environment = null ) {
5902
		$environment = is_null( $environment )
5903
			? $_REQUEST
5904
			: $environment;
5905
5906
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5907
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
5908
		if ( ! $token || empty( $token->secret ) ) {
5909
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5910
		}
5911
5912
		$die_error = __( 'Someone may be trying to trick you into giving them access to your site.  Or it could be you just encountered a bug :).  Either way, please close this window.', 'jetpack' );
5913
5914
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5915
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5916
			/**
5917
			 * Jetpack authorisation request Error.
5918
			 *
5919
			 * @since 7.5.0
5920
			 */
5921
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5922
			$die_error = sprintf(
5923
				/* translators: %s is a URL */
5924
				__( 'Your site is incorrectly double-encoding redirects from http to https. This is preventing Jetpack from authenticating your connection. Please visit our <a href="%s">support page</a> for details about how to resolve this.', 'jetpack' ),
5925
				Redirect::get_url( 'jetpack-support-double-encoding' )
5926
			);
5927
		}
5928
5929
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5930
5931
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5932
			$signature = $jetpack_signature->sign_request(
5933
				$environment['token'],
5934
				$environment['timestamp'],
5935
				$environment['nonce'],
5936
				'',
5937
				'GET',
5938
				$environment['jetpack_json_api_original_query'],
5939
				null,
5940
				true
5941
			);
5942
		} else {
5943
			$signature = $jetpack_signature->sign_current_request(
5944
				array(
5945
					'body'   => null,
5946
					'method' => 'GET',
5947
				)
5948
			);
5949
		}
5950
5951
		if ( ! $signature ) {
5952
			wp_die( $die_error );
5953
		} elseif ( is_wp_error( $signature ) ) {
5954
			wp_die( $die_error );
5955
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5956
			if ( is_ssl() ) {
5957
				// If we signed an HTTP request on the Jetpack Servers, but got redirected to HTTPS by the local blog, check the HTTP signature as well
5958
				$signature = $jetpack_signature->sign_current_request(
5959
					array(
5960
						'scheme' => 'http',
5961
						'body'   => null,
5962
						'method' => 'GET',
5963
					)
5964
				);
5965
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5966
					wp_die( $die_error );
5967
				}
5968
			} else {
5969
				wp_die( $die_error );
5970
			}
5971
		}
5972
5973
		$timestamp = (int) $environment['timestamp'];
5974
		$nonce     = stripslashes( (string) $environment['nonce'] );
5975
5976
		if ( ! $this->connection_manager ) {
5977
			$this->connection_manager = new Connection_Manager();
5978
		}
5979
5980
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5981
			// De-nonce the nonce, at least for 5 minutes.
5982
			// We have to reuse this nonce at least once (used the first time when the initial request is made, used a second time when the login form is POSTed)
5983
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5984
			if ( $old_nonce_time < time() - 300 ) {
5985
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5986
			}
5987
		}
5988
5989
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5990
		$data_filters = array(
5991
			'state'        => 'opaque',
5992
			'client_id'    => 'int',
5993
			'client_title' => 'string',
5994
			'client_image' => 'url',
5995
		);
5996
5997
		foreach ( $data_filters as $key => $sanitation ) {
5998
			if ( ! isset( $data->$key ) ) {
5999
				wp_die( $die_error );
6000
			}
6001
6002
			switch ( $sanitation ) {
6003
				case 'int':
6004
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6005
					break;
6006
				case 'opaque':
6007
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6008
					break;
6009
				case 'string':
6010
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6011
					break;
6012
				case 'url':
6013
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6014
					break;
6015
			}
6016
		}
6017
6018
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6019
			wp_die( $die_error );
6020
		}
6021
	}
6022
6023
	function login_message_json_api_authorization( $message ) {
6024
		return '<p class="message">' . sprintf(
6025
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6026
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6027
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6028
	}
6029
6030
	/**
6031
	 * Get $content_width, but with a <s>twist</s> filter.
6032
	 */
6033
	public static function get_content_width() {
6034
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6035
			? $GLOBALS['content_width']
6036
			: false;
6037
		/**
6038
		 * Filter the Content Width value.
6039
		 *
6040
		 * @since 2.2.3
6041
		 *
6042
		 * @param string $content_width Content Width value.
6043
		 */
6044
		return apply_filters( 'jetpack_content_width', $content_width );
6045
	}
6046
6047
	/**
6048
	 * Pings the WordPress.com Mirror Site for the specified options.
6049
	 *
6050
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6051
	 *
6052
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6053
	 */
6054
	public function get_cloud_site_options( $option_names ) {
6055
		$option_names = array_filter( (array) $option_names, 'is_string' );
6056
6057
		$xml = new Jetpack_IXR_Client();
6058
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6059
		if ( $xml->isError() ) {
6060
			return array(
6061
				'error_code' => $xml->getErrorCode(),
6062
				'error_msg'  => $xml->getErrorMessage(),
6063
			);
6064
		}
6065
		$cloud_site_options = $xml->getResponse();
6066
6067
		return $cloud_site_options;
6068
	}
6069
6070
	/**
6071
	 * Checks if the site is currently in an identity crisis.
6072
	 *
6073
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6074
	 */
6075
	public static function check_identity_crisis() {
6076
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6077
			return false;
6078
		}
6079
6080
		return Jetpack_Options::get_option( 'sync_error_idc' );
6081
	}
6082
6083
	/**
6084
	 * Checks whether the home and siteurl specifically are allowed.
6085
	 * Written so that we don't have re-check $key and $value params every time
6086
	 * we want to check if this site is allowed, for example in footer.php
6087
	 *
6088
	 * @since  3.8.0
6089
	 * @return bool True = already allowed False = not on the allowed list.
6090
	 */
6091
	public static function is_staging_site() {
6092
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6093
		return ( new Status() )->is_staging_site();
6094
	}
6095
6096
	/**
6097
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6098
	 *
6099
	 * @since 4.4.0
6100
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6101
	 *
6102
	 * @return bool
6103
	 */
6104
	public static function validate_sync_error_idc_option() {
6105
		$is_valid = false;
6106
6107
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6108
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6109
		if ( $sync_error && self::sync_idc_optin() ) {
6110
			$local_options = self::get_sync_error_idc_option();
6111
			// Ensure all values are set.
6112
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6113
6114
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6115
				if (
6116
						isset( $sync_error['wpcom_home'] ) &&
6117
						isset( $sync_error['wpcom_siteurl'] ) &&
6118
						$sync_error['wpcom_home'] === $local_options['home'] &&
6119
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6120
				) {
6121
					$is_valid = false;
6122
					// Enable migrate_for_idc so that sync actions are accepted.
6123
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6124
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6125
					$is_valid = true;
6126
				}
6127
			}
6128
		}
6129
6130
		/**
6131
		 * Filters whether the sync_error_idc option is valid.
6132
		 *
6133
		 * @since 4.4.0
6134
		 *
6135
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6136
		 */
6137
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6138
6139
		if ( ! $is_valid && $sync_error ) {
6140
			// Since the option exists, and did not validate, delete it
6141
			Jetpack_Options::delete_option( 'sync_error_idc' );
6142
		}
6143
6144
		return $is_valid;
6145
	}
6146
6147
	/**
6148
	 * Normalizes a url by doing three things:
6149
	 *  - Strips protocol
6150
	 *  - Strips www
6151
	 *  - Adds a trailing slash
6152
	 *
6153
	 * @since 4.4.0
6154
	 * @param string $url
6155
	 * @return WP_Error|string
6156
	 */
6157
	public static function normalize_url_protocol_agnostic( $url ) {
6158
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6159 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsed_url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
6160
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
6161
		}
6162
6163
		// Strip www and protocols
6164
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6165
		return $url;
6166
	}
6167
6168
	/**
6169
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6170
	 *
6171
	 * @since 4.4.0
6172
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6173
	 *
6174
	 * @param array $response
6175
	 * @return array Array of the local urls, wpcom urls, and error code
6176
	 */
6177
	public static function get_sync_error_idc_option( $response = array() ) {
6178
		// Since the local options will hit the database directly, store the values
6179
		// in a transient to allow for autoloading and caching on subsequent views.
6180
		$local_options = get_transient( 'jetpack_idc_local' );
6181
		if ( false === $local_options ) {
6182
			$local_options = array(
6183
				'home'    => Functions::home_url(),
6184
				'siteurl' => Functions::site_url(),
6185
			);
6186
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6187
		}
6188
6189
		$options = array_merge( $local_options, $response );
6190
6191
		$returned_values = array();
6192
		foreach ( $options as $key => $option ) {
6193
			if ( 'error_code' === $key ) {
6194
				$returned_values[ $key ] = $option;
6195
				continue;
6196
			}
6197
6198
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6199
				continue;
6200
			}
6201
6202
			$returned_values[ $key ] = $normalized_url;
6203
		}
6204
6205
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6206
6207
		return $returned_values;
6208
	}
6209
6210
	/**
6211
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6212
	 * If set to true, the site will be put into staging mode.
6213
	 *
6214
	 * @since 4.3.2
6215
	 * @return bool
6216
	 */
6217
	public static function sync_idc_optin() {
6218
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6219
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6220
		} else {
6221
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6222
		}
6223
6224
		/**
6225
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6226
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6227
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6228
		 *
6229
		 * @since 4.3.2
6230
		 *
6231
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6232
		 */
6233
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6234
	}
6235
6236
	/**
6237
	 * Maybe Use a .min.css stylesheet, maybe not.
6238
	 *
6239
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6240
	 */
6241
	public static function maybe_min_asset( $url, $path, $plugin ) {
6242
		// Short out on things trying to find actual paths.
6243
		if ( ! $path || empty( $plugin ) ) {
6244
			return $url;
6245
		}
6246
6247
		$path = ltrim( $path, '/' );
6248
6249
		// Strip out the abspath.
6250
		$base = dirname( plugin_basename( $plugin ) );
6251
6252
		// Short out on non-Jetpack assets.
6253
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6254
			return $url;
6255
		}
6256
6257
		// File name parsing.
6258
		$file              = "{$base}/{$path}";
6259
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6260
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6261
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6262
		$extension         = array_shift( $file_name_parts_r );
6263
6264
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6265
			// Already pointing at the minified version.
6266
			if ( 'min' === $file_name_parts_r[0] ) {
6267
				return $url;
6268
			}
6269
6270
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6271
			if ( file_exists( $min_full_path ) ) {
6272
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6273
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6274
				if ( 'css' === $extension ) {
6275
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6276
					self::$min_assets[ $key ] = $path;
6277
				}
6278
			}
6279
		}
6280
6281
		return $url;
6282
	}
6283
6284
	/**
6285
	 * If the asset is minified, let's flag .min as the suffix.
6286
	 *
6287
	 * Attached to `style_loader_src` filter.
6288
	 *
6289
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6290
	 * @param string $handle The registered handle of the script in question.
6291
	 * @param string $href The url of the asset in question.
0 ignored issues
show
Bug introduced by
There is no parameter named $href. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6292
	 */
6293
	public static function set_suffix_on_min( $src, $handle ) {
6294
		if ( false === strpos( $src, '.min.css' ) ) {
6295
			return $src;
6296
		}
6297
6298
		if ( ! empty( self::$min_assets ) ) {
6299
			foreach ( self::$min_assets as $file => $path ) {
6300
				if ( false !== strpos( $src, $file ) ) {
6301
					wp_style_add_data( $handle, 'suffix', '.min' );
6302
					return $src;
6303
				}
6304
			}
6305
		}
6306
6307
		return $src;
6308
	}
6309
6310
	/**
6311
	 * Maybe inlines a stylesheet.
6312
	 *
6313
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6314
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6315
	 *
6316
	 * Attached to `style_loader_tag` filter.
6317
	 *
6318
	 * @param string $tag The tag that would link to the external asset.
6319
	 * @param string $handle The registered handle of the script in question.
6320
	 *
6321
	 * @return string
6322
	 */
6323
	public static function maybe_inline_style( $tag, $handle ) {
6324
		global $wp_styles;
6325
		$item = $wp_styles->registered[ $handle ];
6326
6327
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6328
			return $tag;
6329
		}
6330
6331
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6332
			$href = $matches[1];
6333
			// Strip off query string
6334
			if ( $pos = strpos( $href, '?' ) ) {
6335
				$href = substr( $href, 0, $pos );
6336
			}
6337
			// Strip off fragment
6338
			if ( $pos = strpos( $href, '#' ) ) {
6339
				$href = substr( $href, 0, $pos );
6340
			}
6341
		} else {
6342
			return $tag;
6343
		}
6344
6345
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6346
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6347
			return $tag;
6348
		}
6349
6350
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6351
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6352
			// And this isn't the pass that actually deals with the RTL version...
6353
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6354
				// Short out, as the RTL version will deal with it in a moment.
6355
				return $tag;
6356
			}
6357
		}
6358
6359
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6360
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6361
		if ( $css ) {
6362
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6363
			if ( empty( $item->extra['after'] ) ) {
6364
				wp_add_inline_style( $handle, $css );
6365
			} else {
6366
				array_unshift( $item->extra['after'], $css );
6367
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6368
			}
6369
		}
6370
6371
		return $tag;
6372
	}
6373
6374
	/**
6375
	 * Loads a view file from the views
6376
	 *
6377
	 * Data passed in with the $data parameter will be available in the
6378
	 * template file as $data['value']
6379
	 *
6380
	 * @param string $template - Template file to load
6381
	 * @param array  $data - Any data to pass along to the template
6382
	 * @return boolean - If template file was found
6383
	 **/
6384
	public function load_view( $template, $data = array() ) {
6385
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6386
6387
		if ( file_exists( $views_dir . $template ) ) {
6388
			require_once $views_dir . $template;
6389
			return true;
6390
		}
6391
6392
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6393
		return false;
6394
	}
6395
6396
	/**
6397
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6398
	 */
6399
	public function deprecated_hooks() {
6400
		$filter_deprecated_list = array(
6401
			'jetpack_bail_on_shortcode'                    => array(
6402
				'replacement' => 'jetpack_shortcodes_to_include',
6403
				'version'     => 'jetpack-3.1.0',
6404
			),
6405
			'wpl_sharing_2014_1'                           => array(
6406
				'replacement' => null,
6407
				'version'     => 'jetpack-3.6.0',
6408
			),
6409
			'jetpack-tools-to-include'                     => array(
6410
				'replacement' => 'jetpack_tools_to_include',
6411
				'version'     => 'jetpack-3.9.0',
6412
			),
6413
			'jetpack_identity_crisis_options_to_check'     => array(
6414
				'replacement' => null,
6415
				'version'     => 'jetpack-4.0.0',
6416
			),
6417
			'update_option_jetpack_single_user_site'       => array(
6418
				'replacement' => null,
6419
				'version'     => 'jetpack-4.3.0',
6420
			),
6421
			'audio_player_default_colors'                  => array(
6422
				'replacement' => null,
6423
				'version'     => 'jetpack-4.3.0',
6424
			),
6425
			'add_option_jetpack_featured_images_enabled'   => array(
6426
				'replacement' => null,
6427
				'version'     => 'jetpack-4.3.0',
6428
			),
6429
			'add_option_jetpack_update_details'            => array(
6430
				'replacement' => null,
6431
				'version'     => 'jetpack-4.3.0',
6432
			),
6433
			'add_option_jetpack_updates'                   => array(
6434
				'replacement' => null,
6435
				'version'     => 'jetpack-4.3.0',
6436
			),
6437
			'add_option_jetpack_network_name'              => array(
6438
				'replacement' => null,
6439
				'version'     => 'jetpack-4.3.0',
6440
			),
6441
			'add_option_jetpack_network_allow_new_registrations' => array(
6442
				'replacement' => null,
6443
				'version'     => 'jetpack-4.3.0',
6444
			),
6445
			'add_option_jetpack_network_add_new_users'     => array(
6446
				'replacement' => null,
6447
				'version'     => 'jetpack-4.3.0',
6448
			),
6449
			'add_option_jetpack_network_site_upload_space' => array(
6450
				'replacement' => null,
6451
				'version'     => 'jetpack-4.3.0',
6452
			),
6453
			'add_option_jetpack_network_upload_file_types' => array(
6454
				'replacement' => null,
6455
				'version'     => 'jetpack-4.3.0',
6456
			),
6457
			'add_option_jetpack_network_enable_administration_menus' => array(
6458
				'replacement' => null,
6459
				'version'     => 'jetpack-4.3.0',
6460
			),
6461
			'add_option_jetpack_is_multi_site'             => array(
6462
				'replacement' => null,
6463
				'version'     => 'jetpack-4.3.0',
6464
			),
6465
			'add_option_jetpack_is_main_network'           => array(
6466
				'replacement' => null,
6467
				'version'     => 'jetpack-4.3.0',
6468
			),
6469
			'add_option_jetpack_main_network_site'         => array(
6470
				'replacement' => null,
6471
				'version'     => 'jetpack-4.3.0',
6472
			),
6473
			'jetpack_sync_all_registered_options'          => array(
6474
				'replacement' => null,
6475
				'version'     => 'jetpack-4.3.0',
6476
			),
6477
			'jetpack_has_identity_crisis'                  => array(
6478
				'replacement' => 'jetpack_sync_error_idc_validation',
6479
				'version'     => 'jetpack-4.4.0',
6480
			),
6481
			'jetpack_is_post_mailable'                     => array(
6482
				'replacement' => null,
6483
				'version'     => 'jetpack-4.4.0',
6484
			),
6485
			'jetpack_seo_site_host'                        => array(
6486
				'replacement' => null,
6487
				'version'     => 'jetpack-5.1.0',
6488
			),
6489
			'jetpack_installed_plugin'                     => array(
6490
				'replacement' => 'jetpack_plugin_installed',
6491
				'version'     => 'jetpack-6.0.0',
6492
			),
6493
			'jetpack_holiday_snow_option_name'             => array(
6494
				'replacement' => null,
6495
				'version'     => 'jetpack-6.0.0',
6496
			),
6497
			'jetpack_holiday_chance_of_snow'               => array(
6498
				'replacement' => null,
6499
				'version'     => 'jetpack-6.0.0',
6500
			),
6501
			'jetpack_holiday_snow_js_url'                  => array(
6502
				'replacement' => null,
6503
				'version'     => 'jetpack-6.0.0',
6504
			),
6505
			'jetpack_is_holiday_snow_season'               => array(
6506
				'replacement' => null,
6507
				'version'     => 'jetpack-6.0.0',
6508
			),
6509
			'jetpack_holiday_snow_option_updated'          => array(
6510
				'replacement' => null,
6511
				'version'     => 'jetpack-6.0.0',
6512
			),
6513
			'jetpack_holiday_snowing'                      => array(
6514
				'replacement' => null,
6515
				'version'     => 'jetpack-6.0.0',
6516
			),
6517
			'jetpack_sso_auth_cookie_expirtation'          => array(
6518
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6519
				'version'     => 'jetpack-6.1.0',
6520
			),
6521
			'jetpack_cache_plans'                          => array(
6522
				'replacement' => null,
6523
				'version'     => 'jetpack-6.1.0',
6524
			),
6525
6526
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6527
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6528
				'version'     => 'jetpack-6.5.0',
6529
			),
6530
			'jetpack_enable_site_verification'             => array(
6531
				'replacement' => null,
6532
				'version'     => 'jetpack-6.5.0',
6533
			),
6534
			'can_display_jetpack_manage_notice'            => array(
6535
				'replacement' => null,
6536
				'version'     => 'jetpack-7.3.0',
6537
			),
6538
			'atd_http_post_timeout'                        => array(
6539
				'replacement' => null,
6540
				'version'     => 'jetpack-7.3.0',
6541
			),
6542
			'atd_service_domain'                           => array(
6543
				'replacement' => null,
6544
				'version'     => 'jetpack-7.3.0',
6545
			),
6546
			'atd_load_scripts'                             => array(
6547
				'replacement' => null,
6548
				'version'     => 'jetpack-7.3.0',
6549
			),
6550
			'jetpack_widget_authors_exclude'               => array(
6551
				'replacement' => 'jetpack_widget_authors_params',
6552
				'version'     => 'jetpack-7.7.0',
6553
			),
6554
			// Removed in Jetpack 7.9.0
6555
			'jetpack_pwa_manifest'                         => array(
6556
				'replacement' => null,
6557
				'version'     => 'jetpack-7.9.0',
6558
			),
6559
			'jetpack_pwa_background_color'                 => array(
6560
				'replacement' => null,
6561
				'version'     => 'jetpack-7.9.0',
6562
			),
6563
			'jetpack_check_mobile'                         => array(
6564
				'replacement' => null,
6565
				'version'     => 'jetpack-8.3.0',
6566
			),
6567
			'jetpack_mobile_stylesheet'                    => array(
6568
				'replacement' => null,
6569
				'version'     => 'jetpack-8.3.0',
6570
			),
6571
			'jetpack_mobile_template'                      => array(
6572
				'replacement' => null,
6573
				'version'     => 'jetpack-8.3.0',
6574
			),
6575
			'jetpack_mobile_theme_menu'                    => array(
6576
				'replacement' => null,
6577
				'version'     => 'jetpack-8.3.0',
6578
			),
6579
			'minileven_show_featured_images'               => array(
6580
				'replacement' => null,
6581
				'version'     => 'jetpack-8.3.0',
6582
			),
6583
			'minileven_attachment_size'                    => array(
6584
				'replacement' => null,
6585
				'version'     => 'jetpack-8.3.0',
6586
			),
6587
			'instagram_cache_oembed_api_response_body'     => array(
6588
				'replacement' => null,
6589
				'version'     => 'jetpack-9.1.0',
6590
			),
6591
			'jetpack_can_make_outbound_https'              => array(
6592
				'replacement' => null,
6593
				'version'     => 'jetpack-9.1.0',
6594
			),
6595
		);
6596
6597
		foreach ( $filter_deprecated_list as $tag => $args ) {
6598
			if ( has_filter( $tag ) ) {
6599
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6600
			}
6601
		}
6602
6603
		$action_deprecated_list = array(
6604
			'jetpack_updated_theme'        => array(
6605
				'replacement' => 'jetpack_updated_themes',
6606
				'version'     => 'jetpack-6.2.0',
6607
			),
6608
			'atd_http_post_error'          => array(
6609
				'replacement' => null,
6610
				'version'     => 'jetpack-7.3.0',
6611
			),
6612
			'mobile_reject_mobile'         => array(
6613
				'replacement' => null,
6614
				'version'     => 'jetpack-8.3.0',
6615
			),
6616
			'mobile_force_mobile'          => array(
6617
				'replacement' => null,
6618
				'version'     => 'jetpack-8.3.0',
6619
			),
6620
			'mobile_app_promo_download'    => array(
6621
				'replacement' => null,
6622
				'version'     => 'jetpack-8.3.0',
6623
			),
6624
			'mobile_setup'                 => array(
6625
				'replacement' => null,
6626
				'version'     => 'jetpack-8.3.0',
6627
			),
6628
			'jetpack_mobile_footer_before' => array(
6629
				'replacement' => null,
6630
				'version'     => 'jetpack-8.3.0',
6631
			),
6632
			'wp_mobile_theme_footer'       => array(
6633
				'replacement' => null,
6634
				'version'     => 'jetpack-8.3.0',
6635
			),
6636
			'minileven_credits'            => array(
6637
				'replacement' => null,
6638
				'version'     => 'jetpack-8.3.0',
6639
			),
6640
			'jetpack_mobile_header_before' => array(
6641
				'replacement' => null,
6642
				'version'     => 'jetpack-8.3.0',
6643
			),
6644
			'jetpack_mobile_header_after'  => array(
6645
				'replacement' => null,
6646
				'version'     => 'jetpack-8.3.0',
6647
			),
6648
		);
6649
6650
		foreach ( $action_deprecated_list as $tag => $args ) {
6651
			if ( has_action( $tag ) ) {
6652
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6653
			}
6654
		}
6655
	}
6656
6657
	/**
6658
	 * Converts any url in a stylesheet, to the correct absolute url.
6659
	 *
6660
	 * Considerations:
6661
	 *  - Normal, relative URLs     `feh.png`
6662
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6663
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6664
	 *  - Absolute URLs             `http://domain.com/feh.png`
6665
	 *  - Domain root relative URLs `/feh.png`
6666
	 *
6667
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6668
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6669
	 *
6670
	 * @return mixed|string
6671
	 */
6672
	public static function absolutize_css_urls( $css, $css_file_url ) {
6673
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6674
		$css_dir = dirname( $css_file_url );
6675
		$p       = wp_parse_url( $css_dir );
6676
		$domain  = sprintf(
6677
			'%1$s//%2$s%3$s%4$s',
6678
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6679
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6680
			$p['host'],
6681
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6682
		);
6683
6684
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6685
			$find = $replace = array();
6686
			foreach ( $matches as $match ) {
6687
				$url = trim( $match['path'], "'\" \t" );
6688
6689
				// If this is a data url, we don't want to mess with it.
6690
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6691
					continue;
6692
				}
6693
6694
				// If this is an absolute or protocol-agnostic url,
6695
				// we don't want to mess with it.
6696
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6697
					continue;
6698
				}
6699
6700
				switch ( substr( $url, 0, 1 ) ) {
6701
					case '/':
6702
						$absolute = $domain . $url;
6703
						break;
6704
					default:
6705
						$absolute = $css_dir . '/' . $url;
6706
				}
6707
6708
				$find[]    = $match[0];
6709
				$replace[] = sprintf( 'url("%s")', $absolute );
6710
			}
6711
			$css = str_replace( $find, $replace, $css );
6712
		}
6713
6714
		return $css;
6715
	}
6716
6717
	/**
6718
	 * This methods removes all of the registered css files on the front end
6719
	 * from Jetpack in favor of using a single file. In effect "imploding"
6720
	 * all the files into one file.
6721
	 *
6722
	 * Pros:
6723
	 * - Uses only ONE css asset connection instead of 15
6724
	 * - Saves a minimum of 56k
6725
	 * - Reduces server load
6726
	 * - Reduces time to first painted byte
6727
	 *
6728
	 * Cons:
6729
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6730
	 *      should not cause any issues with themes.
6731
	 * - Plugins/themes dequeuing styles no longer do anything. See
6732
	 *      jetpack_implode_frontend_css filter for a workaround
6733
	 *
6734
	 * For some situations developers may wish to disable css imploding and
6735
	 * instead operate in legacy mode where each file loads seperately and
6736
	 * can be edited individually or dequeued. This can be accomplished with
6737
	 * the following line:
6738
	 *
6739
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6740
	 *
6741
	 * @since 3.2
6742
	 **/
6743
	public function implode_frontend_css( $travis_test = false ) {
6744
		$do_implode = true;
6745
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6746
			$do_implode = false;
6747
		}
6748
6749
		// Do not implode CSS when the page loads via the AMP plugin.
6750
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6751
			$do_implode = false;
6752
		}
6753
6754
		/**
6755
		 * Allow CSS to be concatenated into a single jetpack.css file.
6756
		 *
6757
		 * @since 3.2.0
6758
		 *
6759
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6760
		 */
6761
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6762
6763
		// Do not use the imploded file when default behavior was altered through the filter
6764
		if ( ! $do_implode ) {
6765
			return;
6766
		}
6767
6768
		// We do not want to use the imploded file in dev mode, or if not connected
6769
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6770
			if ( ! $travis_test ) {
6771
				return;
6772
			}
6773
		}
6774
6775
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6776
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6777
			return;
6778
		}
6779
6780
		/*
6781
		 * Now we assume Jetpack is connected and able to serve the single
6782
		 * file.
6783
		 *
6784
		 * In the future there will be a check here to serve the file locally
6785
		 * or potentially from the Jetpack CDN
6786
		 *
6787
		 * For now:
6788
		 * - Enqueue a single imploded css file
6789
		 * - Zero out the style_loader_tag for the bundled ones
6790
		 * - Be happy, drink scotch
6791
		 */
6792
6793
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6794
6795
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6796
6797
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6798
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6799
	}
6800
6801
	function concat_remove_style_loader_tag( $tag, $handle ) {
6802
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6803
			$tag = '';
6804
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6805
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6806
			}
6807
		}
6808
6809
		return $tag;
6810
	}
6811
6812
	/**
6813
	 * @deprecated
6814
	 * @see Automattic\Jetpack\Assets\add_aync_script
6815
	 */
6816
	public function script_add_async( $tag, $handle, $src ) {
6817
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6818
	}
6819
6820
	/*
6821
	 * Check the heartbeat data
6822
	 *
6823
	 * Organizes the heartbeat data by severity.  For example, if the site
6824
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6825
	 *
6826
	 * Data will be added to "caution" array, if it either:
6827
	 *  - Out of date Jetpack version
6828
	 *  - Out of date WP version
6829
	 *  - Out of date PHP version
6830
	 *
6831
	 * $return array $filtered_data
6832
	 */
6833
	public static function jetpack_check_heartbeat_data() {
6834
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6835
6836
		$good    = array();
6837
		$caution = array();
6838
		$bad     = array();
6839
6840
		foreach ( $raw_data as $stat => $value ) {
6841
6842
			// Check jetpack version
6843
			if ( 'version' == $stat ) {
6844
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6845
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6846
					continue;
6847
				}
6848
			}
6849
6850
			// Check WP version
6851
			if ( 'wp-version' == $stat ) {
6852
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6853
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6854
					continue;
6855
				}
6856
			}
6857
6858
			// Check PHP version
6859
			if ( 'php-version' == $stat ) {
6860
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6861
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6862
					continue;
6863
				}
6864
			}
6865
6866
			// Check ID crisis
6867
			if ( 'identitycrisis' == $stat ) {
6868
				if ( 'yes' == $value ) {
6869
					$bad[ $stat ] = $value;
6870
					continue;
6871
				}
6872
			}
6873
6874
			// The rest are good :)
6875
			$good[ $stat ] = $value;
6876
		}
6877
6878
		$filtered_data = array(
6879
			'good'    => $good,
6880
			'caution' => $caution,
6881
			'bad'     => $bad,
6882
		);
6883
6884
		return $filtered_data;
6885
	}
6886
6887
	/*
6888
	 * This method is used to organize all options that can be reset
6889
	 * without disconnecting Jetpack.
6890
	 *
6891
	 * It is used in class.jetpack-cli.php to reset options
6892
	 *
6893
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6894
	 *
6895
	 * @return array of options to delete.
6896
	 */
6897
	public static function get_jetpack_options_for_reset() {
6898
		return Jetpack_Options::get_options_for_reset();
6899
	}
6900
6901
	/*
6902
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6903
	 * so we can bring them directly to their site in calypso.
6904
	 *
6905
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
6906
	 *
6907
	 * @param string | url
6908
	 * @return string | url without the guff
6909
	 */
6910
	public static function build_raw_urls( $url ) {
6911
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
6912
6913
		return ( new Status() )->get_site_suffix( $url );
6914
	}
6915
6916
	/**
6917
	 * Stores and prints out domains to prefetch for page speed optimization.
6918
	 *
6919
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
6920
	 *
6921
	 * @param string|array $urls URLs to hint.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $urls not be string|array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
6922
	 */
6923
	public static function dns_prefetch( $urls = null ) {
6924
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6925
		if ( $urls ) {
6926
			Assets::add_resource_hint( $urls );
6927
		}
6928
	}
6929
6930
	public function wp_dashboard_setup() {
6931
		if ( self::is_active() ) {
6932
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6933
		}
6934
6935
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6936
			$jetpack_logo = new Jetpack_Logo();
6937
			$widget_title = sprintf(
6938
				/* translators: Placeholder is a Jetpack logo. */
6939
				__( 'Stats by %s', 'jetpack' ),
6940
				$jetpack_logo->get_jp_emblem( true )
6941
			);
6942
6943
			// Wrap title in span so Logo can be properly styled.
6944
			$widget_title = sprintf(
6945
				'<span>%s</span>',
6946
				$widget_title
6947
			);
6948
6949
			wp_add_dashboard_widget(
6950
				'jetpack_summary_widget',
6951
				$widget_title,
6952
				array( __CLASS__, 'dashboard_widget' )
6953
			);
6954
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6955
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6956
6957
			// If we're inactive and not in offline mode, sort our box to the top.
6958
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
6959
				global $wp_meta_boxes;
6960
6961
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6962
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6963
6964
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6965
			}
6966
		}
6967
	}
6968
6969
	/**
6970
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6971
	 * @return mixed
6972
	 */
6973
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6974
		if ( ! is_array( $sorted ) ) {
6975
			return $sorted;
6976
		}
6977
6978
		foreach ( $sorted as $box_context => $ids ) {
6979
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6980
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6981
				continue;
6982
			}
6983
6984
			$ids_array = explode( ',', $ids );
6985
			$key       = array_search( 'dashboard_stats', $ids_array );
6986
6987
			if ( false !== $key ) {
6988
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6989
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6990
				$sorted[ $box_context ] = implode( ',', $ids_array );
6991
				// We've found it, stop searching, and just return.
6992
				break;
6993
			}
6994
		}
6995
6996
		return $sorted;
6997
	}
6998
6999
	public static function dashboard_widget() {
7000
		/**
7001
		 * Fires when the dashboard is loaded.
7002
		 *
7003
		 * @since 3.4.0
7004
		 */
7005
		do_action( 'jetpack_dashboard_widget' );
7006
	}
7007
7008
	public static function dashboard_widget_footer() {
7009
		?>
7010
		<footer>
7011
7012
		<div class="protect">
7013
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7014
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7015
				<p class="blocked-count">
7016
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7017
				</p>
7018
				<p><?php echo esc_html_x( 'Blocked malicious login attempts', '{#} Blocked malicious login attempts -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
7019
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7020
				<a href="
7021
				<?php
7022
				echo esc_url(
7023
					wp_nonce_url(
7024
						self::admin_url(
7025
							array(
7026
								'action' => 'activate',
7027
								'module' => 'protect',
7028
							)
7029
						),
7030
						'jetpack_activate-protect'
7031
					)
7032
				);
7033
				?>
7034
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7035
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7036
				</a>
7037
			<?php else : ?>
7038
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7039
			<?php endif; ?>
7040
		</div>
7041
7042
		<div class="akismet">
7043
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7044
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7045
				<p class="blocked-count">
7046
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7047
				</p>
7048
				<p><?php echo esc_html_x( 'Blocked spam comments.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
7049
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7050
				<a href="
7051
				<?php
7052
				echo esc_url(
7053
					wp_nonce_url(
7054
						add_query_arg(
7055
							array(
7056
								'action' => 'activate',
7057
								'plugin' => 'akismet/akismet.php',
7058
							),
7059
							admin_url( 'plugins.php' )
7060
						),
7061
						'activate-plugin_akismet/akismet.php'
7062
					)
7063
				);
7064
				?>
7065
							" class="button button-jetpack">
7066
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7067
				</a>
7068
			<?php else : ?>
7069
				<p><a href="<?php echo esc_url( 'https://akismet.com/?utm_source=jetpack&utm_medium=link&utm_campaign=Jetpack%20Dashboard%20Widget%20Footer%20Link' ); ?>"><?php esc_html_e( 'Anti-spam can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
7070
			<?php endif; ?>
7071
		</div>
7072
7073
		</footer>
7074
		<?php
7075
	}
7076
7077
	/*
7078
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7079
	 */
7080
	function jetpack_icon_user_connected( $columns ) {
7081
		$columns['user_jetpack'] = '';
7082
		return $columns;
7083
	}
7084
7085
	/*
7086
	 * Show Jetpack icon if the user is linked.
7087
	 */
7088
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7089
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7090
			$jetpack_logo = new Jetpack_Logo();
7091
			$emblem_html  = sprintf(
7092
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7093
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7094
				$jetpack_logo->get_jp_emblem()
7095
			);
7096
			return $emblem_html;
7097
		}
7098
7099
		return $val;
7100
	}
7101
7102
	/*
7103
	 * Style the Jetpack user column
7104
	 */
7105
	function jetpack_user_col_style() {
7106
		global $current_screen;
7107
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7108
			?>
7109
			<style>
7110
				.fixed .column-user_jetpack {
7111
					width: 21px;
7112
				}
7113
				.jp-emblem-user-admin svg {
7114
					width: 20px;
7115
					height: 20px;
7116
				}
7117
				.jp-emblem-user-admin path {
7118
					fill: #00BE28;
7119
				}
7120
			</style>
7121
			<?php
7122
		}
7123
	}
7124
7125
	/**
7126
	 * Checks if Akismet is active and working.
7127
	 *
7128
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7129
	 * that implied usage of methods present since more recent version.
7130
	 * See https://github.com/Automattic/jetpack/pull/9585
7131
	 *
7132
	 * @since  5.1.0
7133
	 *
7134
	 * @return bool True = Akismet available. False = Aksimet not available.
7135
	 */
7136
	public static function is_akismet_active() {
7137
		static $status = null;
7138
7139
		if ( ! is_null( $status ) ) {
7140
			return $status;
7141
		}
7142
7143
		// Check if a modern version of Akismet is active.
7144
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7145
			$status = false;
7146
			return $status;
7147
		}
7148
7149
		// Make sure there is a key known to Akismet at all before verifying key.
7150
		$akismet_key = Akismet::get_api_key();
7151
		if ( ! $akismet_key ) {
7152
			$status = false;
7153
			return $status;
7154
		}
7155
7156
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7157
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7158
7159
		// 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.
7160
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7161
		// We cache the result of the Akismet key verification for ten minutes.
7162
		if ( ! $akismet_key_state || $recheck ) {
7163
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7164
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7165
		}
7166
7167
		$status = 'valid' === $akismet_key_state;
7168
7169
		return $status;
7170
	}
7171
7172
	/**
7173
	 * @deprecated
7174
	 *
7175
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7176
	 */
7177
	public static function is_function_in_backtrace() {
7178
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7179
	}
7180
7181
	/**
7182
	 * Given a minified path, and a non-minified path, will return
7183
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7184
	 *
7185
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7186
	 * root Jetpack directory.
7187
	 *
7188
	 * @since 5.6.0
7189
	 *
7190
	 * @param string $min_path
7191
	 * @param string $non_min_path
7192
	 * @return string The URL to the file
7193
	 */
7194
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7195
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7196
	}
7197
7198
	/**
7199
	 * Checks for whether Jetpack Backup is enabled.
7200
	 * Will return true if the state of Backup is anything except "unavailable".
7201
	 *
7202
	 * @return bool|int|mixed
7203
	 */
7204
	public static function is_rewind_enabled() {
7205
		if ( ! self::is_active() ) {
7206
			return false;
7207
		}
7208
7209
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7210
		if ( false === $rewind_enabled ) {
7211
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7212
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7213
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7214
				&& ! empty( $rewind_data['state'] )
7215
				&& 'active' === $rewind_data['state'] )
7216
				? 1
7217
				: 0;
7218
7219
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7220
		}
7221
		return $rewind_enabled;
7222
	}
7223
7224
	/**
7225
	 * Return Calypso environment value; used for developing Jetpack and pairing
7226
	 * it with different Calypso enrionments, such as localhost.
7227
	 *
7228
	 * @since 7.4.0
7229
	 *
7230
	 * @return string Calypso environment
7231
	 */
7232
	public static function get_calypso_env() {
7233
		if ( isset( $_GET['calypso_env'] ) ) {
7234
			return sanitize_key( $_GET['calypso_env'] );
7235
		}
7236
7237
		if ( getenv( 'CALYPSO_ENV' ) ) {
7238
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7239
		}
7240
7241
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7242
			return sanitize_key( CALYPSO_ENV );
7243
		}
7244
7245
		return '';
7246
	}
7247
7248
	/**
7249
	 * Returns the hostname with protocol for Calypso.
7250
	 * Used for developing Jetpack with Calypso.
7251
	 *
7252
	 * @since 8.4.0
7253
	 *
7254
	 * @return string Calypso host.
7255
	 */
7256
	public static function get_calypso_host() {
7257
		$calypso_env = self::get_calypso_env();
7258
		switch ( $calypso_env ) {
7259
			case 'development':
7260
				return 'http://calypso.localhost:3000/';
7261
			case 'wpcalypso':
7262
				return 'https://wpcalypso.wordpress.com/';
7263
			case 'horizon':
7264
				return 'https://horizon.wordpress.com/';
7265
			default:
7266
				return 'https://wordpress.com/';
7267
		}
7268
	}
7269
7270
	/**
7271
	 * Handles activating default modules as well general cleanup for the new connection.
7272
	 *
7273
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7274
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7275
	 * @param boolean $send_state_messages          Whether to send state messages.
7276
	 * @return void
7277
	 */
7278
	public static function handle_post_authorization_actions(
7279
		$activate_sso = false,
7280
		$redirect_on_activation_error = false,
7281
		$send_state_messages = true
7282
	) {
7283
		$other_modules = $activate_sso
7284
			? array( 'sso' )
7285
			: array();
7286
7287
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7288
			self::delete_active_modules();
7289
7290
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7291
		} else {
7292
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7293
		}
7294
7295
		// Since this is a fresh connection, be sure to clear out IDC options
7296
		Jetpack_IDC::clear_all_idc_options();
7297
7298
		if ( $send_state_messages ) {
7299
			self::state( 'message', 'authorized' );
7300
		}
7301
	}
7302
7303
	/**
7304
	 * Returns a boolean for whether backups UI should be displayed or not.
7305
	 *
7306
	 * @return bool Should backups UI be displayed?
7307
	 */
7308
	public static function show_backups_ui() {
7309
		/**
7310
		 * Whether UI for backups should be displayed.
7311
		 *
7312
		 * @since 6.5.0
7313
		 *
7314
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7315
		 */
7316
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7317
	}
7318
7319
	/*
7320
	 * Deprecated manage functions
7321
	 */
7322
	function prepare_manage_jetpack_notice() {
7323
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7324
	}
7325
	function manage_activate_screen() {
7326
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7327
	}
7328
	function admin_jetpack_manage_notice() {
7329
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7330
	}
7331
	function opt_out_jetpack_manage_url() {
7332
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7333
	}
7334
	function opt_in_jetpack_manage_url() {
7335
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7336
	}
7337
	function opt_in_jetpack_manage_notice() {
7338
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7339
	}
7340
	function can_display_jetpack_manage_notice() {
7341
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7342
	}
7343
7344
	/**
7345
	 * Clean leftoveruser meta.
7346
	 *
7347
	 * Delete Jetpack-related user meta when it is no longer needed.
7348
	 *
7349
	 * @since 7.3.0
7350
	 *
7351
	 * @param int $user_id User ID being updated.
7352
	 */
7353
	public static function user_meta_cleanup( $user_id ) {
7354
		$meta_keys = array(
7355
			// AtD removed from Jetpack 7.3
7356
			'AtD_options',
7357
			'AtD_check_when',
7358
			'AtD_guess_lang',
7359
			'AtD_ignored_phrases',
7360
		);
7361
7362
		foreach ( $meta_keys as $meta_key ) {
7363
			if ( get_user_meta( $user_id, $meta_key ) ) {
7364
				delete_user_meta( $user_id, $meta_key );
7365
			}
7366
		}
7367
	}
7368
7369
	/**
7370
	 * Checks if a Jetpack site is both active and not in offline mode.
7371
	 *
7372
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7373
	 *
7374
	 * @deprecated 8.8.0
7375
	 *
7376
	 * @return bool True if Jetpack is active and not in offline mode.
7377
	 */
7378
	public static function is_active_and_not_development_mode() {
7379
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7380
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7381
			return false;
7382
		}
7383
		return true;
7384
	}
7385
7386
	/**
7387
	 * Checks if a Jetpack site is both active and not in offline mode.
7388
	 *
7389
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7390
	 *
7391
	 * @since 8.8.0
7392
	 *
7393
	 * @return bool True if Jetpack is active and not in offline mode.
7394
	 */
7395
	public static function is_active_and_not_offline_mode() {
7396
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7397
			return false;
7398
		}
7399
		return true;
7400
	}
7401
7402
	/**
7403
	 * Returns the list of products that we have available for purchase.
7404
	 */
7405
	public static function get_products_for_purchase() {
7406
		$products = array();
7407
		if ( ! is_multisite() ) {
7408
			$products[] = array(
7409
				'key'               => 'backup',
7410
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7411
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7412
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7413
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7414
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7415
				'options'           => array(
7416
					array(
7417
						'type'        => 'daily',
7418
						'slug'        => 'jetpack-backup-daily',
7419
						'key'         => 'jetpack_backup_daily',
7420
						'name'        => __( 'Daily Backups', 'jetpack' ),
7421
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7422
					),
7423
					array(
7424
						'type'        => 'realtime',
7425
						'slug'        => 'jetpack-backup-realtime',
7426
						'key'         => 'jetpack_backup_realtime',
7427
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7428
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7429
					),
7430
				),
7431
				'default_option'    => 'realtime',
7432
				'show_promotion'    => true,
7433
				'discount_percent'  => 70,
7434
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7435
			);
7436
7437
			$products[] = array(
7438
				'key'               => 'scan',
7439
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7440
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7441
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7442
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7443
				'show_promotion'    => true,
7444
				'discount_percent'  => 30,
7445
				'options'           => array(
7446
					array(
7447
						'type' => 'scan',
7448
						'slug' => 'jetpack-scan',
7449
						'key'  => 'jetpack_scan',
7450
						'name' => __( 'Daily Scan', 'jetpack' ),
7451
					),
7452
				),
7453
				'default_option'    => 'scan',
7454
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7455
			);
7456
		}
7457
7458
		$products[] = array(
7459
			'key'               => 'search',
7460
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7461
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7462
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7463
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7464
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7465
			'options'           => array(
7466
				array(
7467
					'type' => 'search',
7468
					'slug' => 'jetpack-search',
7469
					'key'  => 'jetpack_search',
7470
					'name' => __( 'Search', 'jetpack' ),
7471
				),
7472
			),
7473
			'tears'             => array(),
7474
			'default_option'    => 'search',
7475
			'show_promotion'    => false,
7476
			'included_in_plans' => array( 'search-plan' ),
7477
		);
7478
7479
		$products[] = array(
7480
			'key'               => 'anti-spam',
7481
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7482
			'short_description' => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
7483
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7484
			'description'       => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
7485
			'options'           => array(
7486
				array(
7487
					'type' => 'anti-spam',
7488
					'slug' => 'jetpack-anti-spam',
7489
					'key'  => 'jetpack_anti_spam',
7490
					'name' => __( 'Anti-Spam', 'jetpack' ),
7491
				),
7492
			),
7493
			'default_option'    => 'anti-spam',
7494
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7495
		);
7496
7497
		return $products;
7498
	}
7499
}
7500