Completed
Push — add/instagram-widget ( 2b8bdc...bb5d28 )
by
unknown
112:19 queued 104:33
created

Jetpack   F

Complexity

Total Complexity 1038

Size/Duplication

Total Lines 7410
Duplicated Lines 5.21 %

Coupling/Cohesion

Components 3
Dependencies 39

Importance

Changes 0
Metric Value
wmc 1038
lcom 3
cbo 39
dl 386
loc 7410
rs 0.8
c 0
b 0
f 0

267 Methods

Rating   Name   Duplication   Size   Complexity  
A jetpack_icon_user_connected() 0 4 1
A is_onboarding() 0 3 1
B jetpack_check_heartbeat_data() 0 53 10
A get_jetpack_options_for_reset() 0 3 1
A maybe_set_version_option() 0 14 3
A check_identity_crisis() 0 7 4
A xmlrpc_api_url() 0 4 1
B get_default_modules() 0 31 6
B filter_default_modules() 0 24 6
A get_module_slug() 0 3 1
A plugin_initialize() 6 17 3
B glob_php() 0 29 7
A get_module_path() 0 11 1
A network_allow_new_registrations() 0 3 2
A user_role_change() 0 4 1
A network_add_new_users() 0 3 1
A translate_module_tag() 0 3 1
A get_i18n_data_json() 0 25 4
A setup_wp_i18n_locale_data() 0 10 2
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
A network_site_upload_space() 0 4 2
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 development_mode_trigger_text() 0 16 6
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
C get_available_modules() 0 60 13
B handle_deprecated_modules() 0 27 8
D get_module() 12 89 11
B get_file_data() 0 33 7
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 init() 0 8 2
A late_initialization() 0 18 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 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
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
F plugin_upgrade() 0 71 15
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 configure() 0 65 9
A point_edit_post_links_to_calypso() 0 31 3
A point_edit_comment_links_to_calypso() 0 14 1
A jetpack_track_last_sync_callback() 0 22 5
A jetpack_connection_banner_callback() 0 14 3
B __construct() 0 142 6
B jetpack_custom_caps() 0 35 11
A require_jetpack_authentication() 9 9 2
A plugin_textdomain() 0 4 1
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_upload_file_types() 0 3 1
A network_max_upload_file_size() 0 4 1
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 show_development_mode_notice() 17 28 4
A is_development_version() 0 15 1
A is_user_connected() 0 3 1
A get_connected_user_data() 26 26 4
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
D load_modules() 6 88 17
A check_rest_api_compat() 0 14 2
C activate_new_modules() 6 59 11
A do_version_bump() 0 10 2
A set_update_modal_display() 0 3 1
A plugin_deactivation() 0 11 2
B disconnect() 0 46 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 48 11
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() 15 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() 32 279 55
B admin_notices() 0 125 7
A track_xmlrpc_error() 0 15 4
A stat() 0 6 2
B do_stats() 0 15 7
A do_server_side_stat() 0 12 3
A build_stats_url() 0 20 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
A build_authorize_url() 0 23 3
B filter_connect_request_body() 0 30 6
A filter_connect_processing_url() 0 4 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 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 42 11
A alert_auto_ssl_fail() 0 54 2
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 load_xml_rpc_client() 0 3 1
A reset_saved_auth_state() 0 9 2
A verify_xml_rpc_signature() 0 4 1
A internal_verify_xml_rpc_signature() 0 3 1
A authenticate_jetpack() 9 9 2
C wp_rest_authenticate() 0 74 16
A wp_rest_authentication_errors() 0 6 2
A add_nonce() 9 9 2
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
A clean_nonces() 0 4 1
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 39 12
A staticize_subdomain() 0 35 4
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 is_staging_site() 0 4 1
B validate_sync_error_idc_option() 0 31 11
A normalize_url_protocol_agnostic() 0 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 88 6
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
A build_raw_urls() 6 6 1
B dns_prefetch() 0 17 7
A wp_dashboard_setup() 0 35 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_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 jetpack_tos_agreed() 0 7 1
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 6 3
B get_products_for_purchase() 0 76 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\Utils as Connection_Utils;
8
use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
9
use Automattic\Jetpack\Constants;
10
use Automattic\Jetpack\Partner;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Sync\Functions;
14
use Automattic\Jetpack\Sync\Health;
15
use Automattic\Jetpack\Sync\Sender;
16
use Automattic\Jetpack\Sync\Users;
17
use Automattic\Jetpack\Terms_Of_Service;
18
use Automattic\Jetpack\Tracking;
19
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
20
use Automattic\Jetpack\Redirect;
21
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
22
23
/*
24
Options:
25
jetpack_options (array)
26
	An array of options.
27
	@see Jetpack_Options::get_option_names()
28
29
jetpack_register (string)
30
	Temporary verification secrets.
31
32
jetpack_activated (int)
33
	1: the plugin was activated normally
34
	2: the plugin was activated on this site because of a network-wide activation
35
	3: the plugin was auto-installed
36
	4: the plugin was manually disconnected (but is still installed)
37
38
jetpack_active_modules (array)
39
	Array of active module slugs.
40
41
jetpack_do_activate (bool)
42
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
43
*/
44
45
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
46
47
class Jetpack {
48
	public $xmlrpc_server = null;
49
50
	private $rest_authentication_status = null;
51
52
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
53
54
	/**
55
	 * @var array The handles of styles that are concatenated into jetpack.css.
56
	 *
57
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
58
	 */
59
	public $concatenated_style_handles = array(
60
		'jetpack-carousel',
61
		'grunion.css',
62
		'the-neverending-homepage',
63
		'jetpack_likes',
64
		'jetpack_related-posts',
65
		'sharedaddy',
66
		'jetpack-slideshow',
67
		'presentations',
68
		'quiz',
69
		'jetpack-subscriptions',
70
		'jetpack-responsive-videos-style',
71
		'jetpack-social-menu',
72
		'tiled-gallery',
73
		'jetpack_display_posts_widget',
74
		'gravatar-profile-widget',
75
		'goodreads-widget',
76
		'jetpack_social_media_icons_widget',
77
		'jetpack-top-posts-widget',
78
		'jetpack_image_widget',
79
		'jetpack-my-community-widget',
80
		'jetpack-authors-widget',
81
		'wordads',
82
		'eu-cookie-law-style',
83
		'flickr-widget-style',
84
		'jetpack-search-widget',
85
		'jetpack-simple-payments-widget-style',
86
		'jetpack-widget-social-icons-styles',
87
		'wpcom_instagram_widget',
88
	);
89
90
	/**
91
	 * Contains all assets that have had their URL rewritten to minified versions.
92
	 *
93
	 * @var array
94
	 */
95
	static $min_assets = array();
96
97
	public $plugins_to_deactivate = array(
98
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
99
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
100
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
101
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
102
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
103
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
104
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
105
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
106
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
107
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
108
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
109
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
110
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
111
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
112
	);
113
114
	/**
115
	 * Map of roles we care about, and their corresponding minimum capabilities.
116
	 *
117
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
118
	 *
119
	 * @access public
120
	 * @static
121
	 *
122
	 * @var array
123
	 */
124
	public static $capability_translations = array(
125
		'administrator' => 'manage_options',
126
		'editor'        => 'edit_others_posts',
127
		'author'        => 'publish_posts',
128
		'contributor'   => 'edit_posts',
129
		'subscriber'    => 'read',
130
	);
131
132
	/**
133
	 * Map of modules that have conflicts with plugins and should not be auto-activated
134
	 * if the plugins are active.  Used by filter_default_modules
135
	 *
136
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
137
	 * change `module-slug` and add this to your plugin:
138
	 *
139
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
140
	 * function my_jetpack_get_default_modules( $modules ) {
141
	 *     return array_diff( $modules, array( 'module-slug' ) );
142
	 * }
143
	 *
144
	 * @var array
145
	 */
146
	private $conflicting_plugins = array(
147
		'comments'           => array(
148
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
149
			'Disqus'                         => 'disqus-comment-system/disqus.php',
150
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
151
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
152
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
153
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
154
		),
155
		'comment-likes'      => array(
156
			'Epoch' => 'epoch/plugincore.php',
157
		),
158
		'contact-form'       => array(
159
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
160
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
161
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
162
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
163
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
164
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
165
		),
166
		'latex'              => array(
167
			'LaTeX for WordPress'     => 'latex/latex.php',
168
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
169
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
170
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
171
			'Enable Latex'            => 'enable-latex/enable-latex.php',
172
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
173
		),
174
		'protect'            => array(
175
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
176
			'Captcha'                           => 'captcha/captcha.php',
177
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
178
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
179
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
180
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
181
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
182
			'Security-protection'               => 'security-protection/security-protection.php',
183
			'Login Security'                    => 'login-security/login-security.php',
184
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
185
			'Wordfence Security'                => 'wordfence/wordfence.php',
186
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
187
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
188
		),
189
		'random-redirect'    => array(
190
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
191
		),
192
		'related-posts'      => array(
193
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
194
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
195
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
196
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
197
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
198
			'outbrain'                    => 'outbrain/outbrain.php',
199
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
200
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
201
		),
202
		'sharedaddy'         => array(
203
			'AddThis'     => 'addthis/addthis_social_widget.php',
204
			'Add To Any'  => 'add-to-any/add-to-any.php',
205
			'ShareThis'   => 'share-this/sharethis.php',
206
			'Shareaholic' => 'shareaholic/shareaholic.php',
207
		),
208
		'seo-tools'          => array(
209
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
210
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
211
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
212
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
213
			'The SEO Framework'              => 'autodescription/autodescription.php',
214
			'Rank Math'                      => 'seo-by-rank-math/rank-math.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
		),
224
		'widget-visibility'  => array(
225
			'Widget Logic'    => 'widget-logic/widget_logic.php',
226
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
227
		),
228
		'sitemaps'           => array(
229
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
230
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
231
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
232
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
233
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
234
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
235
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
236
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
237
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
238
			'The SEO Framework'                    => 'autodescription/autodescription.php',
239
			'Sitemap'                              => 'sitemap/sitemap.php',
240
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
241
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
242
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
243
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
244
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
245
		),
246
		'lazy-images'        => array(
247
			'Lazy Load'              => 'lazy-load/lazy-load.php',
248
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
249
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
250
		),
251
	);
252
253
	/**
254
	 * Plugins for which we turn off our Facebook OG Tags implementation.
255
	 *
256
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
257
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
258
	 *
259
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
260
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
261
	 */
262
	private $open_graph_conflicting_plugins = array(
263
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
264
		// 2 Click Social Media Buttons
265
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
266
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
267
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
268
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
269
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
270
		// Open Graph Meta Tags by Heateor
271
		'facebook/facebook.php',                                 // Facebook (official plugin)
272
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
273
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
274
		// Facebook Featured Image & OG Meta Tags
275
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
276
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
277
		// Facebook Open Graph Meta Tags for WordPress
278
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
279
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
280
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
281
		// Fedmich's Facebook Open Graph Meta
282
		'network-publisher/networkpub.php',                      // Network Publisher
283
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
284
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
285
		// NextScripts SNAP
286
		'og-tags/og-tags.php',                                   // OG Tags
287
		'opengraph/opengraph.php',                               // Open Graph
288
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
289
		// Open Graph Protocol Framework
290
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
291
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
292
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
293
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
294
		'sharepress/sharepress.php',                             // SharePress
295
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
296
		'social-discussions/social-discussions.php',             // Social Discussions
297
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
298
		'socialize/socialize.php',                               // Socialize
299
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
300
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
301
		// Tweet, Like, Google +1 and Share
302
		'wordbooker/wordbooker.php',                             // Wordbooker
303
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
304
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
305
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
306
		// WP Facebook Like Send & Open Graph Meta
307
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
308
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
309
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
310
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
311
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
312
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
313
	);
314
315
	/**
316
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
317
	 */
318
	private $twitter_cards_conflicting_plugins = array(
319
		// 'twitter/twitter.php',                       // The official one handles this on its own.
320
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
321
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
322
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
323
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
324
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
325
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
326
		'twitter-cards/twitter-cards.php',           // Twitter Cards
327
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
328
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
329
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
330
		'seo-by-rank-math/rank-math.php',            // Rank Math.
331
	);
332
333
	/**
334
	 * Message to display in admin_notice
335
	 *
336
	 * @var string
337
	 */
338
	public $message = '';
339
340
	/**
341
	 * Error to display in admin_notice
342
	 *
343
	 * @var string
344
	 */
345
	public $error = '';
346
347
	/**
348
	 * Modules that need more privacy description.
349
	 *
350
	 * @var string
351
	 */
352
	public $privacy_checks = '';
353
354
	/**
355
	 * Stats to record once the page loads
356
	 *
357
	 * @var array
358
	 */
359
	public $stats = array();
360
361
	/**
362
	 * Jetpack_Sync object
363
	 */
364
	public $sync;
365
366
	/**
367
	 * Verified data for JSON authorization request
368
	 */
369
	public $json_api_authorization_request = array();
370
371
	/**
372
	 * @var Automattic\Jetpack\Connection\Manager
373
	 */
374
	protected $connection_manager;
375
376
	/**
377
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
378
	 */
379
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
380
381
	/**
382
	 * Constant for login redirect key.
383
	 *
384
	 * @var string
385
	 * @since 8.4.0
386
	 */
387
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
388
389
	/**
390
	 * Holds the singleton instance of this class
391
	 *
392
	 * @since 2.3.3
393
	 * @var Jetpack
394
	 */
395
	static $instance = false;
396
397
	/**
398
	 * Singleton
399
	 *
400
	 * @static
401
	 */
402
	public static function init() {
403
		if ( ! self::$instance ) {
404
			self::$instance = new Jetpack();
405
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
406
		}
407
408
		return self::$instance;
409
	}
410
411
	/**
412
	 * Must never be called statically
413
	 */
414
	function plugin_upgrade() {
415
		if ( self::is_active() ) {
416
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
417
			if ( JETPACK__VERSION != $version ) {
418
				// Prevent multiple upgrades at once - only a single process should trigger
419
				// an upgrade to avoid stampedes
420
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
421
					return;
422
				}
423
424
				// Set a short lock to prevent multiple instances of the upgrade
425
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
426
427
				// check which active modules actually exist and remove others from active_modules list
428
				$unfiltered_modules = self::get_active_modules();
429
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
430
				if ( array_diff( $unfiltered_modules, $modules ) ) {
431
					self::update_active_modules( $modules );
432
				}
433
434
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
435
436
				// Upgrade to 4.3.0
437
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
438
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
439
				}
440
441
				// Make sure Markdown for posts gets turned back on
442
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
443
					update_option( 'wpcom_publish_posts_with_markdown', true );
444
				}
445
446
				/*
447
				 * Minileven deprecation. 8.3.0.
448
				 * Only delete options if not using
449
				 * the replacement standalone Minileven plugin.
450
				 */
451
				if (
452
					! self::is_plugin_active( 'minileven-master/minileven.php' )
453
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
454
				) {
455
					if ( get_option( 'wp_mobile_custom_css' ) ) {
456
						delete_option( 'wp_mobile_custom_css' );
457
					}
458
					if ( get_option( 'wp_mobile_excerpt' ) ) {
459
						delete_option( 'wp_mobile_excerpt' );
460
					}
461
					if ( get_option( 'wp_mobile_featured_images' ) ) {
462
						delete_option( 'wp_mobile_featured_images' );
463
					}
464
					if ( get_option( 'wp_mobile_app_promos' ) ) {
465
						delete_option( 'wp_mobile_app_promos' );
466
					}
467
				}
468
469
				// Upgrade to 8.4.0.
470
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
471
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
472
				}
473
474
				if ( did_action( 'wp_loaded' ) ) {
475
					self::upgrade_on_load();
476
				} else {
477
					add_action(
478
						'wp_loaded',
479
						array( __CLASS__, 'upgrade_on_load' )
480
					);
481
				}
482
			}
483
		}
484
	}
485
486
	/**
487
	 * Runs upgrade routines that need to have modules loaded.
488
	 */
489
	static function upgrade_on_load() {
490
491
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
492
		// This can happen in case Jetpack has been just upgraded and is
493
		// being initialized late during the page load. In this case we wait
494
		// until the next proper admin page load with Jetpack active.
495
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
496
			delete_transient( self::$plugin_upgrade_lock_key );
497
498
			return;
499
		}
500
501
		self::maybe_set_version_option();
502
503
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
504
			Jetpack_Widget_Conditions::migrate_post_type_rules();
505
		}
506
507
		if (
508
			class_exists( 'Jetpack_Sitemap_Manager' )
509
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
510
		) {
511
			do_action( 'jetpack_sitemaps_purge_data' );
512
		}
513
514
		// Delete old stats cache
515
		delete_option( 'jetpack_restapi_stats_cache' );
516
517
		delete_transient( self::$plugin_upgrade_lock_key );
518
	}
519
520
	/**
521
	 * Saves all the currently active modules to options.
522
	 * Also fires Action hooks for each newly activated and deactivated module.
523
	 *
524
	 * @param $modules Array Array of active modules to be saved in options.
525
	 *
526
	 * @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...
527
	 */
528
	static function update_active_modules( $modules ) {
529
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
530
		$active_modules       = self::get_active_modules();
531
		$new_active_modules   = array_diff( $modules, $current_modules );
532
		$new_inactive_modules = array_diff( $active_modules, $modules );
533
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
534
		$reindexed_modules    = array_values( $new_current_modules );
535
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
536
537
		foreach ( $new_active_modules as $module ) {
538
			/**
539
			 * Fires when a specific module is activated.
540
			 *
541
			 * @since 1.9.0
542
			 *
543
			 * @param string $module Module slug.
544
			 * @param boolean $success whether the module was activated. @since 4.2
545
			 */
546
			do_action( 'jetpack_activate_module', $module, $success );
547
			/**
548
			 * Fires when a module is activated.
549
			 * The dynamic part of the filter, $module, is the module slug.
550
			 *
551
			 * @since 1.9.0
552
			 *
553
			 * @param string $module Module slug.
554
			 */
555
			do_action( "jetpack_activate_module_$module", $module );
556
		}
557
558
		foreach ( $new_inactive_modules as $module ) {
559
			/**
560
			 * Fired after a module has been deactivated.
561
			 *
562
			 * @since 4.2.0
563
			 *
564
			 * @param string $module Module slug.
565
			 * @param boolean $success whether the module was deactivated.
566
			 */
567
			do_action( 'jetpack_deactivate_module', $module, $success );
568
			/**
569
			 * Fires when a module is deactivated.
570
			 * The dynamic part of the filter, $module, is the module slug.
571
			 *
572
			 * @since 1.9.0
573
			 *
574
			 * @param string $module Module slug.
575
			 */
576
			do_action( "jetpack_deactivate_module_$module", $module );
577
		}
578
579
		return $success;
580
	}
581
582
	static function delete_active_modules() {
583
		self::update_active_modules( array() );
584
	}
585
586
	/**
587
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
588
	 * available.
589
	 */
590
	public function add_configure_hook() {
591
		global $wp_filter;
592
593
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
594
		if ( false !== $current_priority ) {
595
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
596
		}
597
598
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
599
		sort( $taken_priorities );
600
601
		$first_priority = array_shift( $taken_priorities );
602
603
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
604
			$new_priority = - PHP_INT_MAX;
605
		} else {
606
			$new_priority = $first_priority - 1;
607
		}
608
609
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
610
	}
611
612
	/**
613
	 * Constructor.  Initializes WordPress hooks
614
	 */
615
	private function __construct() {
616
		/*
617
		 * Check for and alert any deprecated hooks
618
		 */
619
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
620
621
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
622
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
623
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
624
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
625
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
626
627
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
628
629
		add_filter(
630
			'jetpack_signature_check_token',
631
			array( __CLASS__, 'verify_onboarding_token' ),
632
			10,
633
			3
634
		);
635
636
		/**
637
		 * Prepare Gutenberg Editor functionality
638
		 */
639
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
640
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
641
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
642
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
643
644
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
645
646
		// Unlink user before deleting the user from WP.com.
647
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
648
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
649
650
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
651
652
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
653
		add_action( 'login_init', array( $this, 'login_init' ) );
654
655
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
656
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
657
658
		add_action( 'admin_init', array( $this, 'admin_init' ) );
659
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
660
661
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
662
663
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
664
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
665
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
666
667
		// returns HTTPS support status
668
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
669
670
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
671
672
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
673
674
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
675
676
		/**
677
		 * These actions run checks to load additional files.
678
		 * They check for external files or plugins, so they need to run as late as possible.
679
		 */
680
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
681
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
682
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
683
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
684
685
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
686
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
687
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
688
689
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
690
691
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
692
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
693
694
		// A filter to control all just in time messages
695
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
696
697
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
698
699
		/*
700
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
701
		 * We should make sure to only do this for front end links.
702
		 */
703
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
704
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
705
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
706
707
			/*
708
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
709
			 * so they point moderation links on emails to Calypso.
710
			 */
711
			jetpack_require_lib( 'functions.wp-notify' );
712
		}
713
714
		add_action(
715
			'plugins_loaded',
716
			function() {
717
				if ( User_Agent_Info::is_mobile_app() ) {
718
					add_filter( 'get_edit_post_link', '__return_empty_string' );
719
				}
720
			}
721
		);
722
723
		// Update the Jetpack plan from API on heartbeats.
724
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
725
726
		/**
727
		 * This is the hack to concatenate all css files into one.
728
		 * For description and reasoning see the implode_frontend_css method.
729
		 *
730
		 * Super late priority so we catch all the registered styles.
731
		 */
732
		if ( ! is_admin() ) {
733
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
734
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
735
		}
736
737
		/**
738
		 * These are sync actions that we need to keep track of for jitms
739
		 */
740
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
741
742
		// Actually push the stats on shutdown.
743
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
744
			add_action( 'shutdown', array( $this, 'push_stats' ) );
745
		}
746
747
		// Actions for Manager::authorize().
748
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
749
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
750
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
751
752
		// Filters for the Manager::get_token() urls and request body.
753
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
754
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
755
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
756
	}
757
758
	/**
759
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
760
	 * Config object.
761
	 */
762
	public function configure() {
763
		$config = new Config();
764
765
		foreach (
766
			array(
767
				'sync',
768
				'tracking',
769
				'tos',
770
			)
771
			as $feature
772
		) {
773
			$config->ensure( $feature );
774
		}
775
776
		$config->ensure(
777
			'connection',
778
			array(
779
				'slug' => 'jetpack',
780
				'name' => 'Jetpack',
781
			)
782
		);
783
784
		if ( is_admin() ) {
785
			$config->ensure( 'jitm' );
786
		}
787
788
		if ( ! $this->connection_manager ) {
789
			$this->connection_manager = new Connection_Manager( 'jetpack' );
790
		}
791
792
		/*
793
		 * Load things that should only be in Network Admin.
794
		 *
795
		 * For now blow away everything else until a more full
796
		 * understanding of what is needed at the network level is
797
		 * available
798
		 */
799
		if ( is_multisite() ) {
800
			$network = Jetpack_Network::init();
801
			$network->set_connection( $this->connection_manager );
802
		}
803
804
		if ( $this->connection_manager->is_active() ) {
805
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
806
807
			Jetpack_Heartbeat::init();
808
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
809
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
810
				Jetpack_Search_Performance_Logger::init();
811
			}
812
		}
813
814
		// Initialize remote file upload request handlers.
815
		$this->add_remote_request_handlers();
816
817
		/*
818
		 * Enable enhanced handling of previewing sites in Calypso
819
		 */
820
		if ( self::is_active() ) {
821
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
822
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
823
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
824
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
825
		}
826
	}
827
828
	/**
829
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
830
	 * initialization code.
831
	 *
832
	 * @action plugins_loaded
833
	 */
834
	public function late_initialization() {
835
		add_action( 'plugins_loaded', array( 'Jetpack', 'plugin_textdomain' ), 99 );
836
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
837
838
		Partner::init();
839
840
		/**
841
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
842
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
843
		 *
844
		 * @since 8.1.0
845
		 *
846
		 * @param Jetpack $jetpack the main plugin class object.
847
		 */
848
		do_action( 'jetpack_loaded', $this );
849
850
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
851
	}
852
853
	/**
854
	 * Sets up the XMLRPC request handlers.
855
	 *
856
	 * @deprecated since 7.7.0
857
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
858
	 *
859
	 * @param array                 $request_params Incoming request parameters.
860
	 * @param Boolean               $is_active      Whether the connection is currently active.
861
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
862
	 * @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...
863
	 */
864 View Code Duplication
	public function setup_xmlrpc_handlers(
865
		$request_params,
866
		$is_active,
867
		$is_signed,
868
		Jetpack_XMLRPC_Server $xmlrpc_server = null
869
	) {
870
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
871
872
		if ( ! $this->connection_manager ) {
873
			$this->connection_manager = new Connection_Manager();
874
		}
875
876
		return $this->connection_manager->setup_xmlrpc_handlers(
877
			$request_params,
878
			$is_active,
879
			$is_signed,
880
			$xmlrpc_server
881
		);
882
	}
883
884
	/**
885
	 * Initialize REST API registration connector.
886
	 *
887
	 * @deprecated since 7.7.0
888
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
889
	 */
890 View Code Duplication
	public function initialize_rest_api_registration_connector() {
891
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
892
893
		if ( ! $this->connection_manager ) {
894
			$this->connection_manager = new Connection_Manager();
895
		}
896
897
		$this->connection_manager->initialize_rest_api_registration_connector();
898
	}
899
900
	/**
901
	 * This is ported over from the manage module, which has been deprecated and baked in here.
902
	 *
903
	 * @param $domains
904
	 */
905
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
906
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
907
	}
908
909
	/**
910
	 * Return $domains, with 'wordpress.com' appended.
911
	 * This is ported over from the manage module, which has been deprecated and baked in here.
912
	 *
913
	 * @param $domains
914
	 * @return array
915
	 */
916
	function allow_wpcom_domain( $domains ) {
917
		if ( empty( $domains ) ) {
918
			$domains = array();
919
		}
920
		$domains[] = 'wordpress.com';
921
		return array_unique( $domains );
922
	}
923
924
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
925
		$post = get_post( $post_id );
926
927
		if ( empty( $post ) ) {
928
			return $default_url;
929
		}
930
931
		$post_type = $post->post_type;
932
933
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
934
		// https://en.support.wordpress.com/custom-post-types/
935
		$allowed_post_types = array(
936
			'post',
937
			'page',
938
			'jetpack-portfolio',
939
			'jetpack-testimonial',
940
		);
941
942
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
943
			return $default_url;
944
		}
945
946
		return esc_url(
947
			Redirect::get_url(
948
				'calypso-edit-' . $post_type,
949
				array(
950
					'path' => $post_id,
951
				)
952
			)
953
		);
954
	}
955
956
	function point_edit_comment_links_to_calypso( $url ) {
957
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
958
		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...
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
959
960
		return esc_url(
961
			Redirect::get_url(
962
				'calypso-edit-comment',
963
				array(
964
					'path' => $query_args['amp;c'],
965
				)
966
			)
967
		);
968
969
	}
970
971
	function jetpack_track_last_sync_callback( $params ) {
972
		/**
973
		 * Filter to turn off jitm caching
974
		 *
975
		 * @since 5.4.0
976
		 *
977
		 * @param bool false Whether to cache just in time messages
978
		 */
979
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
980
			return $params;
981
		}
982
983
		if ( is_array( $params ) && isset( $params[0] ) ) {
984
			$option = $params[0];
985
			if ( 'active_plugins' === $option ) {
986
				// use the cache if we can, but not terribly important if it gets evicted
987
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
988
			}
989
		}
990
991
		return $params;
992
	}
993
994
	function jetpack_connection_banner_callback() {
995
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
996
997
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
998
		if (
999
			isset( $_REQUEST['dismissBanner'] ) &&
1000
			! Jetpack_Connection_Banner::force_display()
1001
		) {
1002
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1003
			wp_send_json_success();
1004
		}
1005
1006
		wp_die();
1007
	}
1008
1009
	/**
1010
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1011
	 * Only used in our alternate XML-RPC endpoint, where we want to
1012
	 * ensure that Core and other plugins' methods are not exposed.
1013
	 *
1014
	 * @deprecated since 7.7.0
1015
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1016
	 *
1017
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1018
	 * @return array Filtered $methods
1019
	 */
1020 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1021
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1022
1023
		if ( ! $this->connection_manager ) {
1024
			$this->connection_manager = new Connection_Manager();
1025
		}
1026
1027
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1028
	}
1029
1030
	/**
1031
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1032
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1033
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1034
	 * which is accessible via a different URI. Most of the below is copied directly
1035
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1036
	 *
1037
	 * @deprecated since 7.7.0
1038
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1039
	 */
1040 View Code Duplication
	public function alternate_xmlrpc() {
1041
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1042
1043
		if ( ! $this->connection_manager ) {
1044
			$this->connection_manager = new Connection_Manager();
1045
		}
1046
1047
		$this->connection_manager->alternate_xmlrpc();
1048
	}
1049
1050
	/**
1051
	 * The callback for the JITM ajax requests.
1052
	 *
1053
	 * @deprecated since 7.9.0
1054
	 */
1055
	function jetpack_jitm_ajax_callback() {
1056
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1057
	}
1058
1059
	/**
1060
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1061
	 */
1062
	function push_stats() {
1063
		if ( ! empty( $this->stats ) ) {
1064
			$this->do_stats( 'server_side' );
1065
		}
1066
	}
1067
1068
	/**
1069
	 * Sets the Jetpack custom capabilities.
1070
	 *
1071
	 * @param string[] $caps    Array of the user's capabilities.
1072
	 * @param string   $cap     Capability name.
1073
	 * @param int      $user_id The user ID.
1074
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1075
	 */
1076
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1077
		$is_development_mode = ( new Status() )->is_development_mode();
1078
		switch ( $cap ) {
1079
			case 'jetpack_manage_modules':
1080
			case 'jetpack_activate_modules':
1081
			case 'jetpack_deactivate_modules':
1082
				$caps = array( 'manage_options' );
1083
				break;
1084
			case 'jetpack_configure_modules':
1085
				$caps = array( 'manage_options' );
1086
				break;
1087
			case 'jetpack_manage_autoupdates':
1088
				$caps = array(
1089
					'manage_options',
1090
					'update_plugins',
1091
				);
1092
				break;
1093
			case 'jetpack_network_admin_page':
1094
			case 'jetpack_network_settings_page':
1095
				$caps = array( 'manage_network_plugins' );
1096
				break;
1097
			case 'jetpack_network_sites_page':
1098
				$caps = array( 'manage_sites' );
1099
				break;
1100
			case 'jetpack_admin_page':
1101
				if ( $is_development_mode ) {
1102
					$caps = array( 'manage_options' );
1103
					break;
1104
				} else {
1105
					$caps = array( 'read' );
1106
				}
1107
				break;
1108
		}
1109
		return $caps;
1110
	}
1111
1112
	/**
1113
	 * Require a Jetpack authentication.
1114
	 *
1115
	 * @deprecated since 7.7.0
1116
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1117
	 */
1118 View Code Duplication
	public function require_jetpack_authentication() {
1119
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1120
1121
		if ( ! $this->connection_manager ) {
1122
			$this->connection_manager = new Connection_Manager();
1123
		}
1124
1125
		$this->connection_manager->require_jetpack_authentication();
1126
	}
1127
1128
	/**
1129
	 * Load language files
1130
	 *
1131
	 * @action plugins_loaded
1132
	 */
1133
	public static function plugin_textdomain() {
1134
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1135
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1136
	}
1137
1138
	/**
1139
	 * Register assets for use in various modules and the Jetpack admin page.
1140
	 *
1141
	 * @uses wp_script_is, wp_register_script, plugins_url
1142
	 * @action wp_loaded
1143
	 * @return null
1144
	 */
1145
	public function register_assets() {
1146 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1147
			wp_register_script(
1148
				'jetpack-gallery-settings',
1149
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1150
				array( 'media-views' ),
1151
				'20121225'
1152
			);
1153
		}
1154
1155
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1156
			wp_register_script(
1157
				'jetpack-twitter-timeline',
1158
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1159
				array( 'jquery' ),
1160
				'4.0.0',
1161
				true
1162
			);
1163
		}
1164
1165
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1166
			wp_register_script(
1167
				'jetpack-facebook-embed',
1168
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1169
				array(),
1170
				null,
1171
				true
1172
			);
1173
1174
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1175
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1176
			if ( ! is_numeric( $fb_app_id ) ) {
1177
				$fb_app_id = '';
1178
			}
1179
			wp_localize_script(
1180
				'jetpack-facebook-embed',
1181
				'jpfbembed',
1182
				array(
1183
					'appid'  => $fb_app_id,
1184
					'locale' => $this->get_locale(),
1185
				)
1186
			);
1187
		}
1188
1189
		/**
1190
		 * As jetpack_register_genericons is by default fired off a hook,
1191
		 * the hook may have already fired by this point.
1192
		 * So, let's just trigger it manually.
1193
		 */
1194
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1195
		jetpack_register_genericons();
1196
1197
		/**
1198
		 * Register the social logos
1199
		 */
1200
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1201
		jetpack_register_social_logos();
1202
1203 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1204
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1205
		}
1206
	}
1207
1208
	/**
1209
	 * Guess locale from language code.
1210
	 *
1211
	 * @param string $lang Language code.
1212
	 * @return string|bool
1213
	 */
1214 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1215
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1216
			return 'en_US';
1217
		}
1218
1219
		if ( ! class_exists( 'GP_Locales' ) ) {
1220
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1221
				return false;
1222
			}
1223
1224
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1225
		}
1226
1227
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1228
			// WP.com: get_locale() returns 'it'
1229
			$locale = GP_Locales::by_slug( $lang );
1230
		} else {
1231
			// Jetpack: get_locale() returns 'it_IT';
1232
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1233
		}
1234
1235
		if ( ! $locale ) {
1236
			return false;
1237
		}
1238
1239
		if ( empty( $locale->facebook_locale ) ) {
1240
			if ( empty( $locale->wp_locale ) ) {
1241
				return false;
1242
			} else {
1243
				// Facebook SDK is smart enough to fall back to en_US if a
1244
				// locale isn't supported. Since supported Facebook locales
1245
				// can fall out of sync, we'll attempt to use the known
1246
				// wp_locale value and rely on said fallback.
1247
				return $locale->wp_locale;
1248
			}
1249
		}
1250
1251
		return $locale->facebook_locale;
1252
	}
1253
1254
	/**
1255
	 * Get the locale.
1256
	 *
1257
	 * @return string|bool
1258
	 */
1259
	function get_locale() {
1260
		$locale = $this->guess_locale_from_lang( get_locale() );
1261
1262
		if ( ! $locale ) {
1263
			$locale = 'en_US';
1264
		}
1265
1266
		return $locale;
1267
	}
1268
1269
	/**
1270
	 * Return the network_site_url so that .com knows what network this site is a part of.
1271
	 *
1272
	 * @param  bool $option
1273
	 * @return string
1274
	 */
1275
	public function jetpack_main_network_site_option( $option ) {
1276
		return network_site_url();
1277
	}
1278
	/**
1279
	 * Network Name.
1280
	 */
1281
	static function network_name( $option = null ) {
1282
		global $current_site;
1283
		return $current_site->site_name;
1284
	}
1285
	/**
1286
	 * Does the network allow new user and site registrations.
1287
	 *
1288
	 * @return string
1289
	 */
1290
	static function network_allow_new_registrations( $option = null ) {
1291
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1292
	}
1293
	/**
1294
	 * Does the network allow admins to add new users.
1295
	 *
1296
	 * @return boolian
1297
	 */
1298
	static function network_add_new_users( $option = null ) {
1299
		return (bool) get_site_option( 'add_new_users' );
1300
	}
1301
	/**
1302
	 * File upload psace left per site in MB.
1303
	 *  -1 means NO LIMIT.
1304
	 *
1305
	 * @return number
1306
	 */
1307
	static function network_site_upload_space( $option = null ) {
1308
		// value in MB
1309
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1310
	}
1311
1312
	/**
1313
	 * Network allowed file types.
1314
	 *
1315
	 * @return string
1316
	 */
1317
	static function network_upload_file_types( $option = null ) {
1318
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1319
	}
1320
1321
	/**
1322
	 * Maximum file upload size set by the network.
1323
	 *
1324
	 * @return number
1325
	 */
1326
	static function network_max_upload_file_size( $option = null ) {
1327
		// value in KB
1328
		return get_site_option( 'fileupload_maxk', 300 );
1329
	}
1330
1331
	/**
1332
	 * Lets us know if a site allows admins to manage the network.
1333
	 *
1334
	 * @return array
1335
	 */
1336
	static function network_enable_administration_menus( $option = null ) {
1337
		return get_site_option( 'menu_items' );
1338
	}
1339
1340
	/**
1341
	 * If a user has been promoted to or demoted from admin, we need to clear the
1342
	 * jetpack_other_linked_admins transient.
1343
	 *
1344
	 * @since 4.3.2
1345
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1346
	 *
1347
	 * @param int    $user_id   The user ID whose role changed.
1348
	 * @param string $role      The new role.
1349
	 * @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...
1350
	 */
1351
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1352
		if ( 'administrator' == $role
1353
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1354
			|| is_null( $old_roles )
1355
		) {
1356
			delete_transient( 'jetpack_other_linked_admins' );
1357
		}
1358
	}
1359
1360
	/**
1361
	 * Checks to see if there are any other users available to become primary
1362
	 * Users must both:
1363
	 * - Be linked to wpcom
1364
	 * - Be an admin
1365
	 *
1366
	 * @return mixed False if no other users are linked, Int if there are.
1367
	 */
1368
	static function get_other_linked_admins() {
1369
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1370
1371
		if ( false === $other_linked_users ) {
1372
			$admins = get_users( array( 'role' => 'administrator' ) );
1373
			if ( count( $admins ) > 1 ) {
1374
				$available = array();
1375
				foreach ( $admins as $admin ) {
1376
					if ( self::is_user_connected( $admin->ID ) ) {
1377
						$available[] = $admin->ID;
1378
					}
1379
				}
1380
1381
				$count_connected_admins = count( $available );
1382
				if ( count( $available ) > 1 ) {
1383
					$other_linked_users = $count_connected_admins;
1384
				} else {
1385
					$other_linked_users = 0;
1386
				}
1387
			} else {
1388
				$other_linked_users = 0;
1389
			}
1390
1391
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1392
		}
1393
1394
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1395
	}
1396
1397
	/**
1398
	 * Return whether we are dealing with a multi network setup or not.
1399
	 * The reason we are type casting this is because we want to avoid the situation where
1400
	 * the result is false since when is_main_network_option return false it cases
1401
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1402
	 * database which could be set to anything as opposed to what this function returns.
1403
	 *
1404
	 * @param  bool $option
1405
	 *
1406
	 * @return boolean
1407
	 */
1408
	public function is_main_network_option( $option ) {
1409
		// return '1' or ''
1410
		return (string) (bool) self::is_multi_network();
1411
	}
1412
1413
	/**
1414
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1415
	 *
1416
	 * @param  string $option
1417
	 * @return boolean
1418
	 */
1419
	public function is_multisite( $option ) {
1420
		return (string) (bool) is_multisite();
1421
	}
1422
1423
	/**
1424
	 * Implemented since there is no core is multi network function
1425
	 * Right now there is no way to tell if we which network is the dominant network on the system
1426
	 *
1427
	 * @since  3.3
1428
	 * @return boolean
1429
	 */
1430 View Code Duplication
	public static function is_multi_network() {
1431
		global  $wpdb;
1432
1433
		// if we don't have a multi site setup no need to do any more
1434
		if ( ! is_multisite() ) {
1435
			return false;
1436
		}
1437
1438
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1439
		if ( $num_sites > 1 ) {
1440
			return true;
1441
		} else {
1442
			return false;
1443
		}
1444
	}
1445
1446
	/**
1447
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1448
	 *
1449
	 * @return null
1450
	 */
1451
	function update_jetpack_main_network_site_option() {
1452
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1453
	}
1454
	/**
1455
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1456
	 */
1457
	function update_jetpack_network_settings() {
1458
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1459
		// Only sync this info for the main network site.
1460
	}
1461
1462
	/**
1463
	 * Get back if the current site is single user site.
1464
	 *
1465
	 * @return bool
1466
	 */
1467 View Code Duplication
	public static function is_single_user_site() {
1468
		global $wpdb;
1469
1470
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1471
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1472
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1473
		}
1474
		return 1 === (int) $some_users;
1475
	}
1476
1477
	/**
1478
	 * Returns true if the site has file write access false otherwise.
1479
	 *
1480
	 * @return string ( '1' | '0' )
1481
	 **/
1482
	public static function file_system_write_access() {
1483
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1484
			require_once ABSPATH . 'wp-admin/includes/file.php';
1485
		}
1486
1487
		require_once ABSPATH . 'wp-admin/includes/template.php';
1488
1489
		$filesystem_method = get_filesystem_method();
1490
		if ( $filesystem_method === 'direct' ) {
1491
			return 1;
1492
		}
1493
1494
		ob_start();
1495
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1496
		ob_end_clean();
1497
		if ( $filesystem_credentials_are_stored ) {
1498
			return 1;
1499
		}
1500
		return 0;
1501
	}
1502
1503
	/**
1504
	 * Finds out if a site is using a version control system.
1505
	 *
1506
	 * @return string ( '1' | '0' )
1507
	 **/
1508
	public static function is_version_controlled() {
1509
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1510
		return (string) (int) Functions::is_version_controlled();
1511
	}
1512
1513
	/**
1514
	 * Determines whether the current theme supports featured images or not.
1515
	 *
1516
	 * @return string ( '1' | '0' )
1517
	 */
1518
	public static function featured_images_enabled() {
1519
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1520
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1521
	}
1522
1523
	/**
1524
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1525
	 *
1526
	 * @deprecated 4.7 use get_avatar_url instead.
1527
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1528
	 * @param int               $size Size of the avatar image
1529
	 * @param string            $default URL to a default image to use if no avatar is available
1530
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1531
	 *
1532
	 * @return array
1533
	 */
1534
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1535
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1536
		return get_avatar_url(
1537
			$id_or_email,
1538
			array(
1539
				'size'          => $size,
1540
				'default'       => $default,
1541
				'force_default' => $force_display,
1542
			)
1543
		);
1544
	}
1545
1546
	/**
1547
	 * jetpack_updates is saved in the following schema:
1548
	 *
1549
	 * array (
1550
	 *      'plugins'                       => (int) Number of plugin updates available.
1551
	 *      'themes'                        => (int) Number of theme updates available.
1552
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1553
	 *      'translations'                  => (int) Number of translation updates available.
1554
	 *      'total'                         => (int) Total of all available updates.
1555
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1556
	 * )
1557
	 *
1558
	 * @return array
1559
	 */
1560
	public static function get_updates() {
1561
		$update_data = wp_get_update_data();
1562
1563
		// Stores the individual update counts as well as the total count.
1564
		if ( isset( $update_data['counts'] ) ) {
1565
			$updates = $update_data['counts'];
1566
		}
1567
1568
		// If we need to update WordPress core, let's find the latest version number.
1569 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1570
			$cur = get_preferred_from_update_core();
1571
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1572
				$updates['wp_update_version'] = $cur->current;
1573
			}
1574
		}
1575
		return isset( $updates ) ? $updates : array();
1576
	}
1577
1578
	public static function get_update_details() {
1579
		$update_details = array(
1580
			'update_core'    => get_site_transient( 'update_core' ),
1581
			'update_plugins' => get_site_transient( 'update_plugins' ),
1582
			'update_themes'  => get_site_transient( 'update_themes' ),
1583
		);
1584
		return $update_details;
1585
	}
1586
1587
	public static function refresh_update_data() {
1588
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1589
1590
	}
1591
1592
	public static function refresh_theme_data() {
1593
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1594
	}
1595
1596
	/**
1597
	 * Is Jetpack active?
1598
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1599
	 *
1600
	 * @return bool
1601
	 */
1602
	public static function is_active() {
1603
		return self::connection()->is_active();
1604
	}
1605
1606
	/**
1607
	 * Make an API call to WordPress.com for plan status
1608
	 *
1609
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1610
	 *
1611
	 * @return bool True if plan is updated, false if no update
1612
	 */
1613
	public static function refresh_active_plan_from_wpcom() {
1614
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1615
		return Jetpack_Plan::refresh_from_wpcom();
1616
	}
1617
1618
	/**
1619
	 * Get the plan that this Jetpack site is currently using
1620
	 *
1621
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1622
	 * @return array Active Jetpack plan details.
1623
	 */
1624
	public static function get_active_plan() {
1625
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1626
		return Jetpack_Plan::get();
1627
	}
1628
1629
	/**
1630
	 * Determine whether the active plan supports a particular feature
1631
	 *
1632
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1633
	 * @return bool True if plan supports feature, false if not.
1634
	 */
1635
	public static function active_plan_supports( $feature ) {
1636
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1637
		return Jetpack_Plan::supports( $feature );
1638
	}
1639
1640
	/**
1641
	 * Deprecated: Is Jetpack in development (offline) mode?
1642
	 *
1643
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1644
	 * and themes still use it, and we do not want to flood them with notices.
1645
	 *
1646
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1647
	 *
1648
	 * @deprecated since 8.0.
1649
	 */
1650
	public static function is_development_mode() {
1651
		return ( new Status() )->is_development_mode();
1652
	}
1653
1654
	/**
1655
	 * Whether the site is currently onboarding or not.
1656
	 * A site is considered as being onboarded if it currently has an onboarding token.
1657
	 *
1658
	 * @since 5.8
1659
	 *
1660
	 * @access public
1661
	 * @static
1662
	 *
1663
	 * @return bool True if the site is currently onboarding, false otherwise
1664
	 */
1665
	public static function is_onboarding() {
1666
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1667
	}
1668
1669
	/**
1670
	 * Determines reason for Jetpack development mode.
1671
	 */
1672
	public static function development_mode_trigger_text() {
1673
		if ( ! ( new Status() )->is_development_mode() ) {
1674
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1675
		}
1676
1677
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1678
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1679
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1680
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1681
		} else {
1682
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1683
		}
1684
1685
		return $notice;
1686
1687
	}
1688
	/**
1689
	 * Get Jetpack development mode notice text and notice class.
1690
	 *
1691
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1692
	 */
1693
	public static function show_development_mode_notice() {
1694 View Code Duplication
		if ( ( new Status() )->is_development_mode() ) {
1695
			$notice = sprintf(
1696
				/* translators: %s is a URL */
1697
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1698
				Redirect::get_url( 'jetpack-support-development-mode' )
1699
			);
1700
1701
			$notice .= ' ' . self::development_mode_trigger_text();
1702
1703
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1704
		}
1705
1706
		// Throw up a notice if using a development version and as for feedback.
1707
		if ( self::is_development_version() ) {
1708
			/* translators: %s is a URL */
1709
			$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' ) );
1710
1711
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1712
		}
1713
		// Throw up a notice if using staging mode
1714 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1715
			/* translators: %s is a URL */
1716
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1717
1718
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1719
		}
1720
	}
1721
1722
	/**
1723
	 * Whether Jetpack's version maps to a public release, or a development version.
1724
	 */
1725
	public static function is_development_version() {
1726
		/**
1727
		 * Allows filtering whether this is a development version of Jetpack.
1728
		 *
1729
		 * This filter is especially useful for tests.
1730
		 *
1731
		 * @since 4.3.0
1732
		 *
1733
		 * @param bool $development_version Is this a develoment version of Jetpack?
1734
		 */
1735
		return (bool) apply_filters(
1736
			'jetpack_development_version',
1737
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1738
		);
1739
	}
1740
1741
	/**
1742
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1743
	 */
1744
	public static function is_user_connected( $user_id = false ) {
1745
		return self::connection()->is_user_connected( $user_id );
1746
	}
1747
1748
	/**
1749
	 * Get the wpcom user data of the current|specified connected user.
1750
	 */
1751 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1752
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1753
		if ( ! $user_id ) {
1754
			$user_id = get_current_user_id();
1755
		}
1756
1757
		$transient_key = "jetpack_connected_user_data_$user_id";
1758
1759
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1760
			return $cached_user_data;
1761
		}
1762
1763
		$xml = new Jetpack_IXR_Client(
1764
			array(
1765
				'user_id' => $user_id,
1766
			)
1767
		);
1768
		$xml->query( 'wpcom.getUser' );
1769
		if ( ! $xml->isError() ) {
1770
			$user_data = $xml->getResponse();
1771
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1772
			return $user_data;
1773
		}
1774
1775
		return false;
1776
	}
1777
1778
	/**
1779
	 * Get the wpcom email of the current|specified connected user.
1780
	 */
1781
	public static function get_connected_user_email( $user_id = null ) {
1782
		if ( ! $user_id ) {
1783
			$user_id = get_current_user_id();
1784
		}
1785
1786
		$xml = new Jetpack_IXR_Client(
1787
			array(
1788
				'user_id' => $user_id,
1789
			)
1790
		);
1791
		$xml->query( 'wpcom.getUserEmail' );
1792
		if ( ! $xml->isError() ) {
1793
			return $xml->getResponse();
1794
		}
1795
		return false;
1796
	}
1797
1798
	/**
1799
	 * Get the wpcom email of the master user.
1800
	 */
1801
	public static function get_master_user_email() {
1802
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1803
		if ( $master_user_id ) {
1804
			return self::get_connected_user_email( $master_user_id );
1805
		}
1806
		return '';
1807
	}
1808
1809
	/**
1810
	 * Whether the current user is the connection owner.
1811
	 *
1812
	 * @deprecated since 7.7
1813
	 *
1814
	 * @return bool Whether the current user is the connection owner.
1815
	 */
1816
	public function current_user_is_connection_owner() {
1817
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1818
		return self::connection()->is_connection_owner();
1819
	}
1820
1821
	/**
1822
	 * Gets current user IP address.
1823
	 *
1824
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1825
	 *
1826
	 * @return string                  Current user IP address.
1827
	 */
1828
	public static function current_user_ip( $check_all_headers = false ) {
1829
		if ( $check_all_headers ) {
1830
			foreach ( array(
1831
				'HTTP_CF_CONNECTING_IP',
1832
				'HTTP_CLIENT_IP',
1833
				'HTTP_X_FORWARDED_FOR',
1834
				'HTTP_X_FORWARDED',
1835
				'HTTP_X_CLUSTER_CLIENT_IP',
1836
				'HTTP_FORWARDED_FOR',
1837
				'HTTP_FORWARDED',
1838
				'HTTP_VIA',
1839
			) as $key ) {
1840
				if ( ! empty( $_SERVER[ $key ] ) ) {
1841
					return $_SERVER[ $key ];
1842
				}
1843
			}
1844
		}
1845
1846
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1847
	}
1848
1849
	/**
1850
	 * Synchronize connected user role changes
1851
	 */
1852
	function user_role_change( $user_id ) {
1853
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1854
		Users::user_role_change( $user_id );
1855
	}
1856
1857
	/**
1858
	 * Loads the currently active modules.
1859
	 */
1860
	public static function load_modules() {
1861
		$is_development_mode = ( new Status() )->is_development_mode();
1862
		if (
1863
			! self::is_active()
1864
			&& ! $is_development_mode
1865
			&& ! self::is_onboarding()
1866
			&& (
1867
				! is_multisite()
1868
				|| ! get_site_option( 'jetpack_protect_active' )
1869
			)
1870
		) {
1871
			return;
1872
		}
1873
1874
		$version = Jetpack_Options::get_option( 'version' );
1875 View Code Duplication
		if ( ! $version ) {
1876
			$version = $old_version = JETPACK__VERSION . ':' . time();
1877
			/** This action is documented in class.jetpack.php */
1878
			do_action( 'updating_jetpack_version', $version, false );
1879
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1880
		}
1881
		list( $version ) = explode( ':', $version );
1882
1883
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1884
1885
		$modules_data = array();
1886
1887
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1888
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1889
			$updated_modules = array();
1890
			foreach ( $modules as $module ) {
1891
				$modules_data[ $module ] = self::get_module( $module );
1892
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1893
					continue;
1894
				}
1895
1896
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1897
					continue;
1898
				}
1899
1900
				$updated_modules[] = $module;
1901
			}
1902
1903
			$modules = array_diff( $modules, $updated_modules );
1904
		}
1905
1906
		foreach ( $modules as $index => $module ) {
1907
			// If we're in dev mode, disable modules requiring a connection
1908
			if ( $is_development_mode ) {
1909
				// Prime the pump if we need to
1910
				if ( empty( $modules_data[ $module ] ) ) {
1911
					$modules_data[ $module ] = self::get_module( $module );
1912
				}
1913
				// If the module requires a connection, but we're in local mode, don't include it.
1914
				if ( $modules_data[ $module ]['requires_connection'] ) {
1915
					continue;
1916
				}
1917
			}
1918
1919
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1920
				continue;
1921
			}
1922
1923
			if ( ! include_once self::get_module_path( $module ) ) {
1924
				unset( $modules[ $index ] );
1925
				self::update_active_modules( array_values( $modules ) );
1926
				continue;
1927
			}
1928
1929
			/**
1930
			 * Fires when a specific module is loaded.
1931
			 * The dynamic part of the hook, $module, is the module slug.
1932
			 *
1933
			 * @since 1.1.0
1934
			 */
1935
			do_action( 'jetpack_module_loaded_' . $module );
1936
		}
1937
1938
		/**
1939
		 * Fires when all the modules are loaded.
1940
		 *
1941
		 * @since 1.1.0
1942
		 */
1943
		do_action( 'jetpack_modules_loaded' );
1944
1945
		// 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.
1946
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1947
	}
1948
1949
	/**
1950
	 * Check if Jetpack's REST API compat file should be included
1951
	 *
1952
	 * @action plugins_loaded
1953
	 * @return null
1954
	 */
1955
	public function check_rest_api_compat() {
1956
		/**
1957
		 * Filters the list of REST API compat files to be included.
1958
		 *
1959
		 * @since 2.2.5
1960
		 *
1961
		 * @param array $args Array of REST API compat files to include.
1962
		 */
1963
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1964
1965
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1966
			require_once $_jetpack_rest_api_compat_include;
1967
		}
1968
	}
1969
1970
	/**
1971
	 * Gets all plugins currently active in values, regardless of whether they're
1972
	 * traditionally activated or network activated.
1973
	 *
1974
	 * @todo Store the result in core's object cache maybe?
1975
	 */
1976
	public static function get_active_plugins() {
1977
		$active_plugins = (array) get_option( 'active_plugins', array() );
1978
1979
		if ( is_multisite() ) {
1980
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1981
			// whereas active_plugins stores them in the values.
1982
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1983
			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...
1984
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1985
			}
1986
		}
1987
1988
		sort( $active_plugins );
1989
1990
		return array_unique( $active_plugins );
1991
	}
1992
1993
	/**
1994
	 * Gets and parses additional plugin data to send with the heartbeat data
1995
	 *
1996
	 * @since 3.8.1
1997
	 *
1998
	 * @return array Array of plugin data
1999
	 */
2000
	public static function get_parsed_plugin_data() {
2001
		if ( ! function_exists( 'get_plugins' ) ) {
2002
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2003
		}
2004
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2005
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2006
		$active_plugins = self::get_active_plugins();
2007
2008
		$plugins = array();
2009
		foreach ( $all_plugins as $path => $plugin_data ) {
2010
			$plugins[ $path ] = array(
2011
				'is_active' => in_array( $path, $active_plugins ),
2012
				'file'      => $path,
2013
				'name'      => $plugin_data['Name'],
2014
				'version'   => $plugin_data['Version'],
2015
				'author'    => $plugin_data['Author'],
2016
			);
2017
		}
2018
2019
		return $plugins;
2020
	}
2021
2022
	/**
2023
	 * Gets and parses theme data to send with the heartbeat data
2024
	 *
2025
	 * @since 3.8.1
2026
	 *
2027
	 * @return array Array of theme data
2028
	 */
2029
	public static function get_parsed_theme_data() {
2030
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2031
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2032
2033
		$themes = array();
2034
		foreach ( $all_themes as $slug => $theme_data ) {
2035
			$theme_headers = array();
2036
			foreach ( $header_keys as $header_key ) {
2037
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2038
			}
2039
2040
			$themes[ $slug ] = array(
2041
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2042
				'slug'            => $slug,
2043
				'theme_root'      => $theme_data->get_theme_root_uri(),
2044
				'parent'          => $theme_data->parent(),
2045
				'headers'         => $theme_headers,
2046
			);
2047
		}
2048
2049
		return $themes;
2050
	}
2051
2052
	/**
2053
	 * Checks whether a specific plugin is active.
2054
	 *
2055
	 * We don't want to store these in a static variable, in case
2056
	 * there are switch_to_blog() calls involved.
2057
	 */
2058
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2059
		return in_array( $plugin, self::get_active_plugins() );
2060
	}
2061
2062
	/**
2063
	 * Check if Jetpack's Open Graph tags should be used.
2064
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2065
	 *
2066
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2067
	 * @action plugins_loaded
2068
	 * @return null
2069
	 */
2070
	public function check_open_graph() {
2071
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2072
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2073
		}
2074
2075
		$active_plugins = self::get_active_plugins();
2076
2077
		if ( ! empty( $active_plugins ) ) {
2078
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2079
				if ( in_array( $plugin, $active_plugins ) ) {
2080
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2081
					break;
2082
				}
2083
			}
2084
		}
2085
2086
		/**
2087
		 * Allow the addition of Open Graph Meta Tags to all pages.
2088
		 *
2089
		 * @since 2.0.3
2090
		 *
2091
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2092
		 */
2093
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2094
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2095
		}
2096
	}
2097
2098
	/**
2099
	 * Check if Jetpack's Twitter tags should be used.
2100
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2101
	 *
2102
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2103
	 * @action plugins_loaded
2104
	 * @return null
2105
	 */
2106
	public function check_twitter_tags() {
2107
2108
		$active_plugins = self::get_active_plugins();
2109
2110
		if ( ! empty( $active_plugins ) ) {
2111
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2112
				if ( in_array( $plugin, $active_plugins ) ) {
2113
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2114
					break;
2115
				}
2116
			}
2117
		}
2118
2119
		/**
2120
		 * Allow Twitter Card Meta tags to be disabled.
2121
		 *
2122
		 * @since 2.6.0
2123
		 *
2124
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2125
		 */
2126
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2127
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2128
		}
2129
	}
2130
2131
	/**
2132
	 * Allows plugins to submit security reports.
2133
	 *
2134
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2135
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2136
	 * @param array  $args         See definitions above
2137
	 */
2138
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2139
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2140
	}
2141
2142
	/* Jetpack Options API */
2143
2144
	public static function get_option_names( $type = 'compact' ) {
2145
		return Jetpack_Options::get_option_names( $type );
2146
	}
2147
2148
	/**
2149
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2150
	 *
2151
	 * @param string $name    Option name
2152
	 * @param mixed  $default (optional)
2153
	 */
2154
	public static function get_option( $name, $default = false ) {
2155
		return Jetpack_Options::get_option( $name, $default );
2156
	}
2157
2158
	/**
2159
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2160
	 *
2161
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2162
	 * @param string $name  Option name
2163
	 * @param mixed  $value Option value
2164
	 */
2165
	public static function update_option( $name, $value ) {
2166
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2167
		return Jetpack_Options::update_option( $name, $value );
2168
	}
2169
2170
	/**
2171
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2172
	 *
2173
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2174
	 * @param array $array array( option name => option value, ... )
2175
	 */
2176
	public static function update_options( $array ) {
2177
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2178
		return Jetpack_Options::update_options( $array );
2179
	}
2180
2181
	/**
2182
	 * Deletes the given option.  May be passed multiple option names as an array.
2183
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2184
	 *
2185
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2186
	 * @param string|array $names
2187
	 */
2188
	public static function delete_option( $names ) {
2189
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2190
		return Jetpack_Options::delete_option( $names );
2191
	}
2192
2193
	/**
2194
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2195
	 *
2196
	 * Enters a user token into the user_tokens option
2197
	 *
2198
	 * @param int    $user_id The user id.
2199
	 * @param string $token The user token.
2200
	 * @param bool   $is_master_user Whether the user is the master user.
2201
	 * @return bool
2202
	 */
2203
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2204
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2205
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2206
	}
2207
2208
	/**
2209
	 * Returns an array of all PHP files in the specified absolute path.
2210
	 * Equivalent to glob( "$absolute_path/*.php" ).
2211
	 *
2212
	 * @param string $absolute_path The absolute path of the directory to search.
2213
	 * @return array Array of absolute paths to the PHP files.
2214
	 */
2215
	public static function glob_php( $absolute_path ) {
2216
		if ( function_exists( 'glob' ) ) {
2217
			return glob( "$absolute_path/*.php" );
2218
		}
2219
2220
		$absolute_path = untrailingslashit( $absolute_path );
2221
		$files         = array();
2222
		if ( ! $dir = @opendir( $absolute_path ) ) {
2223
			return $files;
2224
		}
2225
2226
		while ( false !== $file = readdir( $dir ) ) {
2227
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2228
				continue;
2229
			}
2230
2231
			$file = "$absolute_path/$file";
2232
2233
			if ( ! is_file( $file ) ) {
2234
				continue;
2235
			}
2236
2237
			$files[] = $file;
2238
		}
2239
2240
		closedir( $dir );
2241
2242
		return $files;
2243
	}
2244
2245
	public static function activate_new_modules( $redirect = false ) {
2246
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2247
			return;
2248
		}
2249
2250
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2251 View Code Duplication
		if ( ! $jetpack_old_version ) {
2252
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2253
			/** This action is documented in class.jetpack.php */
2254
			do_action( 'updating_jetpack_version', $version, false );
2255
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2256
		}
2257
2258
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2259
2260
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2261
			return;
2262
		}
2263
2264
		$active_modules     = self::get_active_modules();
2265
		$reactivate_modules = array();
2266
		foreach ( $active_modules as $active_module ) {
2267
			$module = self::get_module( $active_module );
2268
			if ( ! isset( $module['changed'] ) ) {
2269
				continue;
2270
			}
2271
2272
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2273
				continue;
2274
			}
2275
2276
			$reactivate_modules[] = $active_module;
2277
			self::deactivate_module( $active_module );
2278
		}
2279
2280
		$new_version = JETPACK__VERSION . ':' . time();
2281
		/** This action is documented in class.jetpack.php */
2282
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2283
		Jetpack_Options::update_options(
2284
			array(
2285
				'version'     => $new_version,
2286
				'old_version' => $jetpack_old_version,
2287
			)
2288
		);
2289
2290
		self::state( 'message', 'modules_activated' );
2291
2292
		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...
2293
2294
		if ( $redirect ) {
2295
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2296
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2297
				$page = $_GET['page'];
2298
			}
2299
2300
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2301
			exit;
2302
		}
2303
	}
2304
2305
	/**
2306
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2307
	 * Make sure to tuck away module "library" files in a sub-directory.
2308
	 */
2309
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2310
		static $modules = null;
2311
2312
		if ( ! isset( $modules ) ) {
2313
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2314
			// Use the cache if we're on the front-end and it's available...
2315
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2316
				$modules = $available_modules_option[ JETPACK__VERSION ];
2317
			} else {
2318
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2319
2320
				$modules = array();
2321
2322
				foreach ( $files as $file ) {
2323
					if ( ! $headers = self::get_module( $file ) ) {
2324
						continue;
2325
					}
2326
2327
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2328
				}
2329
2330
				Jetpack_Options::update_option(
2331
					'available_modules',
2332
					array(
2333
						JETPACK__VERSION => $modules,
2334
					)
2335
				);
2336
			}
2337
		}
2338
2339
		/**
2340
		 * Filters the array of modules available to be activated.
2341
		 *
2342
		 * @since 2.4.0
2343
		 *
2344
		 * @param array $modules Array of available modules.
2345
		 * @param string $min_version Minimum version number required to use modules.
2346
		 * @param string $max_version Maximum version number required to use modules.
2347
		 */
2348
		$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...
2349
2350
		if ( ! $min_version && ! $max_version ) {
2351
			return array_keys( $mods );
2352
		}
2353
2354
		$r = array();
2355
		foreach ( $mods as $slug => $introduced ) {
2356
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2357
				continue;
2358
			}
2359
2360
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2361
				continue;
2362
			}
2363
2364
			$r[] = $slug;
2365
		}
2366
2367
		return $r;
2368
	}
2369
2370
	/**
2371
	 * Default modules loaded on activation.
2372
	 */
2373
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2374
		$return = array();
2375
2376
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2377
			$module_data = self::get_module( $module );
2378
2379
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2380
				case 'yes':
2381
					$return[] = $module;
2382
					break;
2383
				case 'public':
2384
					if ( Jetpack_Options::get_option( 'public' ) ) {
2385
						$return[] = $module;
2386
					}
2387
					break;
2388
				case 'no':
2389
				default:
2390
					break;
2391
			}
2392
		}
2393
		/**
2394
		 * Filters the array of default modules.
2395
		 *
2396
		 * @since 2.5.0
2397
		 *
2398
		 * @param array $return Array of default modules.
2399
		 * @param string $min_version Minimum version number required to use modules.
2400
		 * @param string $max_version Maximum version number required to use modules.
2401
		 */
2402
		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...
2403
	}
2404
2405
	/**
2406
	 * Checks activated modules during auto-activation to determine
2407
	 * if any of those modules are being deprecated.  If so, close
2408
	 * them out, and add any replacement modules.
2409
	 *
2410
	 * Runs at priority 99 by default.
2411
	 *
2412
	 * This is run late, so that it can still activate a module if
2413
	 * the new module is a replacement for another that the user
2414
	 * currently has active, even if something at the normal priority
2415
	 * would kibosh everything.
2416
	 *
2417
	 * @since 2.6
2418
	 * @uses jetpack_get_default_modules filter
2419
	 * @param array $modules
2420
	 * @return array
2421
	 */
2422
	function handle_deprecated_modules( $modules ) {
2423
		$deprecated_modules = array(
2424
			'debug'            => null,  // Closed out and moved to the debugger library.
2425
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2426
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2427
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2428
		);
2429
2430
		// Don't activate SSO if they never completed activating WPCC.
2431
		if ( self::is_module_active( 'wpcc' ) ) {
2432
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2433
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2434
				$deprecated_modules['wpcc'] = null;
2435
			}
2436
		}
2437
2438
		foreach ( $deprecated_modules as $module => $replacement ) {
2439
			if ( self::is_module_active( $module ) ) {
2440
				self::deactivate_module( $module );
2441
				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...
2442
					$modules[] = $replacement;
2443
				}
2444
			}
2445
		}
2446
2447
		return array_unique( $modules );
2448
	}
2449
2450
	/**
2451
	 * Checks activated plugins during auto-activation to determine
2452
	 * if any of those plugins are in the list with a corresponding module
2453
	 * that is not compatible with the plugin. The module will not be allowed
2454
	 * to auto-activate.
2455
	 *
2456
	 * @since 2.6
2457
	 * @uses jetpack_get_default_modules filter
2458
	 * @param array $modules
2459
	 * @return array
2460
	 */
2461
	function filter_default_modules( $modules ) {
2462
2463
		$active_plugins = self::get_active_plugins();
2464
2465
		if ( ! empty( $active_plugins ) ) {
2466
2467
			// For each module we'd like to auto-activate...
2468
			foreach ( $modules as $key => $module ) {
2469
				// If there are potential conflicts for it...
2470
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2471
					// For each potential conflict...
2472
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2473
						// If that conflicting plugin is active...
2474
						if ( in_array( $plugin, $active_plugins ) ) {
2475
							// Remove that item from being auto-activated.
2476
							unset( $modules[ $key ] );
2477
						}
2478
					}
2479
				}
2480
			}
2481
		}
2482
2483
		return $modules;
2484
	}
2485
2486
	/**
2487
	 * Extract a module's slug from its full path.
2488
	 */
2489
	public static function get_module_slug( $file ) {
2490
		return str_replace( '.php', '', basename( $file ) );
2491
	}
2492
2493
	/**
2494
	 * Generate a module's path from its slug.
2495
	 */
2496
	public static function get_module_path( $slug ) {
2497
		/**
2498
		 * Filters the path of a modules.
2499
		 *
2500
		 * @since 7.4.0
2501
		 *
2502
		 * @param array $return The absolute path to a module's root php file
2503
		 * @param string $slug The module slug
2504
		 */
2505
		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...
2506
	}
2507
2508
	/**
2509
	 * Load module data from module file. Headers differ from WordPress
2510
	 * plugin headers to avoid them being identified as standalone
2511
	 * plugins on the WordPress plugins page.
2512
	 */
2513
	public static function get_module( $module ) {
2514
		$headers = array(
2515
			'name'                      => 'Module Name',
2516
			'description'               => 'Module Description',
2517
			'sort'                      => 'Sort Order',
2518
			'recommendation_order'      => 'Recommendation Order',
2519
			'introduced'                => 'First Introduced',
2520
			'changed'                   => 'Major Changes In',
2521
			'deactivate'                => 'Deactivate',
2522
			'free'                      => 'Free',
2523
			'requires_connection'       => 'Requires Connection',
2524
			'auto_activate'             => 'Auto Activate',
2525
			'module_tags'               => 'Module Tags',
2526
			'feature'                   => 'Feature',
2527
			'additional_search_queries' => 'Additional Search Queries',
2528
			'plan_classes'              => 'Plans',
2529
		);
2530
2531
		$file = self::get_module_path( self::get_module_slug( $module ) );
2532
2533
		$mod = self::get_file_data( $file, $headers );
2534
		if ( empty( $mod['name'] ) ) {
2535
			return false;
2536
		}
2537
2538
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2539
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2540
		$mod['deactivate']           = empty( $mod['deactivate'] );
2541
		$mod['free']                 = empty( $mod['free'] );
2542
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2543
2544
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2545
			$mod['auto_activate'] = 'No';
2546
		} else {
2547
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2548
		}
2549
2550
		if ( $mod['module_tags'] ) {
2551
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2552
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2553
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2554
		} else {
2555
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2556
		}
2557
2558 View Code Duplication
		if ( $mod['plan_classes'] ) {
2559
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2560
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2561
		} else {
2562
			$mod['plan_classes'] = array( 'free' );
2563
		}
2564
2565 View Code Duplication
		if ( $mod['feature'] ) {
2566
			$mod['feature'] = explode( ',', $mod['feature'] );
2567
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2568
		} else {
2569
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2570
		}
2571
2572
		/**
2573
		 * Filters the feature array on a module.
2574
		 *
2575
		 * This filter allows you to control where each module is filtered: Recommended,
2576
		 * and the default "Other" listing.
2577
		 *
2578
		 * @since 3.5.0
2579
		 *
2580
		 * @param array   $mod['feature'] The areas to feature this module:
2581
		 *     'Recommended' shows on the main Jetpack admin screen.
2582
		 *     'Other' should be the default if no other value is in the array.
2583
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2584
		 * @param array   $mod All the currently assembled module data.
2585
		 */
2586
		$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...
2587
2588
		/**
2589
		 * Filter the returned data about a module.
2590
		 *
2591
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2592
		 * so please be careful.
2593
		 *
2594
		 * @since 3.6.0
2595
		 *
2596
		 * @param array   $mod    The details of the requested module.
2597
		 * @param string  $module The slug of the module, e.g. sharedaddy
2598
		 * @param string  $file   The path to the module source file.
2599
		 */
2600
		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...
2601
	}
2602
2603
	/**
2604
	 * Like core's get_file_data implementation, but caches the result.
2605
	 */
2606
	public static function get_file_data( $file, $headers ) {
2607
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2608
		$file_name = basename( $file );
2609
2610
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2611
2612
		$file_data_option = get_transient( $cache_key );
2613
2614
		if ( ! is_array( $file_data_option ) ) {
2615
			delete_transient( $cache_key );
2616
			$file_data_option = false;
2617
		}
2618
2619
		if ( false === $file_data_option ) {
2620
			$file_data_option = array();
2621
		}
2622
2623
		$key           = md5( $file_name . serialize( $headers ) );
2624
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2625
2626
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2627
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2628
			return $file_data_option[ $key ];
2629
		}
2630
2631
		$data = get_file_data( $file, $headers );
2632
2633
		$file_data_option[ $key ] = $data;
2634
2635
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2636
2637
		return $data;
2638
	}
2639
2640
2641
	/**
2642
	 * Return translated module tag.
2643
	 *
2644
	 * @param string $tag Tag as it appears in each module heading.
2645
	 *
2646
	 * @return mixed
2647
	 */
2648
	public static function translate_module_tag( $tag ) {
2649
		return jetpack_get_module_i18n_tag( $tag );
2650
	}
2651
2652
	/**
2653
	 * Get i18n strings as a JSON-encoded string
2654
	 *
2655
	 * @return string The locale as JSON
2656
	 */
2657
	public static function get_i18n_data_json() {
2658
2659
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2660
		// JSON files with the file they should be included for. This is an md5
2661
		// of '_inc/build/admin.js'.
2662
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2663
2664
		$i18n_json =
2665
				   JETPACK__PLUGIN_DIR
2666
				   . 'languages/json/jetpack-'
2667
				   . get_user_locale()
2668
				   . '-'
2669
				   . $path_md5
2670
				   . '.json';
2671
2672
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2673
			$locale_data = @file_get_contents( $i18n_json );
2674
			if ( $locale_data ) {
2675
				return $locale_data;
2676
			}
2677
		}
2678
2679
		// Return valid empty Jed locale
2680
		return '{ "locale_data": { "messages": { "": {} } } }';
2681
	}
2682
2683
	/**
2684
	 * Add locale data setup to wp-i18n
2685
	 *
2686
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2687
	 *
2688
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2689
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2690
	 *
2691
	 * This method provides a safe way to request the setup multiple times but add the script at
2692
	 * most once.
2693
	 *
2694
	 * @since 6.7.0
2695
	 *
2696
	 * @return void
2697
	 */
2698
	public static function setup_wp_i18n_locale_data() {
2699
		static $script_added = false;
2700
		if ( ! $script_added ) {
2701
			$script_added = true;
2702
			wp_add_inline_script(
2703
				'wp-i18n',
2704
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2705
			);
2706
		}
2707
	}
2708
2709
	/**
2710
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2711
	 *
2712
	 * @since 3.9.2
2713
	 *
2714
	 * @param array $modules
2715
	 *
2716
	 * @return string|void
2717
	 */
2718
	public static function get_translated_modules( $modules ) {
2719
		foreach ( $modules as $index => $module ) {
2720
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2721
			if ( isset( $module['name'] ) ) {
2722
				$modules[ $index ]['name'] = $i18n_module['name'];
2723
			}
2724
			if ( isset( $module['description'] ) ) {
2725
				$modules[ $index ]['description']       = $i18n_module['description'];
2726
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2727
			}
2728
		}
2729
		return $modules;
2730
	}
2731
2732
	/**
2733
	 * Get a list of activated modules as an array of module slugs.
2734
	 */
2735
	public static function get_active_modules() {
2736
		$active = Jetpack_Options::get_option( 'active_modules' );
2737
2738
		if ( ! is_array( $active ) ) {
2739
			$active = array();
2740
		}
2741
2742
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2743
			$active[] = 'vaultpress';
2744
		} else {
2745
			$active = array_diff( $active, array( 'vaultpress' ) );
2746
		}
2747
2748
		// If protect is active on the main site of a multisite, it should be active on all sites.
2749
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2750
			$active[] = 'protect';
2751
		}
2752
2753
		/**
2754
		 * Allow filtering of the active modules.
2755
		 *
2756
		 * Gives theme and plugin developers the power to alter the modules that
2757
		 * are activated on the fly.
2758
		 *
2759
		 * @since 5.8.0
2760
		 *
2761
		 * @param array $active Array of active module slugs.
2762
		 */
2763
		$active = apply_filters( 'jetpack_active_modules', $active );
2764
2765
		return array_unique( $active );
2766
	}
2767
2768
	/**
2769
	 * Check whether or not a Jetpack module is active.
2770
	 *
2771
	 * @param string $module The slug of a Jetpack module.
2772
	 * @return bool
2773
	 *
2774
	 * @static
2775
	 */
2776
	public static function is_module_active( $module ) {
2777
		return in_array( $module, self::get_active_modules() );
2778
	}
2779
2780
	public static function is_module( $module ) {
2781
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2782
	}
2783
2784
	/**
2785
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2786
	 *
2787
	 * @param bool $catch True to start catching, False to stop.
2788
	 *
2789
	 * @static
2790
	 */
2791
	public static function catch_errors( $catch ) {
2792
		static $display_errors, $error_reporting;
2793
2794
		if ( $catch ) {
2795
			$display_errors  = @ini_set( 'display_errors', 1 );
2796
			$error_reporting = @error_reporting( E_ALL );
2797
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2798
		} else {
2799
			@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...
2800
			@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...
2801
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2802
		}
2803
	}
2804
2805
	/**
2806
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2807
	 */
2808
	public static function catch_errors_on_shutdown() {
2809
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2810
	}
2811
2812
	/**
2813
	 * Rewrite any string to make paths easier to read.
2814
	 *
2815
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2816
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2817
	 *
2818
	 * @param $string
2819
	 * @return mixed
2820
	 */
2821
	public static function alias_directories( $string ) {
2822
		// ABSPATH has a trailing slash.
2823
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2824
		// WP_CONTENT_DIR does not have a trailing slash.
2825
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2826
2827
		return $string;
2828
	}
2829
2830
	public static function activate_default_modules(
2831
		$min_version = false,
2832
		$max_version = false,
2833
		$other_modules = array(),
2834
		$redirect = null,
2835
		$send_state_messages = null
2836
	) {
2837
		$jetpack = self::init();
2838
2839
		if ( is_null( $redirect ) ) {
2840
			if (
2841
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2842
			||
2843
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2844
			||
2845
				( defined( 'WP_CLI' ) && WP_CLI )
2846
			||
2847
				( defined( 'DOING_CRON' ) && DOING_CRON )
2848
			||
2849
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2850
			) {
2851
				$redirect = false;
2852
			} elseif ( is_admin() ) {
2853
				$redirect = true;
2854
			} else {
2855
				$redirect = false;
2856
			}
2857
		}
2858
2859
		if ( is_null( $send_state_messages ) ) {
2860
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2861
		}
2862
2863
		$modules = self::get_default_modules( $min_version, $max_version );
2864
		$modules = array_merge( $other_modules, $modules );
2865
2866
		// Look for standalone plugins and disable if active.
2867
2868
		$to_deactivate = array();
2869
		foreach ( $modules as $module ) {
2870
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2871
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2872
			}
2873
		}
2874
2875
		$deactivated = array();
2876
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2877
			list( $probable_file, $probable_title ) = $deactivate_me;
2878
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2879
				$deactivated[] = $module;
2880
			}
2881
		}
2882
2883
		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...
2884
			if ( $send_state_messages ) {
2885
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2886
			}
2887
2888
			if ( $redirect ) {
2889
				$url = add_query_arg(
2890
					array(
2891
						'action'   => 'activate_default_modules',
2892
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2893
					),
2894
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2895
				);
2896
				wp_safe_redirect( $url );
2897
				exit;
2898
			}
2899
		}
2900
2901
		/**
2902
		 * Fires before default modules are activated.
2903
		 *
2904
		 * @since 1.9.0
2905
		 *
2906
		 * @param string $min_version Minimum version number required to use modules.
2907
		 * @param string $max_version Maximum version number required to use modules.
2908
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2909
		 */
2910
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2911
2912
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2913
		if ( $send_state_messages ) {
2914
			self::restate();
2915
			self::catch_errors( true );
2916
		}
2917
2918
		$active = self::get_active_modules();
2919
2920
		foreach ( $modules as $module ) {
2921
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2922
				$active[] = $module;
2923
				self::update_active_modules( $active );
2924
				continue;
2925
			}
2926
2927
			if ( $send_state_messages && in_array( $module, $active ) ) {
2928
				$module_info = self::get_module( $module );
2929 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2930
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2931
					if ( $active_state = self::state( $state ) ) {
2932
						$active_state = explode( ',', $active_state );
2933
					} else {
2934
						$active_state = array();
2935
					}
2936
					$active_state[] = $module;
2937
					self::state( $state, implode( ',', $active_state ) );
2938
				}
2939
				continue;
2940
			}
2941
2942
			$file = self::get_module_path( $module );
2943
			if ( ! file_exists( $file ) ) {
2944
				continue;
2945
			}
2946
2947
			// we'll override this later if the plugin can be included without fatal error
2948
			if ( $redirect ) {
2949
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2950
			}
2951
2952
			if ( $send_state_messages ) {
2953
				self::state( 'error', 'module_activation_failed' );
2954
				self::state( 'module', $module );
2955
			}
2956
2957
			ob_start();
2958
			require_once $file;
2959
2960
			$active[] = $module;
2961
2962 View Code Duplication
			if ( $send_state_messages ) {
2963
2964
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2965
				if ( $active_state = self::state( $state ) ) {
2966
					$active_state = explode( ',', $active_state );
2967
				} else {
2968
					$active_state = array();
2969
				}
2970
				$active_state[] = $module;
2971
				self::state( $state, implode( ',', $active_state ) );
2972
			}
2973
2974
			self::update_active_modules( $active );
2975
2976
			ob_end_clean();
2977
		}
2978
2979
		if ( $send_state_messages ) {
2980
			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...
2981
			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...
2982
		}
2983
2984
		self::catch_errors( false );
2985
		/**
2986
		 * Fires when default modules are activated.
2987
		 *
2988
		 * @since 1.9.0
2989
		 *
2990
		 * @param string $min_version Minimum version number required to use modules.
2991
		 * @param string $max_version Maximum version number required to use modules.
2992
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2993
		 */
2994
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2995
	}
2996
2997
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2998
		/**
2999
		 * Fires before a module is activated.
3000
		 *
3001
		 * @since 2.6.0
3002
		 *
3003
		 * @param string $module Module slug.
3004
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3005
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3006
		 */
3007
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3008
3009
		$jetpack = self::init();
3010
3011
		if ( ! strlen( $module ) ) {
3012
			return false;
3013
		}
3014
3015
		if ( ! self::is_module( $module ) ) {
3016
			return false;
3017
		}
3018
3019
		// If it's already active, then don't do it again
3020
		$active = self::get_active_modules();
3021
		foreach ( $active as $act ) {
3022
			if ( $act == $module ) {
3023
				return true;
3024
			}
3025
		}
3026
3027
		$module_data = self::get_module( $module );
3028
3029
		$is_development_mode = ( new Status() )->is_development_mode();
3030
		if ( ! self::is_active() ) {
3031
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
3032
				return false;
3033
			}
3034
3035
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3036
			if ( $is_development_mode && $module_data['requires_connection'] ) {
3037
				return false;
3038
			}
3039
		}
3040
3041
		// Check and see if the old plugin is active
3042
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3043
			// Deactivate the old plugin
3044
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3045
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3046
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3047
				self::state( 'deactivated_plugins', $module );
3048
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3049
				exit;
3050
			}
3051
		}
3052
3053
		// Protect won't work with mis-configured IPs
3054
		if ( 'protect' === $module ) {
3055
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3056
			if ( ! jetpack_protect_get_ip() ) {
3057
				self::state( 'message', 'protect_misconfigured_ip' );
3058
				return false;
3059
			}
3060
		}
3061
3062
		if ( ! Jetpack_Plan::supports( $module ) ) {
3063
			return false;
3064
		}
3065
3066
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3067
		self::state( 'module', $module );
3068
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3069
3070
		self::catch_errors( true );
3071
		ob_start();
3072
		require self::get_module_path( $module );
3073
		/** This action is documented in class.jetpack.php */
3074
		do_action( 'jetpack_activate_module', $module );
3075
		$active[] = $module;
3076
		self::update_active_modules( $active );
3077
3078
		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...
3079
		ob_end_clean();
3080
		self::catch_errors( false );
3081
3082
		if ( $redirect ) {
3083
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3084
		}
3085
		if ( $exit ) {
3086
			exit;
3087
		}
3088
		return true;
3089
	}
3090
3091
	function activate_module_actions( $module ) {
3092
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3093
	}
3094
3095
	public static function deactivate_module( $module ) {
3096
		/**
3097
		 * Fires when a module is deactivated.
3098
		 *
3099
		 * @since 1.9.0
3100
		 *
3101
		 * @param string $module Module slug.
3102
		 */
3103
		do_action( 'jetpack_pre_deactivate_module', $module );
3104
3105
		$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...
3106
3107
		$active = self::get_active_modules();
3108
		$new    = array_filter( array_diff( $active, (array) $module ) );
3109
3110
		return self::update_active_modules( $new );
3111
	}
3112
3113
	public static function enable_module_configurable( $module ) {
3114
		$module = self::get_module_slug( $module );
3115
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3116
	}
3117
3118
	/**
3119
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3120
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3121
	 *
3122
	 * @param string $module Module slug
3123
	 * @return string $url module configuration URL
3124
	 */
3125
	public static function module_configuration_url( $module ) {
3126
		$module      = self::get_module_slug( $module );
3127
		$default_url = self::admin_url() . "#/settings?term=$module";
3128
		/**
3129
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3130
		 *
3131
		 * @since 6.9.0
3132
		 *
3133
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3134
		 */
3135
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3136
3137
		return $url;
3138
	}
3139
3140
	/* Installation */
3141
	public static function bail_on_activation( $message, $deactivate = true ) {
3142
		?>
3143
<!doctype html>
3144
<html>
3145
<head>
3146
<meta charset="<?php bloginfo( 'charset' ); ?>">
3147
<style>
3148
* {
3149
	text-align: center;
3150
	margin: 0;
3151
	padding: 0;
3152
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3153
}
3154
p {
3155
	margin-top: 1em;
3156
	font-size: 18px;
3157
}
3158
</style>
3159
<body>
3160
<p><?php echo esc_html( $message ); ?></p>
3161
</body>
3162
</html>
3163
		<?php
3164
		if ( $deactivate ) {
3165
			$plugins = get_option( 'active_plugins' );
3166
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3167
			$update  = false;
3168
			foreach ( $plugins as $i => $plugin ) {
3169
				if ( $plugin === $jetpack ) {
3170
					$plugins[ $i ] = false;
3171
					$update        = true;
3172
				}
3173
			}
3174
3175
			if ( $update ) {
3176
				update_option( 'active_plugins', array_filter( $plugins ) );
3177
			}
3178
		}
3179
		exit;
3180
	}
3181
3182
	/**
3183
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3184
	 *
3185
	 * @static
3186
	 */
3187
	public static function plugin_activation( $network_wide ) {
3188
		Jetpack_Options::update_option( 'activated', 1 );
3189
3190
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3191
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3192
		}
3193
3194
		if ( $network_wide ) {
3195
			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...
3196
		}
3197
3198
		// For firing one-off events (notices) immediately after activation
3199
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3200
3201
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3202
3203
		Health::on_jetpack_activated();
3204
3205
		self::plugin_initialize();
3206
	}
3207
3208
	public static function get_activation_source( $referer_url ) {
3209
3210
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3211
			return array( 'wp-cli', null );
3212
		}
3213
3214
		$referer = wp_parse_url( $referer_url );
3215
3216
		$source_type  = 'unknown';
3217
		$source_query = null;
3218
3219
		if ( ! is_array( $referer ) ) {
3220
			return array( $source_type, $source_query );
3221
		}
3222
3223
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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...
3224
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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...
3225
3226
		if ( isset( $referer['query'] ) ) {
3227
			parse_str( $referer['query'], $query_parts );
3228
		} else {
3229
			$query_parts = array();
3230
		}
3231
3232
		if ( $plugins_path === $referer['path'] ) {
3233
			$source_type = 'list';
3234
		} elseif ( $plugins_install_path === $referer['path'] ) {
3235
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3236
			switch ( $tab ) {
3237
				case 'popular':
3238
					$source_type = 'popular';
3239
					break;
3240
				case 'recommended':
3241
					$source_type = 'recommended';
3242
					break;
3243
				case 'favorites':
3244
					$source_type = 'favorites';
3245
					break;
3246
				case 'search':
3247
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3248
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3249
					break;
3250
				default:
3251
					$source_type = 'featured';
3252
			}
3253
		}
3254
3255
		return array( $source_type, $source_query );
3256
	}
3257
3258
	/**
3259
	 * Runs before bumping version numbers up to a new version
3260
	 *
3261
	 * @param string $version    Version:timestamp.
3262
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3263
	 */
3264
	public static function do_version_bump( $version, $old_version ) {
3265
		if ( $old_version ) { // For existing Jetpack installations.
3266
3267
			// If a front end page is visited after the update, the 'wp' action will fire.
3268
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3269
3270
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3271
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3272
		}
3273
	}
3274
3275
	/**
3276
	 * Sets the display_update_modal state.
3277
	 */
3278
	public static function set_update_modal_display() {
3279
		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...
3280
	}
3281
3282
	/**
3283
	 * Sets the internal version number and activation state.
3284
	 *
3285
	 * @static
3286
	 */
3287
	public static function plugin_initialize() {
3288
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3289
			Jetpack_Options::update_option( 'activated', 2 );
3290
		}
3291
3292 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3293
			$version = $old_version = JETPACK__VERSION . ':' . time();
3294
			/** This action is documented in class.jetpack.php */
3295
			do_action( 'updating_jetpack_version', $version, false );
3296
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3297
		}
3298
3299
		self::load_modules();
3300
3301
		Jetpack_Options::delete_option( 'do_activate' );
3302
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3303
	}
3304
3305
	/**
3306
	 * Removes all connection options
3307
	 *
3308
	 * @static
3309
	 */
3310
	public static function plugin_deactivation() {
3311
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3312
		$tracking = new Tracking();
3313
		$tracking->record_user_event( 'deactivate_plugin', array() );
3314
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3315
			Jetpack_Network::init()->deactivate();
3316
		} else {
3317
			self::disconnect( false );
3318
			// Jetpack_Heartbeat::init()->deactivate();
3319
		}
3320
	}
3321
3322
	/**
3323
	 * Disconnects from the Jetpack servers.
3324
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3325
	 *
3326
	 * @static
3327
	 */
3328
	public static function disconnect( $update_activated_state = true ) {
3329
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3330
		$connection = self::connection();
3331
		$connection->clean_nonces( true );
3332
3333
		// If the site is in an IDC because sync is not allowed,
3334
		// let's make sure to not disconnect the production site.
3335
		if ( ! self::validate_sync_error_idc_option() ) {
3336
			$tracking = new Tracking();
3337
			$tracking->record_user_event( 'disconnect_site', array() );
3338
3339
			$connection->disconnect_site_wpcom( true );
3340
		}
3341
3342
		$connection->delete_all_connection_tokens( true );
3343
		Jetpack_IDC::clear_all_idc_options();
3344
3345
		if ( $update_activated_state ) {
3346
			Jetpack_Options::update_option( 'activated', 4 );
3347
		}
3348
3349
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3350
			// Check then record unique disconnection if site has never been disconnected previously
3351
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3352
				$jetpack_unique_connection['disconnected'] = 1;
3353
			} else {
3354
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3355
					// track unique disconnect
3356
					$jetpack = self::init();
3357
3358
					$jetpack->stat( 'connections', 'unique-disconnect' );
3359
					$jetpack->do_stats( 'server_side' );
3360
				}
3361
				// increment number of times disconnected
3362
				$jetpack_unique_connection['disconnected'] += 1;
3363
			}
3364
3365
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3366
		}
3367
3368
		// Delete all the sync related data. Since it could be taking up space.
3369
		Sender::get_instance()->uninstall();
3370
3371
		// Disable the Heartbeat cron
3372
		Jetpack_Heartbeat::init()->deactivate();
3373
	}
3374
3375
	/**
3376
	 * Unlinks the current user from the linked WordPress.com user.
3377
	 *
3378
	 * @deprecated since 7.7
3379
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3380
	 *
3381
	 * @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...
3382
	 * @return Boolean Whether the disconnection of the user was successful.
3383
	 */
3384
	public static function unlink_user( $user_id = null ) {
3385
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3386
		return Connection_Manager::disconnect_user( $user_id );
3387
	}
3388
3389
	/**
3390
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3391
	 */
3392
	public static function try_registration() {
3393
		$terms_of_service = new Terms_Of_Service();
3394
		// The user has agreed to the TOS at some point by now.
3395
		$terms_of_service->agree();
3396
3397
		// Let's get some testing in beta versions and such.
3398
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3399
			// Before attempting to connect, let's make sure that the domains are viable.
3400
			$domains_to_check = array_unique(
3401
				array(
3402
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
3403
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
3404
				)
3405
			);
3406
			foreach ( $domains_to_check as $domain ) {
3407
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Documentation introduced by
$domain is of type array<string,string>|false, 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...
3408
				if ( is_wp_error( $result ) ) {
3409
					return $result;
3410
				}
3411
			}
3412
		}
3413
3414
		$result = self::register();
3415
3416
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3417
		if ( ! $result || is_wp_error( $result ) ) {
3418
			return $result;
3419
		} else {
3420
			return true;
3421
		}
3422
	}
3423
3424
	/**
3425
	 * Tracking an internal event log. Try not to put too much chaff in here.
3426
	 *
3427
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3428
	 */
3429
	public static function log( $code, $data = null ) {
3430
		// only grab the latest 200 entries
3431
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3432
3433
		// Append our event to the log
3434
		$log_entry = array(
3435
			'time'    => time(),
3436
			'user_id' => get_current_user_id(),
3437
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3438
			'code'    => $code,
3439
		);
3440
		// Don't bother storing it unless we've got some.
3441
		if ( ! is_null( $data ) ) {
3442
			$log_entry['data'] = $data;
3443
		}
3444
		$log[] = $log_entry;
3445
3446
		// Try add_option first, to make sure it's not autoloaded.
3447
		// @todo: Add an add_option method to Jetpack_Options
3448
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3449
			Jetpack_Options::update_option( 'log', $log );
3450
		}
3451
3452
		/**
3453
		 * Fires when Jetpack logs an internal event.
3454
		 *
3455
		 * @since 3.0.0
3456
		 *
3457
		 * @param array $log_entry {
3458
		 *  Array of details about the log entry.
3459
		 *
3460
		 *  @param string time Time of the event.
3461
		 *  @param int user_id ID of the user who trigerred the event.
3462
		 *  @param int blog_id Jetpack Blog ID.
3463
		 *  @param string code Unique name for the event.
3464
		 *  @param string data Data about the event.
3465
		 * }
3466
		 */
3467
		do_action( 'jetpack_log_entry', $log_entry );
3468
	}
3469
3470
	/**
3471
	 * Get the internal event log.
3472
	 *
3473
	 * @param $event (string) - only return the specific log events
3474
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3475
	 *
3476
	 * @return array of log events || WP_Error for invalid params
3477
	 */
3478
	public static function get_log( $event = false, $num = false ) {
3479
		if ( $event && ! is_string( $event ) ) {
3480
			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...
3481
		}
3482
3483
		if ( $num && ! is_numeric( $num ) ) {
3484
			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...
3485
		}
3486
3487
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3488
3489
		// If nothing set - act as it did before, otherwise let's start customizing the output
3490
		if ( ! $num && ! $event ) {
3491
			return $entire_log;
3492
		} else {
3493
			$entire_log = array_reverse( $entire_log );
3494
		}
3495
3496
		$custom_log_output = array();
3497
3498
		if ( $event ) {
3499
			foreach ( $entire_log as $log_event ) {
3500
				if ( $event == $log_event['code'] ) {
3501
					$custom_log_output[] = $log_event;
3502
				}
3503
			}
3504
		} else {
3505
			$custom_log_output = $entire_log;
3506
		}
3507
3508
		if ( $num ) {
3509
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3510
		}
3511
3512
		return $custom_log_output;
3513
	}
3514
3515
	/**
3516
	 * Log modification of important settings.
3517
	 */
3518
	public static function log_settings_change( $option, $old_value, $value ) {
3519
		switch ( $option ) {
3520
			case 'jetpack_sync_non_public_post_stati':
3521
				self::log( $option, $value );
3522
				break;
3523
		}
3524
	}
3525
3526
	/**
3527
	 * Return stat data for WPCOM sync
3528
	 */
3529
	public static function get_stat_data( $encode = true, $extended = true ) {
3530
		$data = Jetpack_Heartbeat::generate_stats_array();
3531
3532
		if ( $extended ) {
3533
			$additional_data = self::get_additional_stat_data();
3534
			$data            = array_merge( $data, $additional_data );
3535
		}
3536
3537
		if ( $encode ) {
3538
			return json_encode( $data );
3539
		}
3540
3541
		return $data;
3542
	}
3543
3544
	/**
3545
	 * Get additional stat data to sync to WPCOM
3546
	 */
3547
	public static function get_additional_stat_data( $prefix = '' ) {
3548
		$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...
3549
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3550
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3551
		$return[ "{$prefix}site-count" ]    = 0;
3552
3553
		if ( function_exists( 'get_blog_count' ) ) {
3554
			$return[ "{$prefix}site-count" ] = get_blog_count();
3555
		}
3556
		return $return;
3557
	}
3558
3559
	private static function get_site_user_count() {
3560
		global $wpdb;
3561
3562
		if ( function_exists( 'wp_is_large_network' ) ) {
3563
			if ( wp_is_large_network( 'users' ) ) {
3564
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3565
			}
3566
		}
3567
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3568
			// It wasn't there, so regenerate the data and save the transient
3569
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3570
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3571
		}
3572
		return $user_count;
3573
	}
3574
3575
	/* Admin Pages */
3576
3577
	function admin_init() {
3578
		// If the plugin is not connected, display a connect message.
3579
		if (
3580
			// the plugin was auto-activated and needs its candy
3581
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3582
		||
3583
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3584
			! Jetpack_Options::get_option( 'activated' )
3585
		) {
3586
			self::plugin_initialize();
3587
		}
3588
3589
		$is_development_mode = ( new Status() )->is_development_mode();
3590
		if ( ! self::is_active() && ! $is_development_mode ) {
3591
			Jetpack_Connection_Banner::init();
3592
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3593
			// Upgrade: 1.1 -> 1.1.1
3594
			// Check and see if host can verify the Jetpack servers' SSL certificate
3595
			$args       = array();
3596
			$connection = self::connection();
3597
			Client::_wp_remote_request(
3598
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3599
				$args,
3600
				true
3601
			);
3602
		}
3603
3604
		Jetpack_Wizard_Banner::init();
3605
3606
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3607
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3608
		}
3609
3610
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3611
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3612
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3613
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3614
3615
		if ( self::is_active() || $is_development_mode ) {
3616
			// Artificially throw errors in certain specific cases during plugin activation.
3617
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3618
		}
3619
3620
		// Add custom column in wp-admin/users.php to show whether user is linked.
3621
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3622
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3623
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3624
	}
3625
3626
	function admin_body_class( $admin_body_class = '' ) {
3627
		$classes = explode( ' ', trim( $admin_body_class ) );
3628
3629
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3630
3631
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3632
		return " $admin_body_class ";
3633
	}
3634
3635
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3636
		return $admin_body_class . ' jetpack-pagestyles ';
3637
	}
3638
3639
	/**
3640
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3641
	 * This function artificially throws errors for such cases (per a specific list).
3642
	 *
3643
	 * @param string $plugin The activated plugin.
3644
	 */
3645
	function throw_error_on_activate_plugin( $plugin ) {
3646
		$active_modules = self::get_active_modules();
3647
3648
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3649
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3650
			$throw = false;
3651
3652
			// Try and make sure it really was the stats plugin
3653
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3654
				if ( 'stats.php' == basename( $plugin ) ) {
3655
					$throw = true;
3656
				}
3657
			} else {
3658
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3659
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3660
					$throw = true;
3661
				}
3662
			}
3663
3664
			if ( $throw ) {
3665
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3666
			}
3667
		}
3668
	}
3669
3670
	function intercept_plugin_error_scrape_init() {
3671
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3672
	}
3673
3674
	function intercept_plugin_error_scrape( $action, $result ) {
3675
		if ( ! $result ) {
3676
			return;
3677
		}
3678
3679
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3680
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3681
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3682
			}
3683
		}
3684
	}
3685
3686
	/**
3687
	 * Register the remote file upload request handlers, if needed.
3688
	 *
3689
	 * @access public
3690
	 */
3691
	public function add_remote_request_handlers() {
3692
		// Remote file uploads are allowed only via AJAX requests.
3693
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3694
			return;
3695
		}
3696
3697
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3698
		$remote_request_actions = array(
3699
			'jetpack_upload_file',
3700
			'jetpack_update_file',
3701
		);
3702
3703
		// phpcs:ignore WordPress.Security.NonceVerification
3704
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3705
			return;
3706
		}
3707
3708
		// Require Jetpack authentication for the remote file upload AJAX requests.
3709
		if ( ! $this->connection_manager ) {
3710
			$this->connection_manager = new Connection_Manager();
3711
		}
3712
3713
		$this->connection_manager->require_jetpack_authentication();
3714
3715
		// Register the remote file upload AJAX handlers.
3716
		foreach ( $remote_request_actions as $action ) {
3717
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3718
		}
3719
	}
3720
3721
	/**
3722
	 * Handler for Jetpack remote file uploads.
3723
	 *
3724
	 * @access public
3725
	 */
3726
	public function remote_request_handlers() {
3727
		$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...
3728
3729
		switch ( current_filter() ) {
3730
			case 'wp_ajax_nopriv_jetpack_upload_file':
3731
				$response = $this->upload_handler();
3732
				break;
3733
3734
			case 'wp_ajax_nopriv_jetpack_update_file':
3735
				$response = $this->upload_handler( true );
3736
				break;
3737
			default:
3738
				$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...
3739
				break;
3740
		}
3741
3742
		if ( ! $response ) {
3743
			$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...
3744
		}
3745
3746
		if ( is_wp_error( $response ) ) {
3747
			$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...
3748
			$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...
3749
			$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...
3750
3751
			if ( ! is_int( $status_code ) ) {
3752
				$status_code = 400;
3753
			}
3754
3755
			status_header( $status_code );
3756
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3757
		}
3758
3759
		status_header( 200 );
3760
		if ( true === $response ) {
3761
			exit;
3762
		}
3763
3764
		die( json_encode( (object) $response ) );
3765
	}
3766
3767
	/**
3768
	 * Uploads a file gotten from the global $_FILES.
3769
	 * If `$update_media_item` is true and `post_id` is defined
3770
	 * the attachment file of the media item (gotten through of the post_id)
3771
	 * will be updated instead of add a new one.
3772
	 *
3773
	 * @param  boolean $update_media_item - update media attachment
3774
	 * @return array - An array describing the uploadind files process
3775
	 */
3776
	function upload_handler( $update_media_item = false ) {
3777
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3778
			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...
3779
		}
3780
3781
		$user = wp_authenticate( '', '' );
3782
		if ( ! $user || is_wp_error( $user ) ) {
3783
			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...
3784
		}
3785
3786
		wp_set_current_user( $user->ID );
3787
3788
		if ( ! current_user_can( 'upload_files' ) ) {
3789
			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...
3790
		}
3791
3792
		if ( empty( $_FILES ) ) {
3793
			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...
3794
		}
3795
3796
		foreach ( array_keys( $_FILES ) as $files_key ) {
3797
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3798
				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...
3799
			}
3800
		}
3801
3802
		$media_keys = array_keys( $_FILES['media'] );
3803
3804
		$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...
3805
		if ( ! $token || is_wp_error( $token ) ) {
3806
			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...
3807
		}
3808
3809
		$uploaded_files = array();
3810
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3811
		unset( $GLOBALS['post'] );
3812
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3813
			$file = array();
3814
			foreach ( $media_keys as $media_key ) {
3815
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3816
			}
3817
3818
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3819
3820
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3821
			if ( $hmac_provided !== $hmac_file ) {
3822
				$uploaded_files[ $index ] = (object) array(
3823
					'error'             => 'invalid_hmac',
3824
					'error_description' => 'The corresponding HMAC for this file does not match',
3825
				);
3826
				continue;
3827
			}
3828
3829
			$_FILES['.jetpack.upload.'] = $file;
3830
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3831
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3832
				$post_id = 0;
3833
			}
3834
3835
			if ( $update_media_item ) {
3836
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3837
					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...
3838
				}
3839
3840
				$media_array = $_FILES['media'];
3841
3842
				$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...
3843
				$file_array['type']     = $media_array['type'][0];
3844
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3845
				$file_array['error']    = $media_array['error'][0];
3846
				$file_array['size']     = $media_array['size'][0];
3847
3848
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3849
3850
				if ( is_wp_error( $edited_media_item ) ) {
3851
					return $edited_media_item;
3852
				}
3853
3854
				$response = (object) array(
3855
					'id'   => (string) $post_id,
3856
					'file' => (string) $edited_media_item->post_title,
3857
					'url'  => (string) wp_get_attachment_url( $post_id ),
3858
					'type' => (string) $edited_media_item->post_mime_type,
3859
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3860
				);
3861
3862
				return (array) array( $response );
3863
			}
3864
3865
			$attachment_id = media_handle_upload(
3866
				'.jetpack.upload.',
3867
				$post_id,
3868
				array(),
3869
				array(
3870
					'action' => 'jetpack_upload_file',
3871
				)
3872
			);
3873
3874
			if ( ! $attachment_id ) {
3875
				$uploaded_files[ $index ] = (object) array(
3876
					'error'             => 'unknown',
3877
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3878
				);
3879
			} elseif ( is_wp_error( $attachment_id ) ) {
3880
				$uploaded_files[ $index ] = (object) array(
3881
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3882
					'error_description' => $attachment_id->get_error_message(),
3883
				);
3884
			} else {
3885
				$attachment               = get_post( $attachment_id );
3886
				$uploaded_files[ $index ] = (object) array(
3887
					'id'   => (string) $attachment_id,
3888
					'file' => $attachment->post_title,
3889
					'url'  => wp_get_attachment_url( $attachment_id ),
3890
					'type' => $attachment->post_mime_type,
3891
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3892
				);
3893
				// Zip files uploads are not supported unless they are done for installation purposed
3894
				// lets delete them in case something goes wrong in this whole process
3895
				if ( 'application/zip' === $attachment->post_mime_type ) {
3896
					// Schedule a cleanup for 2 hours from now in case of failed install.
3897
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3898
				}
3899
			}
3900
		}
3901
		if ( ! is_null( $global_post ) ) {
3902
			$GLOBALS['post'] = $global_post;
3903
		}
3904
3905
		return $uploaded_files;
3906
	}
3907
3908
	/**
3909
	 * Add help to the Jetpack page
3910
	 *
3911
	 * @since Jetpack (1.2.3)
3912
	 * @return false if not the Jetpack page
3913
	 */
3914
	function admin_help() {
3915
		$current_screen = get_current_screen();
3916
3917
		// Overview
3918
		$current_screen->add_help_tab(
3919
			array(
3920
				'id'      => 'home',
3921
				'title'   => __( 'Home', 'jetpack' ),
3922
				'content' =>
3923
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3924
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3925
					'<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>',
3926
			)
3927
		);
3928
3929
		// Screen Content
3930
		if ( current_user_can( 'manage_options' ) ) {
3931
			$current_screen->add_help_tab(
3932
				array(
3933
					'id'      => 'settings',
3934
					'title'   => __( 'Settings', 'jetpack' ),
3935
					'content' =>
3936
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3937
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3938
						'<ol>' .
3939
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3940
							'<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>' .
3941
						'</ol>' .
3942
						'<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>',
3943
				)
3944
			);
3945
		}
3946
3947
		// Help Sidebar
3948
		$support_url = Redirect::get_url( 'jetpack-support' );
3949
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3950
		$current_screen->set_help_sidebar(
3951
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3952
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3953
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3954
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3955
		);
3956
	}
3957
3958
	function admin_menu_css() {
3959
		wp_enqueue_style( 'jetpack-icons' );
3960
	}
3961
3962
	function admin_menu_order() {
3963
		return true;
3964
	}
3965
3966 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3967
		$jp_menu_order = array();
3968
3969
		foreach ( $menu_order as $index => $item ) {
3970
			if ( $item != 'jetpack' ) {
3971
				$jp_menu_order[] = $item;
3972
			}
3973
3974
			if ( $index == 0 ) {
3975
				$jp_menu_order[] = 'jetpack';
3976
			}
3977
		}
3978
3979
		return $jp_menu_order;
3980
	}
3981
3982
	function admin_banner_styles() {
3983
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3984
3985 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3986
			wp_register_style(
3987
				'jetpack-dops-style',
3988
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3989
				array(),
3990
				JETPACK__VERSION
3991
			);
3992
		}
3993
3994
		wp_enqueue_style(
3995
			'jetpack',
3996
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3997
			array( 'jetpack-dops-style' ),
3998
			JETPACK__VERSION . '-20121016'
3999
		);
4000
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4001
		wp_style_add_data( 'jetpack', 'suffix', $min );
4002
	}
4003
4004
	function plugin_action_links( $actions ) {
4005
4006
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4007
4008
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
4009
			return array_merge(
4010
				$jetpack_home,
4011
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4012
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4013
				$actions
4014
			);
4015
		}
4016
4017
		return array_merge( $jetpack_home, $actions );
4018
	}
4019
4020
	/**
4021
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4022
	 *
4023
	 * @param string $hook The current admin page.
4024
	 *
4025
	 * @return void
4026
	 */
4027
	public function deactivate_dialog( $hook ) {
4028
		if (
4029
			'plugins.php' === $hook
4030
			&& self::is_active()
4031
		) {
4032
4033
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4034
4035
			if ( count( $active_plugins_using_connection ) > 1 ) {
4036
4037
				add_thickbox();
4038
4039
				wp_register_script(
4040
					'jp-tracks',
4041
					'//stats.wp.com/w.js',
4042
					array(),
4043
					gmdate( 'YW' ),
4044
					true
4045
				);
4046
4047
				wp_register_script(
4048
					'jp-tracks-functions',
4049
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4050
					array( 'jp-tracks' ),
4051
					JETPACK__VERSION,
4052
					false
4053
				);
4054
4055
				wp_enqueue_script(
4056
					'jetpack-deactivate-dialog-js',
4057
					Assets::get_file_url_for_environment(
4058
						'_inc/build/jetpack-deactivate-dialog.min.js',
4059
						'_inc/jetpack-deactivate-dialog.js'
4060
					),
4061
					array( 'jquery', 'jp-tracks-functions' ),
4062
					JETPACK__VERSION,
4063
					true
4064
				);
4065
4066
				wp_localize_script(
4067
					'jetpack-deactivate-dialog-js',
4068
					'deactivate_dialog',
4069
					array(
4070
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4071
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4072
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4073
					)
4074
				);
4075
4076
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4077
4078
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4079
			}
4080
		}
4081
	}
4082
4083
	/**
4084
	 * Outputs the content of the deactivation modal
4085
	 *
4086
	 * @return void
4087
	 */
4088
	public function deactivate_dialog_content() {
4089
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4090
		unset( $active_plugins_using_connection['jetpack'] );
4091
		$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 4089 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...
4092
	}
4093
4094
	/**
4095
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4096
	 *
4097
	 * @param string $login_url The wp-login URL.
4098
	 * @param string $redirect  URL to redirect users after logging in.
4099
	 * @since Jetpack 8.4
4100
	 * @return string
4101
	 */
4102
	public function login_url( $login_url, $redirect ) {
4103
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
4104
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4105
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4106
		}
4107
		return $login_url;
4108
	}
4109
4110
	/**
4111
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4112
	 *
4113
	 * @since Jetpack 8.4
4114
	 */
4115
	public function login_init() {
4116
		// phpcs:ignore WordPress.Security.NonceVerification
4117
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4118
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4119
			wp_safe_redirect(
4120
				add_query_arg(
4121
					array(
4122
						'forceInstall' => 1,
4123
						'url'          => rawurlencode( get_site_url() ),
4124
					),
4125
					// @todo provide way to go to specific calypso env.
4126
					self::get_calypso_host() . 'jetpack/connect'
4127
				)
4128
			);
4129
			exit;
4130
		}
4131
	}
4132
4133
	/*
4134
	 * Registration flow:
4135
	 * 1 - ::admin_page_load() action=register
4136
	 * 2 - ::try_registration()
4137
	 * 3 - ::register()
4138
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4139
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4140
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4141
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4142
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4143
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4144
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4145
	 *       jetpack_id, jetpack_secret, jetpack_public
4146
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4147
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4148
	 * 5 - user logs in with WP.com account
4149
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4150
	 *		- Manager::authorize()
4151
	 *		- Manager::get_token()
4152
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4153
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4154
	 *			- which responds with access_token, token_type, scope
4155
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4156
	 *		- Jetpack::activate_default_modules()
4157
	 *     		- Deactivates deprecated plugins
4158
	 *     		- Activates all default modules
4159
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4160
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4161
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4162
	 *     Done!
4163
	 */
4164
4165
	/**
4166
	 * Handles the page load events for the Jetpack admin page
4167
	 */
4168
	function admin_page_load() {
4169
		$error = false;
4170
4171
		// Make sure we have the right body class to hook stylings for subpages off of.
4172
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4173
4174
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4175
			// Should only be used in intermediate redirects to preserve state across redirects
4176
			self::restate();
4177
		}
4178
4179
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4180
			// @todo: Add validation against a known allowed list.
4181
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4182
			// User clicked in the iframe to link their accounts
4183
			if ( ! self::is_user_connected() ) {
4184
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4185
4186
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4187
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4188
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4189
4190
				if ( isset( $_GET['notes_iframe'] ) ) {
4191
					$connect_url .= '&notes_iframe';
4192
				}
4193
				wp_redirect( $connect_url );
4194
				exit;
4195
			} else {
4196
				if ( ! isset( $_GET['calypso_env'] ) ) {
4197
					self::state( 'message', 'already_authorized' );
4198
					wp_safe_redirect( self::admin_url() );
4199
					exit;
4200
				} else {
4201
					$connect_url  = $this->build_connect_url( true, false, $from );
4202
					$connect_url .= '&already_authorized=true';
4203
					wp_redirect( $connect_url );
4204
					exit;
4205
				}
4206
			}
4207
		}
4208
4209
		if ( isset( $_GET['action'] ) ) {
4210
			switch ( $_GET['action'] ) {
4211
				case 'authorize':
4212
					if ( self::is_active() && self::is_user_connected() ) {
4213
						self::state( 'message', 'already_authorized' );
4214
						wp_safe_redirect( self::admin_url() );
4215
						exit;
4216
					}
4217
					self::log( 'authorize' );
4218
					$client_server = new Jetpack_Client_Server();
4219
					$client_server->client_authorize();
4220
					exit;
4221
				case 'register':
4222
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4223
						$error = 'cheatin';
4224
						break;
4225
					}
4226
					check_admin_referer( 'jetpack-register' );
4227
					self::log( 'register' );
4228
					self::maybe_set_version_option();
4229
					$registered = self::try_registration();
4230 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4231
						$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...
4232
						self::state( 'error', $error );
4233
						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...
4234
4235
						/**
4236
						 * Jetpack registration Error.
4237
						 *
4238
						 * @since 7.5.0
4239
						 *
4240
						 * @param string|int $error The error code.
4241
						 * @param \WP_Error $registered The error object.
4242
						 */
4243
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4244
						break;
4245
					}
4246
4247
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4248
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4249
4250
					/**
4251
					 * Jetpack registration Success.
4252
					 *
4253
					 * @since 7.5.0
4254
					 *
4255
					 * @param string $from 'from' GET parameter;
4256
					 */
4257
					do_action( 'jetpack_connection_register_success', $from );
4258
4259
					$url = $this->build_connect_url( true, $redirect, $from );
4260
4261
					if ( ! empty( $_GET['onboarding'] ) ) {
4262
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4263
					}
4264
4265
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4266
						$url = add_query_arg( 'auth_approved', 'true', $url );
4267
					}
4268
4269
					wp_redirect( $url );
4270
					exit;
4271
				case 'activate':
4272
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4273
						$error = 'cheatin';
4274
						break;
4275
					}
4276
4277
					$module = stripslashes( $_GET['module'] );
4278
					check_admin_referer( "jetpack_activate-$module" );
4279
					self::log( 'activate', $module );
4280
					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...
4281
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4282
					}
4283
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4284
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4285
					exit;
4286
				case 'activate_default_modules':
4287
					check_admin_referer( 'activate_default_modules' );
4288
					self::log( 'activate_default_modules' );
4289
					self::restate();
4290
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4291
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4292
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4293
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4294
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4295
					exit;
4296
				case 'disconnect':
4297
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4298
						$error = 'cheatin';
4299
						break;
4300
					}
4301
4302
					check_admin_referer( 'jetpack-disconnect' );
4303
					self::log( 'disconnect' );
4304
					self::disconnect();
4305
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4306
					exit;
4307
				case 'reconnect':
4308
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4309
						$error = 'cheatin';
4310
						break;
4311
					}
4312
4313
					check_admin_referer( 'jetpack-reconnect' );
4314
					self::log( 'reconnect' );
4315
					$this->disconnect();
4316
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4317
					exit;
4318 View Code Duplication
				case 'deactivate':
4319
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4320
						$error = 'cheatin';
4321
						break;
4322
					}
4323
4324
					$modules = stripslashes( $_GET['module'] );
4325
					check_admin_referer( "jetpack_deactivate-$modules" );
4326
					foreach ( explode( ',', $modules ) as $module ) {
4327
						self::log( 'deactivate', $module );
4328
						self::deactivate_module( $module );
4329
						self::state( 'message', 'module_deactivated' );
4330
					}
4331
					self::state( 'module', $modules );
4332
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4333
					exit;
4334
				case 'unlink':
4335
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4336
					check_admin_referer( 'jetpack-unlink' );
4337
					self::log( 'unlink' );
4338
					Connection_Manager::disconnect_user();
4339
					self::state( 'message', 'unlinked' );
4340
					if ( 'sub-unlink' == $redirect ) {
4341
						wp_safe_redirect( admin_url() );
4342
					} else {
4343
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4344
					}
4345
					exit;
4346
				case 'onboard':
4347
					if ( ! current_user_can( 'manage_options' ) ) {
4348
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4349
					} else {
4350
						self::create_onboarding_token();
4351
						$url = $this->build_connect_url( true );
4352
4353
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4354
							$url = add_query_arg( 'onboarding', $token, $url );
4355
						}
4356
4357
						$calypso_env = $this->get_calypso_env();
4358
						if ( ! empty( $calypso_env ) ) {
4359
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4360
						}
4361
4362
						wp_redirect( $url );
4363
						exit;
4364
					}
4365
					exit;
4366
				default:
4367
					/**
4368
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4369
					 *
4370
					 * @since 2.6.0
4371
					 *
4372
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4373
					 */
4374
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4375
			}
4376
		}
4377
4378
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4379
			self::activate_new_modules( true );
4380
		}
4381
4382
		$message_code = self::state( 'message' );
4383
		if ( self::state( 'optin-manage' ) ) {
4384
			$activated_manage = $message_code;
4385
			$message_code     = 'jetpack-manage';
4386
		}
4387
4388
		switch ( $message_code ) {
4389
			case 'jetpack-manage':
4390
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4391
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4392
				$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>';
4393
				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...
4394
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4395
				}
4396
				break;
4397
4398
		}
4399
4400
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4401
4402
		if ( ! empty( $deactivated_plugins ) ) {
4403
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4404
			$deactivated_titles  = array();
4405
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4406
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4407
					continue;
4408
				}
4409
4410
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4411
			}
4412
4413
			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...
4414
				if ( $this->message ) {
4415
					$this->message .= "<br /><br />\n";
4416
				}
4417
4418
				$this->message .= wp_sprintf(
4419
					_n(
4420
						'Jetpack contains the most recent version of the old %l plugin.',
4421
						'Jetpack contains the most recent versions of the old %l plugins.',
4422
						count( $deactivated_titles ),
4423
						'jetpack'
4424
					),
4425
					$deactivated_titles
4426
				);
4427
4428
				$this->message .= "<br />\n";
4429
4430
				$this->message .= _n(
4431
					'The old version has been deactivated and can be removed from your site.',
4432
					'The old versions have been deactivated and can be removed from your site.',
4433
					count( $deactivated_titles ),
4434
					'jetpack'
4435
				);
4436
			}
4437
		}
4438
4439
		$this->privacy_checks = self::state( 'privacy_checks' );
4440
4441
		if ( $this->message || $this->error || $this->privacy_checks ) {
4442
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4443
		}
4444
4445
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4446
	}
4447
4448
	function admin_notices() {
4449
4450
		if ( $this->error ) {
4451
			?>
4452
<div id="message" class="jetpack-message jetpack-err">
4453
	<div class="squeezer">
4454
		<h2>
4455
			<?php
4456
			echo wp_kses(
4457
				$this->error,
4458
				array(
4459
					'a'      => array( 'href' => array() ),
4460
					'small'  => true,
4461
					'code'   => true,
4462
					'strong' => true,
4463
					'br'     => true,
4464
					'b'      => true,
4465
				)
4466
			);
4467
			?>
4468
			</h2>
4469
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4470
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4471
<?php	endif; ?>
4472
	</div>
4473
</div>
4474
			<?php
4475
		}
4476
4477
		if ( $this->message ) {
4478
			?>
4479
<div id="message" class="jetpack-message">
4480
	<div class="squeezer">
4481
		<h2>
4482
			<?php
4483
			echo wp_kses(
4484
				$this->message,
4485
				array(
4486
					'strong' => array(),
4487
					'a'      => array( 'href' => true ),
4488
					'br'     => true,
4489
				)
4490
			);
4491
			?>
4492
			</h2>
4493
	</div>
4494
</div>
4495
			<?php
4496
		}
4497
4498
		if ( $this->privacy_checks ) :
4499
			$module_names = $module_slugs = array();
4500
4501
			$privacy_checks = explode( ',', $this->privacy_checks );
4502
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4503
			foreach ( $privacy_checks as $module_slug ) {
4504
				$module = self::get_module( $module_slug );
4505
				if ( ! $module ) {
4506
					continue;
4507
				}
4508
4509
				$module_slugs[] = $module_slug;
4510
				$module_names[] = "<strong>{$module['name']}</strong>";
4511
			}
4512
4513
			$module_slugs = join( ',', $module_slugs );
4514
			?>
4515
<div id="message" class="jetpack-message jetpack-err">
4516
	<div class="squeezer">
4517
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4518
		<p>
4519
			<?php
4520
			echo wp_kses(
4521
				wptexturize(
4522
					wp_sprintf(
4523
						_nx(
4524
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4525
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4526
							count( $privacy_checks ),
4527
							'%l = list of Jetpack module/feature names',
4528
							'jetpack'
4529
						),
4530
						$module_names
4531
					)
4532
				),
4533
				array( 'strong' => true )
4534
			);
4535
4536
			echo "\n<br />\n";
4537
4538
			echo wp_kses(
4539
				sprintf(
4540
					_nx(
4541
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4542
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4543
						count( $privacy_checks ),
4544
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4545
						'jetpack'
4546
					),
4547
					wp_nonce_url(
4548
						self::admin_url(
4549
							array(
4550
								'page'   => 'jetpack',
4551
								'action' => 'deactivate',
4552
								'module' => urlencode( $module_slugs ),
4553
							)
4554
						),
4555
						"jetpack_deactivate-$module_slugs"
4556
					),
4557
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4558
				),
4559
				array(
4560
					'a' => array(
4561
						'href'  => true,
4562
						'title' => true,
4563
					),
4564
				)
4565
			);
4566
			?>
4567
		</p>
4568
	</div>
4569
</div>
4570
			<?php
4571
endif;
4572
	}
4573
4574
	/**
4575
	 * We can't always respond to a signed XML-RPC request with a
4576
	 * helpful error message. In some circumstances, doing so could
4577
	 * leak information.
4578
	 *
4579
	 * Instead, track that the error occurred via a Jetpack_Option,
4580
	 * and send that data back in the heartbeat.
4581
	 * All this does is increment a number, but it's enough to find
4582
	 * trends.
4583
	 *
4584
	 * @param WP_Error $xmlrpc_error The error produced during
4585
	 *                               signature validation.
4586
	 */
4587
	function track_xmlrpc_error( $xmlrpc_error ) {
4588
		$code = is_wp_error( $xmlrpc_error )
4589
			? $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...
4590
			: 'should-not-happen';
4591
4592
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4593
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4594
			// No need to update the option if we already have
4595
			// this code stored.
4596
			return;
4597
		}
4598
		$xmlrpc_errors[ $code ] = true;
4599
4600
		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...
4601
	}
4602
4603
	/**
4604
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4605
	 */
4606
	function stat( $group, $detail ) {
4607
		if ( ! isset( $this->stats[ $group ] ) ) {
4608
			$this->stats[ $group ] = array();
4609
		}
4610
		$this->stats[ $group ][] = $detail;
4611
	}
4612
4613
	/**
4614
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4615
	 */
4616
	function do_stats( $method = '' ) {
4617
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4618
			foreach ( $this->stats as $group => $stats ) {
4619
				if ( is_array( $stats ) && count( $stats ) ) {
4620
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4621
					if ( 'server_side' === $method ) {
4622
						self::do_server_side_stat( $args );
4623
					} else {
4624
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4625
					}
4626
				}
4627
				unset( $this->stats[ $group ] );
4628
			}
4629
		}
4630
	}
4631
4632
	/**
4633
	 * Runs stats code for a one-off, server-side.
4634
	 *
4635
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4636
	 *
4637
	 * @return bool If it worked.
4638
	 */
4639
	static function do_server_side_stat( $args ) {
4640
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4641
		if ( is_wp_error( $response ) ) {
4642
			return false;
4643
		}
4644
4645
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4646
			return false;
4647
		}
4648
4649
		return true;
4650
	}
4651
4652
	/**
4653
	 * Builds the stats url.
4654
	 *
4655
	 * @param $args array|string The arguments to append to the URL.
4656
	 *
4657
	 * @return string The URL to be pinged.
4658
	 */
4659
	static function build_stats_url( $args ) {
4660
		$defaults = array(
4661
			'v'    => 'wpcom2',
4662
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4663
		);
4664
		$args     = wp_parse_args( $args, $defaults );
0 ignored issues
show
Documentation introduced by
$defaults is of type array<string,string,{"v"...ring","rand":"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...
4665
		/**
4666
		 * Filter the URL used as the Stats tracking pixel.
4667
		 *
4668
		 * @since 2.3.2
4669
		 *
4670
		 * @param string $url Base URL used as the Stats tracking pixel.
4671
		 */
4672
		$base_url = apply_filters(
4673
			'jetpack_stats_base_url',
4674
			'https://pixel.wp.com/g.gif'
4675
		);
4676
		$url      = add_query_arg( $args, $base_url );
4677
		return $url;
4678
	}
4679
4680
	/**
4681
	 * Get the role of the current user.
4682
	 *
4683
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4684
	 *
4685
	 * @access public
4686
	 * @static
4687
	 *
4688
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4689
	 */
4690
	public static function translate_current_user_to_role() {
4691
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4692
4693
		$roles = new Roles();
4694
		return $roles->translate_current_user_to_role();
4695
	}
4696
4697
	/**
4698
	 * Get the role of a particular user.
4699
	 *
4700
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4701
	 *
4702
	 * @access public
4703
	 * @static
4704
	 *
4705
	 * @param \WP_User $user User object.
4706
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4707
	 */
4708
	public static function translate_user_to_role( $user ) {
4709
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4710
4711
		$roles = new Roles();
4712
		return $roles->translate_user_to_role( $user );
4713
	}
4714
4715
	/**
4716
	 * Get the minimum capability for a role.
4717
	 *
4718
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4719
	 *
4720
	 * @access public
4721
	 * @static
4722
	 *
4723
	 * @param string $role Role name.
4724
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4725
	 */
4726
	public static function translate_role_to_cap( $role ) {
4727
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4728
4729
		$roles = new Roles();
4730
		return $roles->translate_role_to_cap( $role );
4731
	}
4732
4733
	/**
4734
	 * Sign a user role with the master access token.
4735
	 * If not specified, will default to the current user.
4736
	 *
4737
	 * @deprecated since 7.7
4738
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4739
	 *
4740
	 * @access public
4741
	 * @static
4742
	 *
4743
	 * @param string $role    User role.
4744
	 * @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...
4745
	 * @return string Signed user role.
4746
	 */
4747
	public static function sign_role( $role, $user_id = null ) {
4748
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4749
		return self::connection()->sign_role( $role, $user_id );
4750
	}
4751
4752
	/**
4753
	 * Builds a URL to the Jetpack connection auth page
4754
	 *
4755
	 * @since 3.9.5
4756
	 *
4757
	 * @param bool        $raw If true, URL will not be escaped.
4758
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4759
	 *                              If string, will be a custom redirect.
4760
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4761
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4762
	 *
4763
	 * @return string Connect URL
4764
	 */
4765
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4766
		$site_id    = Jetpack_Options::get_option( 'id' );
4767
		$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...
4768
4769
		if ( $register || ! $blog_token || ! $site_id ) {
4770
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4771
4772
			if ( ! empty( $redirect ) ) {
4773
				$url = add_query_arg(
4774
					'redirect',
4775
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4776
					$url
4777
				);
4778
			}
4779
4780
			if ( is_network_admin() ) {
4781
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4782
			}
4783
4784
			$calypso_env = self::get_calypso_env();
4785
4786
			if ( ! empty( $calypso_env ) ) {
4787
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4788
			}
4789
		} else {
4790
4791
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4792
			// because otherwise this logic can get us in to a loop.
4793
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4794
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4795
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4796
4797
				$response = Client::wpcom_json_api_request_as_blog(
4798
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4799
					'1.1'
4800
				);
4801
4802
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4803
4804
					// Generating a register URL instead to refresh the existing token
4805
					return $this->build_connect_url( $raw, $redirect, $from, true );
4806
				}
4807
			}
4808
4809
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4765 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...
4810
		}
4811
4812
		if ( $from ) {
4813
			$url = add_query_arg( 'from', $from, $url );
4814
		}
4815
4816
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4817
		/**
4818
		 * Filter the URL used when connecting a user to a WordPress.com account.
4819
		 *
4820
		 * @since 8.1.0
4821
		 *
4822
		 * @param string $url Connection URL.
4823
		 * @param bool   $raw If true, URL will not be escaped.
4824
		 */
4825
		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...
4826
	}
4827
4828
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4829
4830
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4831
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4832
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4833
4834
		if ( $iframe ) {
4835
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4836
		}
4837
4838
		$c8n = self::connection();
4839
		$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...
4840
4841
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4842
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4843
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4844
4845
		if ( $iframe ) {
4846
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4847
		}
4848
4849
		return $url;
4850
	}
4851
4852
	/**
4853
	 * Filters the connection URL parameter array.
4854
	 *
4855
	 * @param array $args default URL parameters used by the package.
4856
	 * @return array the modified URL arguments array.
4857
	 */
4858
	public static function filter_connect_request_body( $args ) {
4859
		if (
4860
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4861
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4862
		) {
4863
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4864
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4865
				? $gp_locale->slug
4866
				: '';
4867
		}
4868
4869
		$tracking        = new Tracking();
4870
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4871
4872
		$args = array_merge(
4873
			$args,
4874
			array(
4875
				'_ui' => $tracks_identity['_ui'],
4876
				'_ut' => $tracks_identity['_ut'],
4877
			)
4878
		);
4879
4880
		$calypso_env = self::get_calypso_env();
4881
4882
		if ( ! empty( $calypso_env ) ) {
4883
			$args['calypso_env'] = $calypso_env;
4884
		}
4885
4886
		return $args;
4887
	}
4888
4889
	/**
4890
	 * Filters the URL that will process the connection data. It can be different from the URL
4891
	 * that we send the user to after everything is done.
4892
	 *
4893
	 * @param String $processing_url the default redirect URL used by the package.
4894
	 * @return String the modified URL.
4895
	 */
4896
	public static function filter_connect_processing_url( $processing_url ) {
4897
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4898
		return $processing_url;
4899
	}
4900
4901
	/**
4902
	 * Filters the redirection URL that is used for connect requests. The redirect
4903
	 * URL should return the user back to the Jetpack console.
4904
	 *
4905
	 * @param String $redirect the default redirect URL used by the package.
4906
	 * @return String the modified URL.
4907
	 */
4908
	public static function filter_connect_redirect_url( $redirect ) {
4909
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4910
		$redirect           = $redirect
4911
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4912
			: $jetpack_admin_page;
4913
4914
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4915
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4916
		}
4917
4918
		return $redirect;
4919
	}
4920
4921
	/**
4922
	 * This action fires at the beginning of the Manager::authorize method.
4923
	 */
4924
	public static function authorize_starting() {
4925
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4926
		// Checking if site has been active/connected previously before recording unique connection.
4927
		if ( ! $jetpack_unique_connection ) {
4928
			// jetpack_unique_connection option has never been set.
4929
			$jetpack_unique_connection = array(
4930
				'connected'    => 0,
4931
				'disconnected' => 0,
4932
				'version'      => '3.6.1',
4933
			);
4934
4935
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4936
4937
			// Track unique connection.
4938
			$jetpack = self::init();
4939
4940
			$jetpack->stat( 'connections', 'unique-connection' );
4941
			$jetpack->do_stats( 'server_side' );
4942
		}
4943
4944
		// Increment number of times connected.
4945
		$jetpack_unique_connection['connected'] += 1;
4946
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4947
	}
4948
4949
	/**
4950
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4951
	 * linked.
4952
	 */
4953
	public static function authorize_ending_linked() {
4954
		// Don't activate anything since we are just connecting a user.
4955
		self::state( 'message', 'linked' );
4956
	}
4957
4958
	/**
4959
	 * This action fires at the end of the Manager::authorize method when the master user is
4960
	 * authorized.
4961
	 *
4962
	 * @param array $data The request data.
4963
	 */
4964
	public static function authorize_ending_authorized( $data ) {
4965
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4966
		self::invalidate_onboarding_token();
4967
4968
		// If redirect_uri is SSO, ensure SSO module is enabled.
4969
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
4970
4971
		/** This filter is documented in class.jetpack-cli.php */
4972
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4973
4974
		$activate_sso = (
4975
			isset( $redirect_options['action'] ) &&
4976
			'jetpack-sso' === $redirect_options['action'] &&
4977
			$jetpack_start_enable_sso
4978
		);
4979
4980
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4981
4982
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4983
	}
4984
4985
	/**
4986
	 * Get our assumed site creation date.
4987
	 * Calculated based on the earlier date of either:
4988
	 * - Earliest admin user registration date.
4989
	 * - Earliest date of post of any post type.
4990
	 *
4991
	 * @since 7.2.0
4992
	 * @deprecated since 7.8.0
4993
	 *
4994
	 * @return string Assumed site creation date and time.
4995
	 */
4996
	public static function get_assumed_site_creation_date() {
4997
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4998
		return self::connection()->get_assumed_site_creation_date();
4999
	}
5000
5001 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5002
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5003
5004
		if ( $activation_source_name ) {
5005
			$args['_as'] = urlencode( $activation_source_name );
5006
		}
5007
5008
		if ( $activation_source_keyword ) {
5009
			$args['_ak'] = urlencode( $activation_source_keyword );
5010
		}
5011
	}
5012
5013
	function build_reconnect_url( $raw = false ) {
5014
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5015
		return $raw ? $url : esc_url( $url );
5016
	}
5017
5018
	public static function admin_url( $args = null ) {
5019
		$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...
5020
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5021
		return $url;
5022
	}
5023
5024
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5025
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5026
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5027
	}
5028
5029
	function dismiss_jetpack_notice() {
5030
5031
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5032
			return;
5033
		}
5034
5035
		switch ( $_GET['jetpack-notice'] ) {
5036
			case 'dismiss':
5037
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5038
5039
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5040
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5041
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5042
				}
5043
				break;
5044
		}
5045
	}
5046
5047
	public static function sort_modules( $a, $b ) {
5048
		if ( $a['sort'] == $b['sort'] ) {
5049
			return 0;
5050
		}
5051
5052
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5053
	}
5054
5055
	function ajax_recheck_ssl() {
5056
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5057
		$result = self::permit_ssl( true );
5058
		wp_send_json(
5059
			array(
5060
				'enabled' => $result,
5061
				'message' => get_transient( 'jetpack_https_test_message' ),
5062
			)
5063
		);
5064
	}
5065
5066
	/* Client API */
5067
5068
	/**
5069
	 * Returns the requested Jetpack API URL
5070
	 *
5071
	 * @deprecated since 7.7
5072
	 * @return string
5073
	 */
5074
	public static function api_url( $relative_url ) {
5075
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5076
		$connection = self::connection();
5077
		return $connection->api_url( $relative_url );
5078
	}
5079
5080
	/**
5081
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5082
	 *
5083
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5084
	 */
5085
	public static function fix_url_for_bad_hosts( $url ) {
5086
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5087
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5088
	}
5089
5090
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5091
		// Default to a blog token.
5092
		$token_type = 'blog';
5093
5094
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5095
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5096
			if ( ! empty( $_GET['onboarding'] ) ) {
5097
				$jpo = $_GET;
5098
			} else {
5099
				$jpo = json_decode( $request_data, true );
5100
			}
5101
5102
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5103
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5104
5105
			if (
5106
				isset( $jpo_user )
5107
				&& isset( $jpo_token )
5108
				&& is_email( $jpo_user )
5109
				&& ctype_alnum( $jpo_token )
5110
				&& isset( $_GET['rest_route'] )
5111
				&& self::validate_onboarding_token_action(
5112
					$jpo_token,
5113
					$_GET['rest_route']
5114
				)
5115
			) {
5116
				$jp_user = get_user_by( 'email', $jpo_user );
5117
				if ( is_a( $jp_user, 'WP_User' ) ) {
5118
					wp_set_current_user( $jp_user->ID );
5119
					$user_can = is_multisite()
5120
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5121
						: current_user_can( 'manage_options' );
5122
					if ( $user_can ) {
5123
						$token_type              = 'user';
5124
						$token->external_user_id = $jp_user->ID;
5125
					}
5126
				}
5127
			}
5128
5129
			$token_data['type']    = $token_type;
5130
			$token_data['user_id'] = $token->external_user_id;
5131
		}
5132
5133
		return $token_data;
5134
	}
5135
5136
	/**
5137
	 * Create a random secret for validating onboarding payload
5138
	 *
5139
	 * @return string Secret token
5140
	 */
5141
	public static function create_onboarding_token() {
5142
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5143
			$token = wp_generate_password( 32, false );
5144
			Jetpack_Options::update_option( 'onboarding', $token );
5145
		}
5146
5147
		return $token;
5148
	}
5149
5150
	/**
5151
	 * Remove the onboarding token
5152
	 *
5153
	 * @return bool True on success, false on failure
5154
	 */
5155
	public static function invalidate_onboarding_token() {
5156
		return Jetpack_Options::delete_option( 'onboarding' );
5157
	}
5158
5159
	/**
5160
	 * Validate an onboarding token for a specific action
5161
	 *
5162
	 * @return boolean True if token/action pair is accepted, false if not
5163
	 */
5164
	public static function validate_onboarding_token_action( $token, $action ) {
5165
		// Compare tokens, bail if tokens do not match
5166
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5167
			return false;
5168
		}
5169
5170
		// List of valid actions we can take
5171
		$valid_actions = array(
5172
			'/jetpack/v4/settings',
5173
		);
5174
5175
		// Only allow valid actions.
5176
		if ( ! in_array( $action, $valid_actions ) ) {
5177
			return false;
5178
		}
5179
5180
		return true;
5181
	}
5182
5183
	/**
5184
	 * Checks to see if the URL is using SSL to connect with Jetpack
5185
	 *
5186
	 * @since 2.3.3
5187
	 * @return boolean
5188
	 */
5189
	public static function permit_ssl( $force_recheck = false ) {
5190
		// Do some fancy tests to see if ssl is being supported
5191
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5192
			$message = '';
5193
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5194
				$ssl = 0;
5195
			} else {
5196
				switch ( JETPACK_CLIENT__HTTPS ) {
5197
					case 'NEVER':
5198
						$ssl     = 0;
5199
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5200
						break;
5201
					case 'ALWAYS':
5202
					case 'AUTO':
5203
					default:
5204
						$ssl = 1;
5205
						break;
5206
				}
5207
5208
				// If it's not 'NEVER', test to see
5209
				if ( $ssl ) {
5210
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5211
						$ssl     = 0;
5212
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5213
					} else {
5214
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5215
						if ( is_wp_error( $response ) ) {
5216
							$ssl     = 0;
5217
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5218
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5219
							$ssl     = 0;
5220
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5221
						}
5222
					}
5223
				}
5224
			}
5225
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5226
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5227
		}
5228
5229
		return (bool) $ssl;
5230
	}
5231
5232
	/*
5233
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5234
	 */
5235
	public function alert_auto_ssl_fail() {
5236
		if ( ! current_user_can( 'manage_options' ) ) {
5237
			return;
5238
		}
5239
5240
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5241
		?>
5242
5243
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5244
			<div class="jp-banner__content">
5245
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5246
				<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>
5247
				<p>
5248
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5249
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5250
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5251
				</p>
5252
				<p>
5253
					<?php
5254
					printf(
5255
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5256
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5257
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5258
					);
5259
					?>
5260
				</p>
5261
			</div>
5262
		</div>
5263
		<style>
5264
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5265
		</style>
5266
		<script type="text/javascript">
5267
			jQuery( document ).ready( function( $ ) {
5268
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5269
					var $this = $( this );
5270
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5271
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5272
					e.preventDefault();
5273
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5274
					$.post( ajaxurl, data )
5275
					  .done( function( response ) {
5276
						  if ( response.enabled ) {
5277
							  $( '#jetpack-ssl-warning' ).hide();
5278
						  } else {
5279
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5280
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5281
						  }
5282
					  }.bind( $this ) );
5283
				} );
5284
			} );
5285
		</script>
5286
5287
		<?php
5288
	}
5289
5290
	/**
5291
	 * Returns the Jetpack XML-RPC API
5292
	 *
5293
	 * @deprecated 8.0 Use Connection_Manager instead.
5294
	 * @return string
5295
	 */
5296
	public static function xmlrpc_api_url() {
5297
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5298
		return self::connection()->xmlrpc_api_url();
5299
	}
5300
5301
	/**
5302
	 * Returns the connection manager object.
5303
	 *
5304
	 * @return Automattic\Jetpack\Connection\Manager
5305
	 */
5306
	public static function connection() {
5307
		$jetpack = static::init();
5308
5309
		// If the connection manager hasn't been instantiated, do that now.
5310
		if ( ! $jetpack->connection_manager ) {
5311
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5312
		}
5313
5314
		return $jetpack->connection_manager;
5315
	}
5316
5317
	/**
5318
	 * Creates two secret tokens and the end of life timestamp for them.
5319
	 *
5320
	 * Note these tokens are unique per call, NOT static per site for connecting.
5321
	 *
5322
	 * @since 2.6
5323
	 * @param String  $action  The action name.
5324
	 * @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...
5325
	 * @param Integer $exp     Expiration time in seconds.
5326
	 * @return array
5327
	 */
5328
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5329
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5330
	}
5331
5332
	public static function get_secrets( $action, $user_id ) {
5333
		$secrets = self::connection()->get_secrets( $action, $user_id );
5334
5335
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5336
			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...
5337
		}
5338
5339
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5340
			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...
5341
		}
5342
5343
		return $secrets;
5344
	}
5345
5346
	/**
5347
	 * @deprecated 7.5 Use Connection_Manager instead.
5348
	 *
5349
	 * @param $action
5350
	 * @param $user_id
5351
	 */
5352
	public static function delete_secrets( $action, $user_id ) {
5353
		return self::connection()->delete_secrets( $action, $user_id );
5354
	}
5355
5356
	/**
5357
	 * Builds the timeout limit for queries talking with the wpcom servers.
5358
	 *
5359
	 * Based on local php max_execution_time in php.ini
5360
	 *
5361
	 * @since 2.6
5362
	 * @return int
5363
	 * @deprecated
5364
	 **/
5365
	public function get_remote_query_timeout_limit() {
5366
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5367
		return self::get_max_execution_time();
5368
	}
5369
5370
	/**
5371
	 * Builds the timeout limit for queries talking with the wpcom servers.
5372
	 *
5373
	 * Based on local php max_execution_time in php.ini
5374
	 *
5375
	 * @since 5.4
5376
	 * @return int
5377
	 **/
5378
	public static function get_max_execution_time() {
5379
		$timeout = (int) ini_get( 'max_execution_time' );
5380
5381
		// Ensure exec time set in php.ini
5382
		if ( ! $timeout ) {
5383
			$timeout = 30;
5384
		}
5385
		return $timeout;
5386
	}
5387
5388
	/**
5389
	 * Sets a minimum request timeout, and returns the current timeout
5390
	 *
5391
	 * @since 5.4
5392
	 **/
5393 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5394
		$timeout = self::get_max_execution_time();
5395
		if ( $timeout < $min_timeout ) {
5396
			$timeout = $min_timeout;
5397
			set_time_limit( $timeout );
5398
		}
5399
		return $timeout;
5400
	}
5401
5402
	/**
5403
	 * Takes the response from the Jetpack register new site endpoint and
5404
	 * verifies it worked properly.
5405
	 *
5406
	 * @since 2.6
5407
	 * @deprecated since 7.7.0
5408
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5409
	 **/
5410
	public function validate_remote_register_response() {
5411
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5412
	}
5413
5414
	/**
5415
	 * @return bool|WP_Error
5416
	 */
5417
	public static function register() {
5418
		$tracking = new Tracking();
5419
		$tracking->record_user_event( 'jpc_register_begin' );
5420
5421
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5422
5423
		$connection   = self::connection();
5424
		$registration = $connection->register();
5425
5426
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5427
5428
		if ( ! $registration || is_wp_error( $registration ) ) {
5429
			return $registration;
5430
		}
5431
5432
		return true;
5433
	}
5434
5435
	/**
5436
	 * Filters the registration request body to include tracking properties.
5437
	 *
5438
	 * @param array $properties
5439
	 * @return array amended properties.
5440
	 */
5441 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5442
		$tracking        = new Tracking();
5443
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5444
5445
		return array_merge(
5446
			$properties,
5447
			array(
5448
				'_ui' => $tracks_identity['_ui'],
5449
				'_ut' => $tracks_identity['_ut'],
5450
			)
5451
		);
5452
	}
5453
5454
	/**
5455
	 * Filters the token request body to include tracking properties.
5456
	 *
5457
	 * @param array $properties
5458
	 * @return array amended properties.
5459
	 */
5460 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5461
		$tracking        = new Tracking();
5462
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5463
5464
		return array_merge(
5465
			$properties,
5466
			array(
5467
				'_ui' => $tracks_identity['_ui'],
5468
				'_ut' => $tracks_identity['_ut'],
5469
			)
5470
		);
5471
	}
5472
5473
	/**
5474
	 * If the db version is showing something other that what we've got now, bump it to current.
5475
	 *
5476
	 * @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...
5477
	 */
5478
	public static function maybe_set_version_option() {
5479
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5480
		if ( JETPACK__VERSION != $version ) {
5481
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5482
5483
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5484
				/** This action is documented in class.jetpack.php */
5485
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5486
			}
5487
5488
			return true;
5489
		}
5490
		return false;
5491
	}
5492
5493
	/* Client Server API */
5494
5495
	/**
5496
	 * Loads the Jetpack XML-RPC client.
5497
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5498
	 *
5499
	 * @deprecated since 7.7.0
5500
	 */
5501
	public static function load_xml_rpc_client() {
5502
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5503
	}
5504
5505
	/**
5506
	 * Resets the saved authentication state in between testing requests.
5507
	 */
5508
	public function reset_saved_auth_state() {
5509
		$this->rest_authentication_status = null;
5510
5511
		if ( ! $this->connection_manager ) {
5512
			$this->connection_manager = new Connection_Manager();
5513
		}
5514
5515
		$this->connection_manager->reset_saved_auth_state();
5516
	}
5517
5518
	/**
5519
	 * Verifies the signature of the current request.
5520
	 *
5521
	 * @deprecated since 7.7.0
5522
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5523
	 *
5524
	 * @return false|array
5525
	 */
5526
	public function verify_xml_rpc_signature() {
5527
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5528
		return self::connection()->verify_xml_rpc_signature();
5529
	}
5530
5531
	/**
5532
	 * Verifies the signature of the current request.
5533
	 *
5534
	 * This function has side effects and should not be used. Instead,
5535
	 * use the memoized version `->verify_xml_rpc_signature()`.
5536
	 *
5537
	 * @deprecated since 7.7.0
5538
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5539
	 * @internal
5540
	 */
5541
	private function internal_verify_xml_rpc_signature() {
5542
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5543
	}
5544
5545
	/**
5546
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5547
	 *
5548
	 * @deprecated since 7.7.0
5549
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5550
	 *
5551
	 * @param \WP_User|mixed $user     User object if authenticated.
5552
	 * @param string         $username Username.
5553
	 * @param string         $password Password string.
5554
	 * @return \WP_User|mixed Authenticated user or error.
5555
	 */
5556 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5557
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5558
5559
		if ( ! $this->connection_manager ) {
5560
			$this->connection_manager = new Connection_Manager();
5561
		}
5562
5563
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5564
	}
5565
5566
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5567
	// Uses the existing XMLRPC request signing implementation.
5568
	function wp_rest_authenticate( $user ) {
5569
		if ( ! empty( $user ) ) {
5570
			// Another authentication method is in effect.
5571
			return $user;
5572
		}
5573
5574
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5575
			// Nothing to do for this authentication method.
5576
			return null;
5577
		}
5578
5579
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5580
			// Nothing to do for this authentication method.
5581
			return null;
5582
		}
5583
5584
		// Ensure that we always have the request body available.  At this
5585
		// point, the WP REST API code to determine the request body has not
5586
		// run yet.  That code may try to read from 'php://input' later, but
5587
		// this can only be done once per request in PHP versions prior to 5.6.
5588
		// So we will go ahead and perform this read now if needed, and save
5589
		// the request body where both the Jetpack signature verification code
5590
		// and the WP REST API code can see it.
5591
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5592
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5593
		}
5594
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5595
5596
		// Only support specific request parameters that have been tested and
5597
		// are known to work with signature verification.  A different method
5598
		// can be passed to the WP REST API via the '?_method=' parameter if
5599
		// needed.
5600
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5601
			$this->rest_authentication_status = new WP_Error(
5602
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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...
5603
				__( 'This request method is not supported.', 'jetpack' ),
5604
				array( 'status' => 400 )
5605
			);
5606
			return null;
5607
		}
5608
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5609
			$this->rest_authentication_status = new WP_Error(
5610
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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...
5611
				__( 'This request method does not support body parameters.', 'jetpack' ),
5612
				array( 'status' => 400 )
5613
			);
5614
			return null;
5615
		}
5616
5617
		if ( ! $this->connection_manager ) {
5618
			$this->connection_manager = new Connection_Manager();
5619
		}
5620
5621
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5622
5623
		if (
5624
			$verified &&
5625
			isset( $verified['type'] ) &&
5626
			'user' === $verified['type'] &&
5627
			! empty( $verified['user_id'] )
5628
		) {
5629
			// Authentication successful.
5630
			$this->rest_authentication_status = true;
5631
			return $verified['user_id'];
5632
		}
5633
5634
		// Something else went wrong.  Probably a signature error.
5635
		$this->rest_authentication_status = new WP_Error(
5636
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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...
5637
			__( 'The request is not signed correctly.', 'jetpack' ),
5638
			array( 'status' => 400 )
5639
		);
5640
		return null;
5641
	}
5642
5643
	/**
5644
	 * Report authentication status to the WP REST API.
5645
	 *
5646
	 * @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...
5647
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5648
	 */
5649
	public function wp_rest_authentication_errors( $value ) {
5650
		if ( $value !== null ) {
5651
			return $value;
5652
		}
5653
		return $this->rest_authentication_status;
5654
	}
5655
5656
	/**
5657
	 * Add our nonce to this request.
5658
	 *
5659
	 * @deprecated since 7.7.0
5660
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5661
	 *
5662
	 * @param int    $timestamp Timestamp of the request.
5663
	 * @param string $nonce     Nonce string.
5664
	 */
5665 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5666
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5667
5668
		if ( ! $this->connection_manager ) {
5669
			$this->connection_manager = new Connection_Manager();
5670
		}
5671
5672
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5673
	}
5674
5675
	/**
5676
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5677
	 * Capture it here so we can verify the signature later.
5678
	 *
5679
	 * @deprecated since 7.7.0
5680
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5681
	 *
5682
	 * @param array $methods XMLRPC methods.
5683
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5684
	 */
5685 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5686
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5687
5688
		if ( ! $this->connection_manager ) {
5689
			$this->connection_manager = new Connection_Manager();
5690
		}
5691
5692
		return $this->connection_manager->xmlrpc_methods( $methods );
5693
	}
5694
5695
	/**
5696
	 * Register additional public XMLRPC methods.
5697
	 *
5698
	 * @deprecated since 7.7.0
5699
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5700
	 *
5701
	 * @param array $methods Public XMLRPC methods.
5702
	 * @return array Public XMLRPC methods, with the getOptions one.
5703
	 */
5704 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5705
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5706
5707
		if ( ! $this->connection_manager ) {
5708
			$this->connection_manager = new Connection_Manager();
5709
		}
5710
5711
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5712
	}
5713
5714
	/**
5715
	 * Handles a getOptions XMLRPC method call.
5716
	 *
5717
	 * @deprecated since 7.7.0
5718
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5719
	 *
5720
	 * @param array $args method call arguments.
5721
	 * @return array an amended XMLRPC server options array.
5722
	 */
5723 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5724
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5725
5726
		if ( ! $this->connection_manager ) {
5727
			$this->connection_manager = new Connection_Manager();
5728
		}
5729
5730
		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...
5731
	}
5732
5733
	/**
5734
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5735
	 *
5736
	 * @deprecated since 7.7.0
5737
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5738
	 *
5739
	 * @param array $options Standard Core options.
5740
	 * @return array Amended options.
5741
	 */
5742 View Code Duplication
	public function xmlrpc_options( $options ) {
5743
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5744
5745
		if ( ! $this->connection_manager ) {
5746
			$this->connection_manager = new Connection_Manager();
5747
		}
5748
5749
		return $this->connection_manager->xmlrpc_options( $options );
5750
	}
5751
5752
	/**
5753
	 * Cleans nonces that were saved when calling ::add_nonce.
5754
	 *
5755
	 * @deprecated since 7.7.0
5756
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5757
	 *
5758
	 * @param bool $all whether to clean even non-expired nonces.
5759
	 */
5760
	public static function clean_nonces( $all = false ) {
5761
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5762
		return self::connection()->clean_nonces( $all );
5763
	}
5764
5765
	/**
5766
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5767
	 * SET: state( $key, $value );
5768
	 * GET: $value = state( $key );
5769
	 *
5770
	 * @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...
5771
	 * @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...
5772
	 * @param bool   $restate private
5773
	 */
5774
	public static function state( $key = null, $value = null, $restate = false ) {
5775
		static $state = array();
5776
		static $path, $domain;
5777
		if ( ! isset( $path ) ) {
5778
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5779
			$admin_url = self::admin_url();
5780
			$bits      = wp_parse_url( $admin_url );
5781
5782
			if ( is_array( $bits ) ) {
5783
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5784
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5785
			} else {
5786
				$path = $domain = null;
5787
			}
5788
		}
5789
5790
		// Extract state from cookies and delete cookies
5791
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5792
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5793
			unset( $_COOKIE['jetpackState'] );
5794
			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...
5795
				if ( strlen( $v ) ) {
5796
					$state[ $k ] = $v;
5797
				}
5798
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5799
			}
5800
		}
5801
5802
		if ( $restate ) {
5803
			foreach ( $state as $k => $v ) {
5804
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5805
			}
5806
			return;
5807
		}
5808
5809
		// Get a state variable.
5810
		if ( isset( $key ) && ! isset( $value ) ) {
5811
			if ( array_key_exists( $key, $state ) ) {
5812
				return $state[ $key ];
5813
			}
5814
			return null;
5815
		}
5816
5817
		// Set a state variable.
5818
		if ( isset( $key ) && isset( $value ) ) {
5819
			if ( is_array( $value ) && isset( $value[0] ) ) {
5820
				$value = $value[0];
5821
			}
5822
			$state[ $key ] = $value;
5823
			if ( ! headers_sent() ) {
5824
				if ( self::should_set_cookie( $key ) ) {
5825
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5826
				}
5827
			}
5828
		}
5829
	}
5830
5831
	public static function restate() {
5832
		self::state( null, null, true );
5833
	}
5834
5835
	/**
5836
	 * Determines whether the jetpackState[$key] value should be added to the
5837
	 * cookie.
5838
	 *
5839
	 * @param string $key The state key.
5840
	 *
5841
	 * @return boolean Whether the value should be added to the cookie.
5842
	 */
5843
	public static function should_set_cookie( $key ) {
5844
		global $current_screen;
5845
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5846
5847
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5848
			return false;
5849
		}
5850
5851
		return true;
5852
	}
5853
5854
	public static function check_privacy( $file ) {
5855
		static $is_site_publicly_accessible = null;
5856
5857
		if ( is_null( $is_site_publicly_accessible ) ) {
5858
			$is_site_publicly_accessible = false;
5859
5860
			$rpc = new Jetpack_IXR_Client();
5861
5862
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5863
			if ( $success ) {
5864
				$response = $rpc->getResponse();
5865
				if ( $response ) {
5866
					$is_site_publicly_accessible = true;
5867
				}
5868
			}
5869
5870
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5871
		}
5872
5873
		if ( $is_site_publicly_accessible ) {
5874
			return;
5875
		}
5876
5877
		$module_slug = self::get_module_slug( $file );
5878
5879
		$privacy_checks = self::state( 'privacy_checks' );
5880
		if ( ! $privacy_checks ) {
5881
			$privacy_checks = $module_slug;
5882
		} else {
5883
			$privacy_checks .= ",$module_slug";
5884
		}
5885
5886
		self::state( 'privacy_checks', $privacy_checks );
5887
	}
5888
5889
	/**
5890
	 * Helper method for multicall XMLRPC.
5891
	 *
5892
	 * @param ...$args Args for the async_call.
5893
	 */
5894
	public static function xmlrpc_async_call( ...$args ) {
5895
		global $blog_id;
5896
		static $clients = array();
5897
5898
		$client_blog_id = is_multisite() ? $blog_id : 0;
5899
5900
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5901
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5902
			if ( function_exists( 'ignore_user_abort' ) ) {
5903
				ignore_user_abort( true );
5904
			}
5905
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5906
		}
5907
5908
		if ( ! empty( $args[0] ) ) {
5909
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5910
		} elseif ( is_multisite() ) {
5911
			foreach ( $clients as $client_blog_id => $client ) {
5912
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5913
					continue;
5914
				}
5915
5916
				$switch_success = switch_to_blog( $client_blog_id, true );
5917
				if ( ! $switch_success ) {
5918
					continue;
5919
				}
5920
5921
				flush();
5922
				$client->query();
5923
5924
				restore_current_blog();
5925
			}
5926
		} else {
5927
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5928
				flush();
5929
				$clients[0]->query();
5930
			}
5931
		}
5932
	}
5933
5934
	public static function staticize_subdomain( $url ) {
5935
5936
		// Extract hostname from URL
5937
		$host = wp_parse_url( $url, PHP_URL_HOST );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
5938
5939
		// Explode hostname on '.'
5940
		$exploded_host = explode( '.', $host );
5941
5942
		// Retrieve the name and TLD
5943
		if ( count( $exploded_host ) > 1 ) {
5944
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5945
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5946
			// Rebuild domain excluding subdomains
5947
			$domain = $name . '.' . $tld;
5948
		} else {
5949
			$domain = $host;
5950
		}
5951
		// Array of Automattic domains.
5952
		$domains_allowed = array( 'wordpress.com', 'wp.com' );
5953
5954
		// Return $url if not an Automattic domain.
5955
		if ( ! in_array( $domain, $domains_allowed, true ) ) {
5956
			return $url;
5957
		}
5958
5959
		if ( is_ssl() ) {
5960
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5961
		}
5962
5963
		srand( crc32( basename( $url ) ) );
5964
		$static_counter = rand( 0, 2 );
5965
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5966
5967
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5968
	}
5969
5970
	/* JSON API Authorization */
5971
5972
	/**
5973
	 * Handles the login action for Authorizing the JSON API
5974
	 */
5975
	function login_form_json_api_authorization() {
5976
		$this->verify_json_api_authorization_request();
5977
5978
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5979
5980
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5981
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5982
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5983
	}
5984
5985
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5986
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5987
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5988
			return $url;
5989
		}
5990
5991
		$parsed_url = wp_parse_url( $url );
5992
		$url        = strtok( $url, '?' );
5993
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5994
		if ( ! empty( $parsed_url['query'] ) ) {
5995
			$url .= "&{$parsed_url['query']}";
5996
		}
5997
5998
		return $url;
5999
	}
6000
6001
	// Make sure the POSTed request is handled by the same action
6002
	function preserve_action_in_login_form_for_json_api_authorization() {
6003
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6004
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6005
	}
6006
6007
	// If someone logs in to approve API access, store the Access Code in usermeta
6008
	function store_json_api_authorization_token( $user_login, $user ) {
6009
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6010
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6011
		$token = wp_generate_password( 32, false );
6012
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6013
	}
6014
6015
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
6016
	function allow_wpcom_public_api_domain( $domains ) {
6017
		$domains[] = 'public-api.wordpress.com';
6018
		return $domains;
6019
	}
6020
6021
	static function is_redirect_encoded( $redirect_url ) {
6022
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6023
	}
6024
6025
	// Add all wordpress.com environments to the safe redirect allowed list.
6026
	function allow_wpcom_environments( $domains ) {
6027
		$domains[] = 'wordpress.com';
6028
		$domains[] = 'wpcalypso.wordpress.com';
6029
		$domains[] = 'horizon.wordpress.com';
6030
		$domains[] = 'calypso.localhost';
6031
		return $domains;
6032
	}
6033
6034
	// Add the Access Code details to the public-api.wordpress.com redirect
6035
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6036
		return add_query_arg(
6037
			urlencode_deep(
6038
				array(
6039
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6040
					'jetpack-user-id' => (int) $user->ID,
6041
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6042
				)
6043
			),
6044
			$redirect_to
6045
		);
6046
	}
6047
6048
6049
	/**
6050
	 * Verifies the request by checking the signature
6051
	 *
6052
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6053
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6054
	 *
6055
	 * @param null|array $environment
6056
	 */
6057
	function verify_json_api_authorization_request( $environment = null ) {
6058
		$environment = is_null( $environment )
6059
			? $_REQUEST
6060
			: $environment;
6061
6062
		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...
6063
		$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...
6064
		if ( ! $token || empty( $token->secret ) ) {
6065
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6066
		}
6067
6068
		$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' );
6069
6070
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6071
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6072
			/**
6073
			 * Jetpack authorisation request Error.
6074
			 *
6075
			 * @since 7.5.0
6076
			 */
6077
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6078
			$die_error = sprintf(
6079
				/* translators: %s is a URL */
6080
				__( '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' ),
6081
				Redirect::get_url( 'jetpack-support-double-encoding' )
6082
			);
6083
		}
6084
6085
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6086
6087
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6088
			$signature = $jetpack_signature->sign_request(
6089
				$environment['token'],
6090
				$environment['timestamp'],
6091
				$environment['nonce'],
6092
				'',
6093
				'GET',
6094
				$environment['jetpack_json_api_original_query'],
6095
				null,
6096
				true
6097
			);
6098
		} else {
6099
			$signature = $jetpack_signature->sign_current_request(
6100
				array(
6101
					'body'   => null,
6102
					'method' => 'GET',
6103
				)
6104
			);
6105
		}
6106
6107
		if ( ! $signature ) {
6108
			wp_die( $die_error );
6109
		} elseif ( is_wp_error( $signature ) ) {
6110
			wp_die( $die_error );
6111
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6112
			if ( is_ssl() ) {
6113
				// 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
6114
				$signature = $jetpack_signature->sign_current_request(
6115
					array(
6116
						'scheme' => 'http',
6117
						'body'   => null,
6118
						'method' => 'GET',
6119
					)
6120
				);
6121
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6122
					wp_die( $die_error );
6123
				}
6124
			} else {
6125
				wp_die( $die_error );
6126
			}
6127
		}
6128
6129
		$timestamp = (int) $environment['timestamp'];
6130
		$nonce     = stripslashes( (string) $environment['nonce'] );
6131
6132
		if ( ! $this->connection_manager ) {
6133
			$this->connection_manager = new Connection_Manager();
6134
		}
6135
6136
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6137
			// De-nonce the nonce, at least for 5 minutes.
6138
			// 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)
6139
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6140
			if ( $old_nonce_time < time() - 300 ) {
6141
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6142
			}
6143
		}
6144
6145
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6146
		$data_filters = array(
6147
			'state'        => 'opaque',
6148
			'client_id'    => 'int',
6149
			'client_title' => 'string',
6150
			'client_image' => 'url',
6151
		);
6152
6153
		foreach ( $data_filters as $key => $sanitation ) {
6154
			if ( ! isset( $data->$key ) ) {
6155
				wp_die( $die_error );
6156
			}
6157
6158
			switch ( $sanitation ) {
6159
				case 'int':
6160
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6161
					break;
6162
				case 'opaque':
6163
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6164
					break;
6165
				case 'string':
6166
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6167
					break;
6168
				case 'url':
6169
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6170
					break;
6171
			}
6172
		}
6173
6174
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6175
			wp_die( $die_error );
6176
		}
6177
	}
6178
6179
	function login_message_json_api_authorization( $message ) {
6180
		return '<p class="message">' . sprintf(
6181
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6182
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6183
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6184
	}
6185
6186
	/**
6187
	 * Get $content_width, but with a <s>twist</s> filter.
6188
	 */
6189
	public static function get_content_width() {
6190
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6191
			? $GLOBALS['content_width']
6192
			: false;
6193
		/**
6194
		 * Filter the Content Width value.
6195
		 *
6196
		 * @since 2.2.3
6197
		 *
6198
		 * @param string $content_width Content Width value.
6199
		 */
6200
		return apply_filters( 'jetpack_content_width', $content_width );
6201
	}
6202
6203
	/**
6204
	 * Pings the WordPress.com Mirror Site for the specified options.
6205
	 *
6206
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6207
	 *
6208
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6209
	 */
6210
	public function get_cloud_site_options( $option_names ) {
6211
		$option_names = array_filter( (array) $option_names, 'is_string' );
6212
6213
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6214
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6215
		if ( $xml->isError() ) {
6216
			return array(
6217
				'error_code' => $xml->getErrorCode(),
6218
				'error_msg'  => $xml->getErrorMessage(),
6219
			);
6220
		}
6221
		$cloud_site_options = $xml->getResponse();
6222
6223
		return $cloud_site_options;
6224
	}
6225
6226
	/**
6227
	 * Checks if the site is currently in an identity crisis.
6228
	 *
6229
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6230
	 */
6231
	public static function check_identity_crisis() {
6232
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6233
			return false;
6234
		}
6235
6236
		return Jetpack_Options::get_option( 'sync_error_idc' );
6237
	}
6238
6239
	/**
6240
	 * Checks whether the home and siteurl specifically are allowed.
6241
	 * Written so that we don't have re-check $key and $value params every time
6242
	 * we want to check if this site is allowed, for example in footer.php
6243
	 *
6244
	 * @since  3.8.0
6245
	 * @return bool True = already allowed False = not on the allowed list.
6246
	 */
6247
	public static function is_staging_site() {
6248
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6249
		return ( new Status() )->is_staging_site();
6250
	}
6251
6252
	/**
6253
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6254
	 *
6255
	 * @since 4.4.0
6256
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6257
	 *
6258
	 * @return bool
6259
	 */
6260
	public static function validate_sync_error_idc_option() {
6261
		$is_valid = false;
6262
6263
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6264
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6265
		if ( $sync_error && self::sync_idc_optin() ) {
6266
			$local_options = self::get_sync_error_idc_option();
6267
			// Ensure all values are set.
6268
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6269
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6270
					$is_valid = true;
6271
				}
6272
			}
6273
		}
6274
6275
		/**
6276
		 * Filters whether the sync_error_idc option is valid.
6277
		 *
6278
		 * @since 4.4.0
6279
		 *
6280
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6281
		 */
6282
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6283
6284
		if ( ! $is_valid && $sync_error ) {
6285
			// Since the option exists, and did not validate, delete it
6286
			Jetpack_Options::delete_option( 'sync_error_idc' );
6287
		}
6288
6289
		return $is_valid;
6290
	}
6291
6292
	/**
6293
	 * Normalizes a url by doing three things:
6294
	 *  - Strips protocol
6295
	 *  - Strips www
6296
	 *  - Adds a trailing slash
6297
	 *
6298
	 * @since 4.4.0
6299
	 * @param string $url
6300
	 * @return WP_Error|string
6301
	 */
6302
	public static function normalize_url_protocol_agnostic( $url ) {
6303
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6304
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6305
			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...
6306
		}
6307
6308
		// Strip www and protocols
6309
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6310
		return $url;
6311
	}
6312
6313
	/**
6314
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6315
	 *
6316
	 * @since 4.4.0
6317
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6318
	 *
6319
	 * @param array $response
6320
	 * @return array Array of the local urls, wpcom urls, and error code
6321
	 */
6322
	public static function get_sync_error_idc_option( $response = array() ) {
6323
		// Since the local options will hit the database directly, store the values
6324
		// in a transient to allow for autoloading and caching on subsequent views.
6325
		$local_options = get_transient( 'jetpack_idc_local' );
6326
		if ( false === $local_options ) {
6327
			$local_options = array(
6328
				'home'    => Functions::home_url(),
6329
				'siteurl' => Functions::site_url(),
6330
			);
6331
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6332
		}
6333
6334
		$options = array_merge( $local_options, $response );
6335
6336
		$returned_values = array();
6337
		foreach ( $options as $key => $option ) {
6338
			if ( 'error_code' === $key ) {
6339
				$returned_values[ $key ] = $option;
6340
				continue;
6341
			}
6342
6343
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6344
				continue;
6345
			}
6346
6347
			$returned_values[ $key ] = $normalized_url;
6348
		}
6349
6350
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6351
6352
		return $returned_values;
6353
	}
6354
6355
	/**
6356
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6357
	 * If set to true, the site will be put into staging mode.
6358
	 *
6359
	 * @since 4.3.2
6360
	 * @return bool
6361
	 */
6362
	public static function sync_idc_optin() {
6363
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6364
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6365
		} else {
6366
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6367
		}
6368
6369
		/**
6370
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6371
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6372
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6373
		 *
6374
		 * @since 4.3.2
6375
		 *
6376
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6377
		 */
6378
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6379
	}
6380
6381
	/**
6382
	 * Maybe Use a .min.css stylesheet, maybe not.
6383
	 *
6384
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6385
	 */
6386
	public static function maybe_min_asset( $url, $path, $plugin ) {
6387
		// Short out on things trying to find actual paths.
6388
		if ( ! $path || empty( $plugin ) ) {
6389
			return $url;
6390
		}
6391
6392
		$path = ltrim( $path, '/' );
6393
6394
		// Strip out the abspath.
6395
		$base = dirname( plugin_basename( $plugin ) );
6396
6397
		// Short out on non-Jetpack assets.
6398
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6399
			return $url;
6400
		}
6401
6402
		// File name parsing.
6403
		$file              = "{$base}/{$path}";
6404
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6405
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6406
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6407
		$extension         = array_shift( $file_name_parts_r );
6408
6409
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6410
			// Already pointing at the minified version.
6411
			if ( 'min' === $file_name_parts_r[0] ) {
6412
				return $url;
6413
			}
6414
6415
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6416
			if ( file_exists( $min_full_path ) ) {
6417
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6418
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6419
				if ( 'css' === $extension ) {
6420
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6421
					self::$min_assets[ $key ] = $path;
6422
				}
6423
			}
6424
		}
6425
6426
		return $url;
6427
	}
6428
6429
	/**
6430
	 * If the asset is minified, let's flag .min as the suffix.
6431
	 *
6432
	 * Attached to `style_loader_src` filter.
6433
	 *
6434
	 * @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...
6435
	 * @param string $handle The registered handle of the script in question.
6436
	 * @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...
6437
	 */
6438
	public static function set_suffix_on_min( $src, $handle ) {
6439
		if ( false === strpos( $src, '.min.css' ) ) {
6440
			return $src;
6441
		}
6442
6443
		if ( ! empty( self::$min_assets ) ) {
6444
			foreach ( self::$min_assets as $file => $path ) {
6445
				if ( false !== strpos( $src, $file ) ) {
6446
					wp_style_add_data( $handle, 'suffix', '.min' );
6447
					return $src;
6448
				}
6449
			}
6450
		}
6451
6452
		return $src;
6453
	}
6454
6455
	/**
6456
	 * Maybe inlines a stylesheet.
6457
	 *
6458
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6459
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6460
	 *
6461
	 * Attached to `style_loader_tag` filter.
6462
	 *
6463
	 * @param string $tag The tag that would link to the external asset.
6464
	 * @param string $handle The registered handle of the script in question.
6465
	 *
6466
	 * @return string
6467
	 */
6468
	public static function maybe_inline_style( $tag, $handle ) {
6469
		global $wp_styles;
6470
		$item = $wp_styles->registered[ $handle ];
6471
6472
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6473
			return $tag;
6474
		}
6475
6476
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6477
			$href = $matches[1];
6478
			// Strip off query string
6479
			if ( $pos = strpos( $href, '?' ) ) {
6480
				$href = substr( $href, 0, $pos );
6481
			}
6482
			// Strip off fragment
6483
			if ( $pos = strpos( $href, '#' ) ) {
6484
				$href = substr( $href, 0, $pos );
6485
			}
6486
		} else {
6487
			return $tag;
6488
		}
6489
6490
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6491
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6492
			return $tag;
6493
		}
6494
6495
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6496
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6497
			// And this isn't the pass that actually deals with the RTL version...
6498
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6499
				// Short out, as the RTL version will deal with it in a moment.
6500
				return $tag;
6501
			}
6502
		}
6503
6504
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6505
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6506
		if ( $css ) {
6507
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6508
			if ( empty( $item->extra['after'] ) ) {
6509
				wp_add_inline_style( $handle, $css );
6510
			} else {
6511
				array_unshift( $item->extra['after'], $css );
6512
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6513
			}
6514
		}
6515
6516
		return $tag;
6517
	}
6518
6519
	/**
6520
	 * Loads a view file from the views
6521
	 *
6522
	 * Data passed in with the $data parameter will be available in the
6523
	 * template file as $data['value']
6524
	 *
6525
	 * @param string $template - Template file to load
6526
	 * @param array  $data - Any data to pass along to the template
6527
	 * @return boolean - If template file was found
6528
	 **/
6529
	public function load_view( $template, $data = array() ) {
6530
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6531
6532
		if ( file_exists( $views_dir . $template ) ) {
6533
			require_once $views_dir . $template;
6534
			return true;
6535
		}
6536
6537
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6538
		return false;
6539
	}
6540
6541
	/**
6542
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6543
	 */
6544
	public function deprecated_hooks() {
6545
		global $wp_filter;
6546
6547
		/*
6548
		 * Format:
6549
		 * deprecated_filter_name => replacement_name
6550
		 *
6551
		 * If there is no replacement, use null for replacement_name
6552
		 */
6553
		$deprecated_list = array(
6554
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6555
			'wpl_sharing_2014_1'                           => null,
6556
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6557
			'jetpack_identity_crisis_options_to_check'     => null,
6558
			'update_option_jetpack_single_user_site'       => null,
6559
			'audio_player_default_colors'                  => null,
6560
			'add_option_jetpack_featured_images_enabled'   => null,
6561
			'add_option_jetpack_update_details'            => null,
6562
			'add_option_jetpack_updates'                   => null,
6563
			'add_option_jetpack_network_name'              => null,
6564
			'add_option_jetpack_network_allow_new_registrations' => null,
6565
			'add_option_jetpack_network_add_new_users'     => null,
6566
			'add_option_jetpack_network_site_upload_space' => null,
6567
			'add_option_jetpack_network_upload_file_types' => null,
6568
			'add_option_jetpack_network_enable_administration_menus' => null,
6569
			'add_option_jetpack_is_multi_site'             => null,
6570
			'add_option_jetpack_is_main_network'           => null,
6571
			'add_option_jetpack_main_network_site'         => null,
6572
			'jetpack_sync_all_registered_options'          => null,
6573
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6574
			'jetpack_is_post_mailable'                     => null,
6575
			'jetpack_seo_site_host'                        => null,
6576
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6577
			'jetpack_holiday_snow_option_name'             => null,
6578
			'jetpack_holiday_chance_of_snow'               => null,
6579
			'jetpack_holiday_snow_js_url'                  => null,
6580
			'jetpack_is_holiday_snow_season'               => null,
6581
			'jetpack_holiday_snow_option_updated'          => null,
6582
			'jetpack_holiday_snowing'                      => null,
6583
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6584
			'jetpack_cache_plans'                          => null,
6585
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6586
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6587
			'jetpack_enable_site_verification'             => null,
6588
			'can_display_jetpack_manage_notice'            => null,
6589
			// Removed in Jetpack 7.3.0
6590
			'atd_load_scripts'                             => null,
6591
			'atd_http_post_timeout'                        => null,
6592
			'atd_http_post_error'                          => null,
6593
			'atd_service_domain'                           => null,
6594
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6595
			// Removed in Jetpack 7.9.0
6596
			'jetpack_pwa_manifest'                         => null,
6597
			'jetpack_pwa_background_color'                 => null,
6598
			// Removed in Jetpack 8.3.0.
6599
			'jetpack_check_mobile'                         => null,
6600
			'jetpack_mobile_stylesheet'                    => null,
6601
			'jetpack_mobile_template'                      => null,
6602
			'mobile_reject_mobile'                         => null,
6603
			'mobile_force_mobile'                          => null,
6604
			'mobile_app_promo_download'                    => null,
6605
			'mobile_setup'                                 => null,
6606
			'jetpack_mobile_footer_before'                 => null,
6607
			'wp_mobile_theme_footer'                       => null,
6608
			'minileven_credits'                            => null,
6609
			'jetpack_mobile_header_before'                 => null,
6610
			'jetpack_mobile_header_after'                  => null,
6611
			'jetpack_mobile_theme_menu'                    => null,
6612
			'minileven_show_featured_images'               => null,
6613
			'minileven_attachment_size'                    => null,
6614
		);
6615
6616
		// This is a silly loop depth. Better way?
6617
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6618
			if ( has_action( $hook ) ) {
6619
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6620
					foreach ( $values as $hooked ) {
6621
						if ( is_callable( $hooked['function'] ) ) {
6622
							$function_name = $hooked['function'];
6623
						} else {
6624
							$function_name = 'an anonymous function';
6625
						}
6626
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6627
					}
6628
				}
6629
			}
6630
		}
6631
	}
6632
6633
	/**
6634
	 * Converts any url in a stylesheet, to the correct absolute url.
6635
	 *
6636
	 * Considerations:
6637
	 *  - Normal, relative URLs     `feh.png`
6638
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6639
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6640
	 *  - Absolute URLs             `http://domain.com/feh.png`
6641
	 *  - Domain root relative URLs `/feh.png`
6642
	 *
6643
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6644
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6645
	 *
6646
	 * @return mixed|string
6647
	 */
6648
	public static function absolutize_css_urls( $css, $css_file_url ) {
6649
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6650
		$css_dir = dirname( $css_file_url );
6651
		$p       = wp_parse_url( $css_dir );
6652
		$domain  = sprintf(
6653
			'%1$s//%2$s%3$s%4$s',
6654
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6655
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6656
			$p['host'],
6657
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6658
		);
6659
6660
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6661
			$find = $replace = array();
6662
			foreach ( $matches as $match ) {
6663
				$url = trim( $match['path'], "'\" \t" );
6664
6665
				// If this is a data url, we don't want to mess with it.
6666
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6667
					continue;
6668
				}
6669
6670
				// If this is an absolute or protocol-agnostic url,
6671
				// we don't want to mess with it.
6672
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6673
					continue;
6674
				}
6675
6676
				switch ( substr( $url, 0, 1 ) ) {
6677
					case '/':
6678
						$absolute = $domain . $url;
6679
						break;
6680
					default:
6681
						$absolute = $css_dir . '/' . $url;
6682
				}
6683
6684
				$find[]    = $match[0];
6685
				$replace[] = sprintf( 'url("%s")', $absolute );
6686
			}
6687
			$css = str_replace( $find, $replace, $css );
6688
		}
6689
6690
		return $css;
6691
	}
6692
6693
	/**
6694
	 * This methods removes all of the registered css files on the front end
6695
	 * from Jetpack in favor of using a single file. In effect "imploding"
6696
	 * all the files into one file.
6697
	 *
6698
	 * Pros:
6699
	 * - Uses only ONE css asset connection instead of 15
6700
	 * - Saves a minimum of 56k
6701
	 * - Reduces server load
6702
	 * - Reduces time to first painted byte
6703
	 *
6704
	 * Cons:
6705
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6706
	 *      should not cause any issues with themes.
6707
	 * - Plugins/themes dequeuing styles no longer do anything. See
6708
	 *      jetpack_implode_frontend_css filter for a workaround
6709
	 *
6710
	 * For some situations developers may wish to disable css imploding and
6711
	 * instead operate in legacy mode where each file loads seperately and
6712
	 * can be edited individually or dequeued. This can be accomplished with
6713
	 * the following line:
6714
	 *
6715
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6716
	 *
6717
	 * @since 3.2
6718
	 **/
6719
	public function implode_frontend_css( $travis_test = false ) {
6720
		$do_implode = true;
6721
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6722
			$do_implode = false;
6723
		}
6724
6725
		// Do not implode CSS when the page loads via the AMP plugin.
6726
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6727
			$do_implode = false;
6728
		}
6729
6730
		/**
6731
		 * Allow CSS to be concatenated into a single jetpack.css file.
6732
		 *
6733
		 * @since 3.2.0
6734
		 *
6735
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6736
		 */
6737
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6738
6739
		// Do not use the imploded file when default behavior was altered through the filter
6740
		if ( ! $do_implode ) {
6741
			return;
6742
		}
6743
6744
		// We do not want to use the imploded file in dev mode, or if not connected
6745
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6746
			if ( ! $travis_test ) {
6747
				return;
6748
			}
6749
		}
6750
6751
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6752
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6753
			return;
6754
		}
6755
6756
		/*
6757
		 * Now we assume Jetpack is connected and able to serve the single
6758
		 * file.
6759
		 *
6760
		 * In the future there will be a check here to serve the file locally
6761
		 * or potentially from the Jetpack CDN
6762
		 *
6763
		 * For now:
6764
		 * - Enqueue a single imploded css file
6765
		 * - Zero out the style_loader_tag for the bundled ones
6766
		 * - Be happy, drink scotch
6767
		 */
6768
6769
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6770
6771
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6772
6773
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6774
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6775
	}
6776
6777
	function concat_remove_style_loader_tag( $tag, $handle ) {
6778
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6779
			$tag = '';
6780
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6781
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6782
			}
6783
		}
6784
6785
		return $tag;
6786
	}
6787
6788
	/**
6789
	 * @deprecated
6790
	 * @see Automattic\Jetpack\Assets\add_aync_script
6791
	 */
6792
	public function script_add_async( $tag, $handle, $src ) {
6793
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6794
	}
6795
6796
	/*
6797
	 * Check the heartbeat data
6798
	 *
6799
	 * Organizes the heartbeat data by severity.  For example, if the site
6800
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6801
	 *
6802
	 * Data will be added to "caution" array, if it either:
6803
	 *  - Out of date Jetpack version
6804
	 *  - Out of date WP version
6805
	 *  - Out of date PHP version
6806
	 *
6807
	 * $return array $filtered_data
6808
	 */
6809
	public static function jetpack_check_heartbeat_data() {
6810
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6811
6812
		$good    = array();
6813
		$caution = array();
6814
		$bad     = array();
6815
6816
		foreach ( $raw_data as $stat => $value ) {
6817
6818
			// Check jetpack version
6819
			if ( 'version' == $stat ) {
6820
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6821
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6822
					continue;
6823
				}
6824
			}
6825
6826
			// Check WP version
6827
			if ( 'wp-version' == $stat ) {
6828
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6829
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6830
					continue;
6831
				}
6832
			}
6833
6834
			// Check PHP version
6835
			if ( 'php-version' == $stat ) {
6836
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6837
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6838
					continue;
6839
				}
6840
			}
6841
6842
			// Check ID crisis
6843
			if ( 'identitycrisis' == $stat ) {
6844
				if ( 'yes' == $value ) {
6845
					$bad[ $stat ] = $value;
6846
					continue;
6847
				}
6848
			}
6849
6850
			// The rest are good :)
6851
			$good[ $stat ] = $value;
6852
		}
6853
6854
		$filtered_data = array(
6855
			'good'    => $good,
6856
			'caution' => $caution,
6857
			'bad'     => $bad,
6858
		);
6859
6860
		return $filtered_data;
6861
	}
6862
6863
6864
	/*
6865
	 * This method is used to organize all options that can be reset
6866
	 * without disconnecting Jetpack.
6867
	 *
6868
	 * It is used in class.jetpack-cli.php to reset options
6869
	 *
6870
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6871
	 *
6872
	 * @return array of options to delete.
6873
	 */
6874
	public static function get_jetpack_options_for_reset() {
6875
		return Jetpack_Options::get_options_for_reset();
6876
	}
6877
6878
	/*
6879
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6880
	 * so we can bring them directly to their site in calypso.
6881
	 *
6882
	 * @param string | url
6883
	 * @return string | url without the guff
6884
	 */
6885 View Code Duplication
	public static function build_raw_urls( $url ) {
6886
		$strip_http = '/.*?:\/\//i';
6887
		$url        = preg_replace( $strip_http, '', $url );
6888
		$url        = str_replace( '/', '::', $url );
6889
		return $url;
6890
	}
6891
6892
	/**
6893
	 * Stores and prints out domains to prefetch for page speed optimization.
6894
	 *
6895
	 * @param mixed $new_urls
6896
	 */
6897
	public static function dns_prefetch( $new_urls = null ) {
6898
		static $prefetch_urls = array();
6899
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6900
			echo "\r\n";
6901
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6902
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6903
			}
6904
		} elseif ( ! empty( $new_urls ) ) {
6905
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6906
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6907
			}
6908
			foreach ( (array) $new_urls as $this_new_url ) {
6909
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6910
			}
6911
			$prefetch_urls = array_unique( $prefetch_urls );
6912
		}
6913
	}
6914
6915
	public function wp_dashboard_setup() {
6916
		if ( self::is_active() ) {
6917
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6918
		}
6919
6920
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6921
			$jetpack_logo = new Jetpack_Logo();
6922
			$widget_title = sprintf(
6923
				wp_kses(
6924
					/* translators: Placeholder is a Jetpack logo. */
6925
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6926
					array( 'span' => array() )
6927
				),
6928
				$jetpack_logo->get_jp_emblem( true )
6929
			);
6930
6931
			wp_add_dashboard_widget(
6932
				'jetpack_summary_widget',
6933
				$widget_title,
6934
				array( __CLASS__, 'dashboard_widget' )
6935
			);
6936
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6937
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6938
6939
			// If we're inactive and not in development mode, sort our box to the top.
6940
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6941
				global $wp_meta_boxes;
6942
6943
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6944
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6945
6946
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6947
			}
6948
		}
6949
	}
6950
6951
	/**
6952
	 * @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...
6953
	 * @return mixed
6954
	 */
6955
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6956
		if ( ! is_array( $sorted ) ) {
6957
			return $sorted;
6958
		}
6959
6960
		foreach ( $sorted as $box_context => $ids ) {
6961
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6962
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6963
				continue;
6964
			}
6965
6966
			$ids_array = explode( ',', $ids );
6967
			$key       = array_search( 'dashboard_stats', $ids_array );
6968
6969
			if ( false !== $key ) {
6970
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6971
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6972
				$sorted[ $box_context ] = implode( ',', $ids_array );
6973
				// We've found it, stop searching, and just return.
6974
				break;
6975
			}
6976
		}
6977
6978
		return $sorted;
6979
	}
6980
6981
	public static function dashboard_widget() {
6982
		/**
6983
		 * Fires when the dashboard is loaded.
6984
		 *
6985
		 * @since 3.4.0
6986
		 */
6987
		do_action( 'jetpack_dashboard_widget' );
6988
	}
6989
6990
	public static function dashboard_widget_footer() {
6991
		?>
6992
		<footer>
6993
6994
		<div class="protect">
6995
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6996
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6997
				<p class="blocked-count">
6998
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6999
				</p>
7000
				<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>
7001
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
7002
				<a href="
7003
				<?php
7004
				echo esc_url(
7005
					wp_nonce_url(
7006
						self::admin_url(
7007
							array(
7008
								'action' => 'activate',
7009
								'module' => 'protect',
7010
							)
7011
						),
7012
						'jetpack_activate-protect'
7013
					)
7014
				);
7015
				?>
7016
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7017
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7018
				</a>
7019
			<?php else : ?>
7020
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7021
			<?php endif; ?>
7022
		</div>
7023
7024
		<div class="akismet">
7025
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7026
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7027
				<p class="blocked-count">
7028
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7029
				</p>
7030
				<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>
7031
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7032
				<a href="
7033
				<?php
7034
				echo esc_url(
7035
					wp_nonce_url(
7036
						add_query_arg(
7037
							array(
7038
								'action' => 'activate',
7039
								'plugin' => 'akismet/akismet.php',
7040
							),
7041
							admin_url( 'plugins.php' )
7042
						),
7043
						'activate-plugin_akismet/akismet.php'
7044
					)
7045
				);
7046
				?>
7047
							" class="button button-jetpack">
7048
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7049
				</a>
7050
			<?php else : ?>
7051
				<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>
7052
			<?php endif; ?>
7053
		</div>
7054
7055
		</footer>
7056
		<?php
7057
	}
7058
7059
	/*
7060
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7061
	 */
7062
	function jetpack_icon_user_connected( $columns ) {
7063
		$columns['user_jetpack'] = '';
7064
		return $columns;
7065
	}
7066
7067
	/*
7068
	 * Show Jetpack icon if the user is linked.
7069
	 */
7070
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7071
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7072
			$jetpack_logo = new Jetpack_Logo();
7073
			$emblem_html  = sprintf(
7074
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7075
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7076
				$jetpack_logo->get_jp_emblem()
7077
			);
7078
			return $emblem_html;
7079
		}
7080
7081
		return $val;
7082
	}
7083
7084
	/*
7085
	 * Style the Jetpack user column
7086
	 */
7087
	function jetpack_user_col_style() {
7088
		global $current_screen;
7089
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7090
			?>
7091
			<style>
7092
				.fixed .column-user_jetpack {
7093
					width: 21px;
7094
				}
7095
				.jp-emblem-user-admin svg {
7096
					width: 20px;
7097
					height: 20px;
7098
				}
7099
				.jp-emblem-user-admin path {
7100
					fill: #00BE28;
7101
				}
7102
			</style>
7103
			<?php
7104
		}
7105
	}
7106
7107
	/**
7108
	 * Checks if Akismet is active and working.
7109
	 *
7110
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7111
	 * that implied usage of methods present since more recent version.
7112
	 * See https://github.com/Automattic/jetpack/pull/9585
7113
	 *
7114
	 * @since  5.1.0
7115
	 *
7116
	 * @return bool True = Akismet available. False = Aksimet not available.
7117
	 */
7118
	public static function is_akismet_active() {
7119
		static $status = null;
7120
7121
		if ( ! is_null( $status ) ) {
7122
			return $status;
7123
		}
7124
7125
		// Check if a modern version of Akismet is active.
7126
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7127
			$status = false;
7128
			return $status;
7129
		}
7130
7131
		// Make sure there is a key known to Akismet at all before verifying key.
7132
		$akismet_key = Akismet::get_api_key();
7133
		if ( ! $akismet_key ) {
7134
			$status = false;
7135
			return $status;
7136
		}
7137
7138
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7139
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7140
7141
		// 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.
7142
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7143
		// We cache the result of the Akismet key verification for ten minutes.
7144
		if ( ! $akismet_key_state || $recheck ) {
7145
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7146
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7147
		}
7148
7149
		$status = 'valid' === $akismet_key_state;
7150
7151
		return $status;
7152
	}
7153
7154
	/**
7155
	 * @deprecated
7156
	 *
7157
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7158
	 */
7159
	public static function is_function_in_backtrace() {
7160
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7161
	}
7162
7163
	/**
7164
	 * Given a minified path, and a non-minified path, will return
7165
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7166
	 *
7167
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7168
	 * root Jetpack directory.
7169
	 *
7170
	 * @since 5.6.0
7171
	 *
7172
	 * @param string $min_path
7173
	 * @param string $non_min_path
7174
	 * @return string The URL to the file
7175
	 */
7176
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7177
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7178
	}
7179
7180
	/**
7181
	 * Checks for whether Jetpack Backup is enabled.
7182
	 * Will return true if the state of Backup is anything except "unavailable".
7183
	 *
7184
	 * @return bool|int|mixed
7185
	 */
7186
	public static function is_rewind_enabled() {
7187
		if ( ! self::is_active() ) {
7188
			return false;
7189
		}
7190
7191
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7192
		if ( false === $rewind_enabled ) {
7193
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7194
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7195
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7196
				&& ! empty( $rewind_data['state'] )
7197
				&& 'active' === $rewind_data['state'] )
7198
				? 1
7199
				: 0;
7200
7201
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7202
		}
7203
		return $rewind_enabled;
7204
	}
7205
7206
	/**
7207
	 * Return Calypso environment value; used for developing Jetpack and pairing
7208
	 * it with different Calypso enrionments, such as localhost.
7209
	 *
7210
	 * @since 7.4.0
7211
	 *
7212
	 * @return string Calypso environment
7213
	 */
7214
	public static function get_calypso_env() {
7215
		if ( isset( $_GET['calypso_env'] ) ) {
7216
			return sanitize_key( $_GET['calypso_env'] );
7217
		}
7218
7219
		if ( getenv( 'CALYPSO_ENV' ) ) {
7220
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7221
		}
7222
7223
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7224
			return sanitize_key( CALYPSO_ENV );
7225
		}
7226
7227
		return '';
7228
	}
7229
7230
	/**
7231
	 * Returns the hostname with protocol for Calypso.
7232
	 * Used for developing Jetpack with Calypso.
7233
	 *
7234
	 * @since 8.4.0
7235
	 *
7236
	 * @return string Calypso host.
7237
	 */
7238
	public static function get_calypso_host() {
7239
		$calypso_env = self::get_calypso_env();
7240
		switch ( $calypso_env ) {
7241
			case 'development':
7242
				return 'http://calypso.localhost:3000/';
7243
			case 'wpcalypso':
7244
				return 'https://wpcalypso.wordpress.com/';
7245
			case 'horizon':
7246
				return 'https://horizon.wordpress.com/';
7247
			default:
7248
				return 'https://wordpress.com/';
7249
		}
7250
	}
7251
7252
	/**
7253
	 * Checks whether or not TOS has been agreed upon.
7254
	 * Will return true if a user has clicked to register, or is already connected.
7255
	 */
7256
	public static function jetpack_tos_agreed() {
7257
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7258
7259
		$terms_of_service = new Terms_Of_Service();
7260
		return $terms_of_service->has_agreed();
7261
7262
	}
7263
7264
	/**
7265
	 * Handles activating default modules as well general cleanup for the new connection.
7266
	 *
7267
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7268
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7269
	 * @param boolean $send_state_messages          Whether to send state messages.
7270
	 * @return void
7271
	 */
7272
	public static function handle_post_authorization_actions(
7273
		$activate_sso = false,
7274
		$redirect_on_activation_error = false,
7275
		$send_state_messages = true
7276
	) {
7277
		$other_modules = $activate_sso
7278
			? array( 'sso' )
7279
			: array();
7280
7281
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7282
			self::delete_active_modules();
7283
7284
			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...
7285
		} else {
7286
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7287
		}
7288
7289
		// Since this is a fresh connection, be sure to clear out IDC options
7290
		Jetpack_IDC::clear_all_idc_options();
7291
7292
		if ( $send_state_messages ) {
7293
			self::state( 'message', 'authorized' );
7294
		}
7295
	}
7296
7297
	/**
7298
	 * Returns a boolean for whether backups UI should be displayed or not.
7299
	 *
7300
	 * @return bool Should backups UI be displayed?
7301
	 */
7302
	public static function show_backups_ui() {
7303
		/**
7304
		 * Whether UI for backups should be displayed.
7305
		 *
7306
		 * @since 6.5.0
7307
		 *
7308
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7309
		 */
7310
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7311
	}
7312
7313
	/*
7314
	 * Deprecated manage functions
7315
	 */
7316
	function prepare_manage_jetpack_notice() {
7317
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7318
	}
7319
	function manage_activate_screen() {
7320
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7321
	}
7322
	function admin_jetpack_manage_notice() {
7323
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7324
	}
7325
	function opt_out_jetpack_manage_url() {
7326
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7327
	}
7328
	function opt_in_jetpack_manage_url() {
7329
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7330
	}
7331
	function opt_in_jetpack_manage_notice() {
7332
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7333
	}
7334
	function can_display_jetpack_manage_notice() {
7335
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7336
	}
7337
7338
	/**
7339
	 * Clean leftoveruser meta.
7340
	 *
7341
	 * Delete Jetpack-related user meta when it is no longer needed.
7342
	 *
7343
	 * @since 7.3.0
7344
	 *
7345
	 * @param int $user_id User ID being updated.
7346
	 */
7347
	public static function user_meta_cleanup( $user_id ) {
7348
		$meta_keys = array(
7349
			// AtD removed from Jetpack 7.3
7350
			'AtD_options',
7351
			'AtD_check_when',
7352
			'AtD_guess_lang',
7353
			'AtD_ignored_phrases',
7354
		);
7355
7356
		foreach ( $meta_keys as $meta_key ) {
7357
			if ( get_user_meta( $user_id, $meta_key ) ) {
7358
				delete_user_meta( $user_id, $meta_key );
7359
			}
7360
		}
7361
	}
7362
7363
	/**
7364
	 * Checks if a Jetpack site is both active and not in development.
7365
	 *
7366
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7367
	 *
7368
	 * @return bool True if Jetpack is active and not in development.
7369
	 */
7370
	public static function is_active_and_not_development_mode() {
7371
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7372
			return false;
7373
		}
7374
		return true;
7375
	}
7376
7377
	/**
7378
	 * Returns the list of products that we have available for purchase.
7379
	 */
7380
	public static function get_products_for_purchase() {
7381
		$products = array();
7382
		if ( ! is_multisite() ) {
7383
			$products[] = array(
7384
				'key'               => 'backup',
7385
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7386
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7387
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7388
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7389
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7390
				'options'           => array(
7391
					array(
7392
						'type'        => 'daily',
7393
						'slug'        => 'jetpack-backup-daily',
7394
						'key'         => 'jetpack_backup_daily',
7395
						'name'        => __( 'Daily Backups', 'jetpack' ),
7396
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7397
					),
7398
					array(
7399
						'type'        => 'realtime',
7400
						'slug'        => 'jetpack-backup-realtime',
7401
						'key'         => 'jetpack_backup_realtime',
7402
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7403
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7404
					),
7405
				),
7406
				'default_option'    => 'realtime',
7407
				'show_promotion'    => true,
7408
				'discount_percent'  => 70,
7409
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7410
			);
7411
7412
			$products[] = array(
7413
				'key'               => 'scan',
7414
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7415
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7416
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7417
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7418
				'show_promotion'    => true,
7419
				'discount_percent'  => 30,
7420
				'options'           => array(
7421
					array(
7422
						'type'      => 'scan',
7423
						'slug'      => 'jetpack-scan',
7424
						'key'       => 'jetpack_scan',
7425
						'name'      => __( 'Daily Scan', 'jetpack' ),
7426
					),
7427
				),
7428
				'default_option'    => 'scan',
7429
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7430
			);
7431
		}
7432
7433
		$products[] = array(
7434
			'key'               => 'search',
7435
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7436
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7437
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7438
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7439
			'label_popup'  		=> __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.' ),
7440
			'options'           => array(
7441
				array(
7442
					'type'      => 'search',
7443
					'slug'      => 'jetpack-search',
7444
					'key'       => 'jetpack_search',
7445
					'name'      => __( 'Search', 'jetpack' ),
7446
				),
7447
			),
7448
			'tears'             => array(),
7449
			'default_option'    => 'search',
7450
			'show_promotion'    => false,
7451
			'included_in_plans' => array( 'search-plan' ),
7452
		);
7453
7454
		return $products;
7455
	}
7456
}
7457