Completed
Push — update/map-block-zoom-controls ( eee244...961242 )
by
unknown
18:08 queued 10:21
created

Jetpack   F

Complexity

Total Complexity 1017

Size/Duplication

Total Lines 7133
Duplicated Lines 4.15 %

Coupling/Cohesion

Components 4
Dependencies 36

Importance

Changes 0
Metric Value
dl 296
loc 7133
rs 0.8
c 0
b 0
f 0
wmc 1017
lcom 4
cbo 36

260 Methods

Rating   Name   Duplication   Size   Complexity  
B get_default_modules() 0 31 6
B do_stats() 0 15 7
A build_stats_url() 0 20 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 xmlrpc_api_url() 0 4 1
A get_user_option_meta_box_order_dashboard() 0 25 5
A dashboard_widget() 0 8 1
B filter_default_modules() 0 24 6
A get_module_slug() 0 3 1
A staticize_subdomain() 0 35 4
A login_form_json_api_authorization() 0 9 1
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
B jetpack_check_heartbeat_data() 0 53 10
A get_jetpack_options_for_reset() 0 3 1
A build_raw_urls() 0 6 1
B dns_prefetch() 0 17 7
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
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 do_version_bump() 0 5 2
C get_activation_source() 0 49 14
A admin_help() 0 41 2
A admin_menu_css() 0 3 1
A admin_menu_order() 0 3 1
A jetpack_menu_order() 15 15 4
A plugin_action_links() 0 15 4
A xmlrpc_methods() 0 4 1
A jetpack_icon_user_connected() 0 4 1
A jetpack_show_user_connected_icon() 0 13 3
A normalize_url_protocol_agnostic() 0 10 4
A get_sync_error_idc_option() 0 32 5
A jetpack_main_network_site_option() 0 3 1
A network_name() 0 4 1
A network_max_upload_file_size() 0 4 1
A network_upload_file_types() 0 3 1
B glob_php() 0 29 7
C activate_new_modules() 6 58 11
A network_site_upload_space() 0 4 2
A is_onboarding() 0 3 1
A development_mode_trigger_text() 0 16 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 plugin_textdomain() 0 4 1
A update_jetpack_main_network_site_option() 0 3 1
A file_system_write_access() 0 20 4
A current_user_ip() 0 20 5
A get_module_path() 0 11 1
A push_stats() 0 5 2
A is_main_network_option() 0 4 1
A is_multisite() 0 3 1
A update_jetpack_network_settings() 0 4 1
A featured_images_enabled() 0 4 2
A check_identity_crisis() 0 7 4
C guess_locale_from_lang() 39 39 12
A get_locale() 0 9 2
A is_version_controlled() 0 4 1
A user_role_change() 0 4 1
A login_message_json_api_authorization() 0 6 1
A get_content_width() 0 13 3
A handle_post_authorization_actions() 0 29 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 get_file_url_for_environment() 0 3 1
A network_add_new_users() 0 3 1
A show_development_mode_notice() 11 28 4
A is_development_version() 0 15 1
A is_user_connected() 0 3 1
A admin_body_class() 0 8 2
A add_jetpack_pagestyles() 0 3 1
B add_remote_request_handlers() 0 25 6
B remote_request_handlers() 0 40 7
F upload_handler() 0 131 24
F admin_page_load() 32 277 55
B admin_notices() 0 125 7
A track_xmlrpc_error() 0 15 4
A stat() 0 6 2
A do_server_side_stat() 0 12 3
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
A jetpack_user_col_style() 0 19 3
B is_akismet_active() 0 35 9
A is_function_in_backtrace() 0 3 1
A is_rewind_enabled() 0 19 6
A get_calypso_env() 0 15 5
A jetpack_tos_agreed() 0 7 1
A is_active_and_not_development_mode() 0 6 3
A init() 0 8 2
C plugin_upgrade() 0 57 12
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 26 4
B __construct() 0 123 4
C configure() 0 72 10
A late_initialization() 0 18 1
A setup_xmlrpc_handlers() 0 14 1
A initialize_rest_api_registration_connector() 0 4 1
A add_wpcom_to_allowed_redirect_hosts() 0 3 1
A allow_wpcom_domain() 0 7 2
A point_edit_post_links_to_calypso() 0 28 3
A point_edit_comment_links_to_calypso() 0 11 1
A jetpack_track_last_sync_callback() 0 22 5
A jetpack_connection_banner_callback() 0 10 2
A remove_non_jetpack_xmlrpc_methods() 0 4 1
A alternate_xmlrpc() 0 4 1
A jetpack_jitm_ajax_callback() 0 3 1
D jetpack_custom_caps() 0 73 21
A require_jetpack_authentication() 0 4 1
B register_assets() 27 80 8
A network_allow_new_registrations() 0 3 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 is_multi_network() 15 15 3
A is_single_user_site() 9 9 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 get_connected_user_data() 26 26 4
A get_connected_user_email() 14 16 3
A get_master_user_email() 0 7 2
A current_user_is_connection_owner() 0 4 1
A extra_oembed_providers() 0 10 1
D load_modules() 6 88 17
A check_rest_api_compat() 0 18 3
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
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
F activate_default_modules() 21 166 36
D activate_module() 0 93 17
A plugin_activation() 0 20 3
A plugin_initialize() 6 17 3
A plugin_deactivation() 0 9 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 45 11
A admin_banner_styles() 8 21 4
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 3 1
A generate_secrets() 0 3 1
A get_secrets() 0 13 3
A delete_secrets() 0 3 1
A get_remote_query_timeout_limit() 0 4 1
A get_max_execution_time() 0 9 2
A set_min_time_limit() 8 8 2
A validate_remote_register_response() 0 3 1
A register() 0 17 3
A filter_register_request_body() 12 12 1
A filter_token_request_body() 12 12 1
A maybe_set_version_option() 0 14 3
A load_xml_rpc_client() 0 3 1
A reset_saved_auth_state() 0 4 1
A verify_xml_rpc_signature() 0 4 1
A internal_verify_xml_rpc_signature() 0 3 1
A authenticate_jetpack() 0 4 1
C wp_rest_authenticate() 0 70 15
A wp_rest_authentication_errors() 0 6 2
A add_nonce() 0 4 1
A public_xmlrpc_methods() 0 4 1
A jetpack_getOptions() 0 4 1
A xmlrpc_options() 0 4 1
A clean_nonces() 0 4 1
D state() 0 54 19
A restate() 0 3 1
B check_privacy() 0 34 6
C xmlrpc_async_call() 0 39 12
A post_login_form_to_signed_url() 0 14 5
F verify_json_api_authorization_request() 0 117 22
A get_cloud_site_options() 0 15 2
A is_staging_site() 0 4 1
C validate_sync_error_idc_option() 0 48 17
B deprecated_hooks() 0 88 6
A script_add_async() 0 7 2
A wp_dashboard_setup() 0 35 5
B dashboard_widget_footer() 0 68 7

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\Constants;
9
use Automattic\Jetpack\Partner;
10
use Automattic\Jetpack\Roles;
11
use Automattic\Jetpack\Status;
12
use Automattic\Jetpack\Sync\Functions;
13
use Automattic\Jetpack\Sync\Health;
14
use Automattic\Jetpack\Sync\Sender;
15
use Automattic\Jetpack\Sync\Users;
16
use Automattic\Jetpack\Terms_Of_Service;
17
use Automattic\Jetpack\Tracking;
18
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
19
20
/*
21
Options:
22
jetpack_options (array)
23
	An array of options.
24
	@see Jetpack_Options::get_option_names()
25
26
jetpack_register (string)
27
	Temporary verification secrets.
28
29
jetpack_activated (int)
30
	1: the plugin was activated normally
31
	2: the plugin was activated on this site because of a network-wide activation
32
	3: the plugin was auto-installed
33
	4: the plugin was manually disconnected (but is still installed)
34
35
jetpack_active_modules (array)
36
	Array of active module slugs.
37
38
jetpack_do_activate (bool)
39
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
40
*/
41
42
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
43
44
class Jetpack {
45
	public $xmlrpc_server = null;
46
47
	private $rest_authentication_status = null;
48
49
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
50
51
	/**
52
	 * @var array The handles of styles that are concatenated into jetpack.css.
53
	 *
54
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
55
	 */
56
	public $concatenated_style_handles = array(
57
		'jetpack-carousel',
58
		'grunion.css',
59
		'the-neverending-homepage',
60
		'jetpack_likes',
61
		'jetpack_related-posts',
62
		'sharedaddy',
63
		'jetpack-slideshow',
64
		'presentations',
65
		'quiz',
66
		'jetpack-subscriptions',
67
		'jetpack-responsive-videos-style',
68
		'jetpack-social-menu',
69
		'tiled-gallery',
70
		'jetpack_display_posts_widget',
71
		'gravatar-profile-widget',
72
		'goodreads-widget',
73
		'jetpack_social_media_icons_widget',
74
		'jetpack-top-posts-widget',
75
		'jetpack_image_widget',
76
		'jetpack-my-community-widget',
77
		'jetpack-authors-widget',
78
		'wordads',
79
		'eu-cookie-law-style',
80
		'flickr-widget-style',
81
		'jetpack-search-widget',
82
		'jetpack-simple-payments-widget-style',
83
		'jetpack-widget-social-icons-styles',
84
	);
85
86
	/**
87
	 * The handles of scripts that can be loaded asynchronously.
88
	 *
89
	 * @var array
90
	 */
91
	public $async_script_handles = array(
92
		'woocommerce-analytics',
93
	);
94
95
	/**
96
	 * Contains all assets that have had their URL rewritten to minified versions.
97
	 *
98
	 * @var array
99
	 */
100
	static $min_assets = array();
101
102
	public $plugins_to_deactivate = array(
103
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
104
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
105
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
106
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
107
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
108
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
109
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
110
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
111
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
112
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
113
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
114
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
115
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
116
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
117
	);
118
119
	/**
120
	 * Map of roles we care about, and their corresponding minimum capabilities.
121
	 *
122
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
123
	 *
124
	 * @access public
125
	 * @static
126
	 *
127
	 * @var array
128
	 */
129
	public static $capability_translations = array(
130
		'administrator' => 'manage_options',
131
		'editor'        => 'edit_others_posts',
132
		'author'        => 'publish_posts',
133
		'contributor'   => 'edit_posts',
134
		'subscriber'    => 'read',
135
	);
136
137
	/**
138
	 * Map of modules that have conflicts with plugins and should not be auto-activated
139
	 * if the plugins are active.  Used by filter_default_modules
140
	 *
141
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
142
	 * change `module-slug` and add this to your plugin:
143
	 *
144
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
145
	 * function my_jetpack_get_default_modules( $modules ) {
146
	 *     return array_diff( $modules, array( 'module-slug' ) );
147
	 * }
148
	 *
149
	 * @var array
150
	 */
151
	private $conflicting_plugins = array(
152
		'comments'           => array(
153
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
154
			'Disqus'                         => 'disqus-comment-system/disqus.php',
155
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
156
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
157
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
158
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
159
		),
160
		'comment-likes'      => array(
161
			'Epoch' => 'epoch/plugincore.php',
162
		),
163
		'contact-form'       => array(
164
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
165
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
166
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
167
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
168
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
169
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
170
		),
171
		'latex'              => array(
172
			'LaTeX for WordPress'     => 'latex/latex.php',
173
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
174
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
175
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
176
			'Enable Latex'            => 'enable-latex/enable-latex.php',
177
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
178
		),
179
		'protect'            => array(
180
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
181
			'Captcha'                           => 'captcha/captcha.php',
182
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
183
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
184
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
185
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
186
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
187
			'Security-protection'               => 'security-protection/security-protection.php',
188
			'Login Security'                    => 'login-security/login-security.php',
189
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
190
			'Wordfence Security'                => 'wordfence/wordfence.php',
191
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
192
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
193
		),
194
		'random-redirect'    => array(
195
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
196
		),
197
		'related-posts'      => array(
198
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
199
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
200
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
201
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
202
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
203
			'outbrain'                    => 'outbrain/outbrain.php',
204
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
205
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
206
		),
207
		'sharedaddy'         => array(
208
			'AddThis'     => 'addthis/addthis_social_widget.php',
209
			'Add To Any'  => 'add-to-any/add-to-any.php',
210
			'ShareThis'   => 'share-this/sharethis.php',
211
			'Shareaholic' => 'shareaholic/shareaholic.php',
212
		),
213
		'seo-tools'          => array(
214
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
215
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
216
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
217
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
218
			'The SEO Framework'              => 'autodescription/autodescription.php',
219
		),
220
		'verification-tools' => array(
221
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
222
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
223
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
224
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
225
			'The SEO Framework'              => 'autodescription/autodescription.php',
226
		),
227
		'widget-visibility'  => array(
228
			'Widget Logic'    => 'widget-logic/widget_logic.php',
229
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
230
		),
231
		'sitemaps'           => array(
232
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
233
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
234
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
235
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
236
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
237
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
238
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
239
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
240
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
241
			'The SEO Framework'                    => 'autodescription/autodescription.php',
242
			'Sitemap'                              => 'sitemap/sitemap.php',
243
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
244
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
245
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
246
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
247
		),
248
		'lazy-images'        => array(
249
			'Lazy Load'              => 'lazy-load/lazy-load.php',
250
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
251
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
252
		),
253
	);
254
255
	/**
256
	 * Plugins for which we turn off our Facebook OG Tags implementation.
257
	 *
258
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
259
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
260
	 *
261
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
262
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
263
	 */
264
	private $open_graph_conflicting_plugins = array(
265
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
266
		// 2 Click Social Media Buttons
267
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
268
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
269
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
270
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
271
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
272
		// Open Graph Meta Tags by Heateor
273
		'facebook/facebook.php',                                 // Facebook (official plugin)
274
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
275
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
276
		// Facebook Featured Image & OG Meta Tags
277
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
278
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
279
		// Facebook Open Graph Meta Tags for WordPress
280
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
281
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
282
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
283
		// Fedmich's Facebook Open Graph Meta
284
		'network-publisher/networkpub.php',                      // Network Publisher
285
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
286
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
287
		// NextScripts SNAP
288
		'og-tags/og-tags.php',                                   // OG Tags
289
		'opengraph/opengraph.php',                               // Open Graph
290
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
291
		// Open Graph Protocol Framework
292
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
293
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
294
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
295
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
296
		'sharepress/sharepress.php',                             // SharePress
297
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
298
		'social-discussions/social-discussions.php',             // Social Discussions
299
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
300
		'socialize/socialize.php',                               // Socialize
301
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
302
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
303
		// Tweet, Like, Google +1 and Share
304
		'wordbooker/wordbooker.php',                             // Wordbooker
305
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
306
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
307
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
308
		// WP Facebook Like Send & Open Graph Meta
309
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
310
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
311
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
312
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
313
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
314
	);
315
316
	/**
317
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
318
	 */
319
	private $twitter_cards_conflicting_plugins = array(
320
		// 'twitter/twitter.php',                       // The official one handles this on its own.
321
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
322
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
323
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
324
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
325
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
326
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
327
		'twitter-cards/twitter-cards.php',           // Twitter Cards
328
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
329
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
330
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
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
	 * Holds the singleton instance of this class
383
	 *
384
	 * @since 2.3.3
385
	 * @var Jetpack
386
	 */
387
	static $instance = false;
388
389
	/**
390
	 * Singleton
391
	 *
392
	 * @static
393
	 */
394
	public static function init() {
395
		if ( ! self::$instance ) {
396
			self::$instance = new Jetpack();
397
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
398
		}
399
400
		return self::$instance;
401
	}
402
403
	/**
404
	 * Must never be called statically
405
	 */
406
	function plugin_upgrade() {
407
		if ( self::is_active() ) {
408
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
409
			if ( JETPACK__VERSION != $version ) {
410
				// Prevent multiple upgrades at once - only a single process should trigger
411
				// an upgrade to avoid stampedes
412
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
413
					return;
414
				}
415
416
				// Set a short lock to prevent multiple instances of the upgrade
417
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
418
419
				// check which active modules actually exist and remove others from active_modules list
420
				$unfiltered_modules = self::get_active_modules();
421
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
422
				if ( array_diff( $unfiltered_modules, $modules ) ) {
423
					self::update_active_modules( $modules );
424
				}
425
426
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
427
428
				// Upgrade to 4.3.0
429
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
430
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
431
				}
432
433
				// Make sure Markdown for posts gets turned back on
434
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
435
					update_option( 'wpcom_publish_posts_with_markdown', true );
436
				}
437
438
				// Minileven deprecation. 8.3.0.
439
				if ( get_option( 'wp_mobile_custom_css' ) ) {
440
					delete_option( 'wp_mobile_custom_css' );
441
				}
442
				if ( Jetpack_Options::get_option( 'wp_mobile_excerpt' ) ) {
443
					Jetpack_Options::delete_option( 'wp_mobile_excerpt' );
444
				}
445
				if ( Jetpack_Options::get_option( 'wp_mobile_featured_images' ) ) {
446
					Jetpack_Options::delete_option( 'wp_mobile_featured_images' );
447
				}
448
				if ( Jetpack_Options::get_option( 'wp_mobile_app_promos' ) ) {
449
					Jetpack_Options::delete_option( 'wp_mobile_app_promos' );
450
				}
451
452
				if ( did_action( 'wp_loaded' ) ) {
453
					self::upgrade_on_load();
454
				} else {
455
					add_action(
456
						'wp_loaded',
457
						array( __CLASS__, 'upgrade_on_load' )
458
					);
459
				}
460
			}
461
		}
462
	}
463
464
	/**
465
	 * Runs upgrade routines that need to have modules loaded.
466
	 */
467
	static function upgrade_on_load() {
468
469
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
470
		// This can happen in case Jetpack has been just upgraded and is
471
		// being initialized late during the page load. In this case we wait
472
		// until the next proper admin page load with Jetpack active.
473
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
474
			delete_transient( self::$plugin_upgrade_lock_key );
475
476
			return;
477
		}
478
479
		self::maybe_set_version_option();
480
481
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
482
			Jetpack_Widget_Conditions::migrate_post_type_rules();
483
		}
484
485
		if (
486
			class_exists( 'Jetpack_Sitemap_Manager' )
487
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
488
		) {
489
			do_action( 'jetpack_sitemaps_purge_data' );
490
		}
491
492
		// Delete old stats cache
493
		delete_option( 'jetpack_restapi_stats_cache' );
494
495
		delete_transient( self::$plugin_upgrade_lock_key );
496
	}
497
498
	/**
499
	 * Saves all the currently active modules to options.
500
	 * Also fires Action hooks for each newly activated and deactivated module.
501
	 *
502
	 * @param $modules Array Array of active modules to be saved in options.
503
	 *
504
	 * @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...
505
	 */
506
	static function update_active_modules( $modules ) {
507
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
508
		$active_modules       = self::get_active_modules();
509
		$new_active_modules   = array_diff( $modules, $current_modules );
510
		$new_inactive_modules = array_diff( $active_modules, $modules );
511
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
512
		$reindexed_modules    = array_values( $new_current_modules );
513
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
514
515
		foreach ( $new_active_modules as $module ) {
516
			/**
517
			 * Fires when a specific module is activated.
518
			 *
519
			 * @since 1.9.0
520
			 *
521
			 * @param string $module Module slug.
522
			 * @param boolean $success whether the module was activated. @since 4.2
523
			 */
524
			do_action( 'jetpack_activate_module', $module, $success );
525
			/**
526
			 * Fires when a module is activated.
527
			 * The dynamic part of the filter, $module, is the module slug.
528
			 *
529
			 * @since 1.9.0
530
			 *
531
			 * @param string $module Module slug.
532
			 */
533
			do_action( "jetpack_activate_module_$module", $module );
534
		}
535
536
		foreach ( $new_inactive_modules as $module ) {
537
			/**
538
			 * Fired after a module has been deactivated.
539
			 *
540
			 * @since 4.2.0
541
			 *
542
			 * @param string $module Module slug.
543
			 * @param boolean $success whether the module was deactivated.
544
			 */
545
			do_action( 'jetpack_deactivate_module', $module, $success );
546
			/**
547
			 * Fires when a module is deactivated.
548
			 * The dynamic part of the filter, $module, is the module slug.
549
			 *
550
			 * @since 1.9.0
551
			 *
552
			 * @param string $module Module slug.
553
			 */
554
			do_action( "jetpack_deactivate_module_$module", $module );
555
		}
556
557
		return $success;
558
	}
559
560
	static function delete_active_modules() {
561
		self::update_active_modules( array() );
562
	}
563
564
	/**
565
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
566
	 * available.
567
	 */
568
	public function add_configure_hook() {
569
		global $wp_filter;
570
571
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
572
		if ( false !== $current_priority ) {
573
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
574
		}
575
576
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
577
		sort( $taken_priorities );
578
579
		$first_priority = array_shift( $taken_priorities );
580
581
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
582
			trigger_error( // phpcs:ignore
583
				/* translators: plugins_loaded is a filter name in WordPress, no need to translate. */
584
				__( 'A plugin on your site is using the plugins_loaded filter with a priority that is too high. Jetpack does not support this, you may experience problems.', 'jetpack' ), // phpcs:ignore
585
				E_USER_NOTICE
586
			);
587
			$new_priority = - PHP_INT_MAX;
588
		} else {
589
			$new_priority = $first_priority - 1;
590
		}
591
592
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
593
	}
594
595
	/**
596
	 * Constructor.  Initializes WordPress hooks
597
	 */
598
	private function __construct() {
599
		/*
600
		 * Check for and alert any deprecated hooks
601
		 */
602
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
603
604
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
605
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
606
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
607
608
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
609
610
		add_filter(
611
			'jetpack_signature_check_token',
612
			array( __CLASS__, 'verify_onboarding_token' ),
613
			10,
614
			3
615
		);
616
617
		/**
618
		 * Prepare Gutenberg Editor functionality
619
		 */
620
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
621
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
622
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
623
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
624
625
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
626
627
		// Unlink user before deleting the user from WP.com.
628
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
629
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
630
631
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
632
633
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
634
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
635
636
		add_action( 'admin_init', array( $this, 'admin_init' ) );
637
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
638
639
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
640
641
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
642
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
643
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
644
645
		// returns HTTPS support status
646
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
647
648
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
649
650
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
651
652
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
653
654
		/**
655
		 * These actions run checks to load additional files.
656
		 * They check for external files or plugins, so they need to run as late as possible.
657
		 */
658
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
659
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
660
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
661
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
662
663
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
664
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
665
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
666
667
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
668
669
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
670
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
671
672
		// A filter to control all just in time messages
673
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
674
675
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
676
677
		// Hide edit post link if mobile app.
678
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
679
			add_filter( 'get_edit_post_link', '__return_empty_string' );
680
		}
681
682
		// Update the Jetpack plan from API on heartbeats
683
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
684
685
		/**
686
		 * This is the hack to concatenate all css files into one.
687
		 * For description and reasoning see the implode_frontend_css method
688
		 *
689
		 * Super late priority so we catch all the registered styles
690
		 */
691
		if ( ! is_admin() ) {
692
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
693
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
694
		}
695
696
		/**
697
		 * These are sync actions that we need to keep track of for jitms
698
		 */
699
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
700
701
		// Actually push the stats on shutdown.
702
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
703
			add_action( 'shutdown', array( $this, 'push_stats' ) );
704
		}
705
706
		/*
707
		 * Load some scripts asynchronously.
708
		 */
709
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
710
711
		// Actions for Manager::authorize().
712
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
713
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
714
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
715
716
		// Filters for the Manager::get_token() urls and request body.
717
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
718
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
719
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
720
	}
721
722
	/**
723
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
724
	 * Config object.
725
	 */
726
	public function configure() {
727
		$config = new Config();
728
729
		foreach (
730
			array(
731
				'connection',
732
				'sync',
733
				'tracking',
734
				'tos',
735
			)
736
			as $feature
737
		) {
738
			$config->ensure( $feature );
739
		}
740
741
		if ( is_admin() ) {
742
			$config->ensure( 'jitm' );
743
		}
744
745
		$this->connection_manager = new Connection_Manager();
746
747
		/*
748
		 * Load things that should only be in Network Admin.
749
		 *
750
		 * For now blow away everything else until a more full
751
		 * understanding of what is needed at the network level is
752
		 * available
753
		 */
754
		if ( is_multisite() ) {
755
			$network = Jetpack_Network::init();
756
			$network->set_connection( $this->connection_manager );
757
		}
758
759
		if ( $this->connection_manager->is_active() ) {
760
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
761
762
			Jetpack_Heartbeat::init();
763
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
764
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
765
				Jetpack_Search_Performance_Logger::init();
766
			}
767
		}
768
769
		// Initialize remote file upload request handlers.
770
		$this->add_remote_request_handlers();
771
772
		/*
773
		 * Enable enhanced handling of previewing sites in Calypso
774
		 */
775
		if ( self::is_active() ) {
776
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
777
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
778
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
779
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
780
		}
781
782
		/*
783
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
784
		 * We should make sure to only do this for front end links.
785
		 */
786
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
787
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
788
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
789
790
			/*
791
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
792
			 * so they point moderation links on emails to Calypso.
793
			 */
794
			jetpack_require_lib( 'functions.wp-notify' );
795
		}
796
797
	}
798
799
	/**
800
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
801
	 * initialization code.
802
	 *
803
	 * @action plugins_loaded
804
	 */
805
	public function late_initialization() {
806
		add_action( 'plugins_loaded', array( 'Jetpack', 'plugin_textdomain' ), 99 );
807
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
808
809
		Partner::init();
810
811
		/**
812
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
813
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
814
		 *
815
		 * @since 8.1.0
816
		 *
817
		 * @param Jetpack $jetpack the main plugin class object.
818
		 */
819
		do_action( 'jetpack_loaded', $this );
820
821
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
822
	}
823
824
	/**
825
	 * Sets up the XMLRPC request handlers.
826
	 *
827
	 * @deprecated since 7.7.0
828
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
829
	 *
830
	 * @param Array                 $request_params Incoming request parameters.
831
	 * @param Boolean               $is_active      Whether the connection is currently active.
832
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
833
	 * @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...
834
	 */
835
	public function setup_xmlrpc_handlers(
836
		$request_params,
837
		$is_active,
838
		$is_signed,
839
		Jetpack_XMLRPC_Server $xmlrpc_server = null
840
	) {
841
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
842
		return $this->connection_manager->setup_xmlrpc_handlers(
843
			$request_params,
844
			$is_active,
845
			$is_signed,
846
			$xmlrpc_server
847
		);
848
	}
849
850
	/**
851
	 * Initialize REST API registration connector.
852
	 *
853
	 * @deprecated since 7.7.0
854
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
855
	 */
856
	public function initialize_rest_api_registration_connector() {
857
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
858
		$this->connection_manager->initialize_rest_api_registration_connector();
859
	}
860
861
	/**
862
	 * This is ported over from the manage module, which has been deprecated and baked in here.
863
	 *
864
	 * @param $domains
865
	 */
866
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
867
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
868
	}
869
870
	/**
871
	 * Return $domains, with 'wordpress.com' appended.
872
	 * This is ported over from the manage module, which has been deprecated and baked in here.
873
	 *
874
	 * @param $domains
875
	 * @return array
876
	 */
877
	function allow_wpcom_domain( $domains ) {
878
		if ( empty( $domains ) ) {
879
			$domains = array();
880
		}
881
		$domains[] = 'wordpress.com';
882
		return array_unique( $domains );
883
	}
884
885
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
886
		$post = get_post( $post_id );
887
888
		if ( empty( $post ) ) {
889
			return $default_url;
890
		}
891
892
		$post_type = $post->post_type;
893
894
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
895
		// https://en.support.wordpress.com/custom-post-types/
896
		$allowed_post_types = array(
897
			'post'                => 'post',
898
			'page'                => 'page',
899
			'jetpack-portfolio'   => 'edit/jetpack-portfolio',
900
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
901
		);
902
903
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
904
			return $default_url;
905
		}
906
907
		$path_prefix = $allowed_post_types[ $post_type ];
908
909
		$site_slug = self::build_raw_urls( get_home_url() );
910
911
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
912
	}
913
914
	function point_edit_comment_links_to_calypso( $url ) {
915
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
916
		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...
917
		return esc_url(
918
			sprintf(
919
				'https://wordpress.com/comment/%s/%d',
920
				self::build_raw_urls( get_home_url() ),
921
				$query_args['amp;c']
922
			)
923
		);
924
	}
925
926
	function jetpack_track_last_sync_callback( $params ) {
927
		/**
928
		 * Filter to turn off jitm caching
929
		 *
930
		 * @since 5.4.0
931
		 *
932
		 * @param bool false Whether to cache just in time messages
933
		 */
934
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
935
			return $params;
936
		}
937
938
		if ( is_array( $params ) && isset( $params[0] ) ) {
939
			$option = $params[0];
940
			if ( 'active_plugins' === $option ) {
941
				// use the cache if we can, but not terribly important if it gets evicted
942
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
943
			}
944
		}
945
946
		return $params;
947
	}
948
949
	function jetpack_connection_banner_callback() {
950
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
951
952
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
953
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
954
			wp_send_json_success();
955
		}
956
957
		wp_die();
958
	}
959
960
	/**
961
	 * Removes all XML-RPC methods that are not `jetpack.*`.
962
	 * Only used in our alternate XML-RPC endpoint, where we want to
963
	 * ensure that Core and other plugins' methods are not exposed.
964
	 *
965
	 * @deprecated since 7.7.0
966
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
967
	 *
968
	 * @param array $methods A list of registered WordPress XMLRPC methods.
969
	 * @return array Filtered $methods
970
	 */
971
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
972
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
973
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
974
	}
975
976
	/**
977
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
978
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
979
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
980
	 * which is accessible via a different URI. Most of the below is copied directly
981
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
982
	 *
983
	 * @deprecated since 7.7.0
984
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
985
	 */
986
	public function alternate_xmlrpc() {
987
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
988
		$this->connection_manager->alternate_xmlrpc();
989
	}
990
991
	/**
992
	 * The callback for the JITM ajax requests.
993
	 *
994
	 * @deprecated since 7.9.0
995
	 */
996
	function jetpack_jitm_ajax_callback() {
997
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
998
	}
999
1000
	/**
1001
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1002
	 */
1003
	function push_stats() {
1004
		if ( ! empty( $this->stats ) ) {
1005
			$this->do_stats( 'server_side' );
1006
		}
1007
	}
1008
1009
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1010
		$is_development_mode = ( new Status() )->is_development_mode();
1011
		switch ( $cap ) {
1012
			case 'jetpack_connect':
1013
			case 'jetpack_reconnect':
1014
				if ( $is_development_mode ) {
1015
					$caps = array( 'do_not_allow' );
1016
					break;
1017
				}
1018
				/**
1019
				 * Pass through. If it's not development mode, these should match disconnect.
1020
				 * Let users disconnect if it's development mode, just in case things glitch.
1021
				 */
1022
			case 'jetpack_disconnect':
1023
				/**
1024
				 * In multisite, can individual site admins manage their own connection?
1025
				 *
1026
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1027
				 */
1028
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1029
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1030
						/**
1031
						 * We need to update the option name -- it's terribly unclear which
1032
						 * direction the override goes.
1033
						 *
1034
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1035
						 */
1036
						$caps = array( 'do_not_allow' );
1037
						break;
1038
					}
1039
				}
1040
1041
				$caps = array( 'manage_options' );
1042
				break;
1043
			case 'jetpack_manage_modules':
1044
			case 'jetpack_activate_modules':
1045
			case 'jetpack_deactivate_modules':
1046
				$caps = array( 'manage_options' );
1047
				break;
1048
			case 'jetpack_configure_modules':
1049
				$caps = array( 'manage_options' );
1050
				break;
1051
			case 'jetpack_manage_autoupdates':
1052
				$caps = array(
1053
					'manage_options',
1054
					'update_plugins',
1055
				);
1056
				break;
1057
			case 'jetpack_network_admin_page':
1058
			case 'jetpack_network_settings_page':
1059
				$caps = array( 'manage_network_plugins' );
1060
				break;
1061
			case 'jetpack_network_sites_page':
1062
				$caps = array( 'manage_sites' );
1063
				break;
1064
			case 'jetpack_admin_page':
1065
				if ( $is_development_mode ) {
1066
					$caps = array( 'manage_options' );
1067
					break;
1068
				} else {
1069
					$caps = array( 'read' );
1070
				}
1071
				break;
1072
			case 'jetpack_connect_user':
1073
				if ( $is_development_mode ) {
1074
					$caps = array( 'do_not_allow' );
1075
					break;
1076
				}
1077
				$caps = array( 'read' );
1078
				break;
1079
		}
1080
		return $caps;
1081
	}
1082
1083
	/**
1084
	 * Require a Jetpack authentication.
1085
	 *
1086
	 * @deprecated since 7.7.0
1087
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1088
	 */
1089
	public function require_jetpack_authentication() {
1090
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1091
		$this->connection_manager->require_jetpack_authentication();
1092
	}
1093
1094
	/**
1095
	 * Load language files
1096
	 *
1097
	 * @action plugins_loaded
1098
	 */
1099
	public static function plugin_textdomain() {
1100
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1101
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1102
	}
1103
1104
	/**
1105
	 * Register assets for use in various modules and the Jetpack admin page.
1106
	 *
1107
	 * @uses wp_script_is, wp_register_script, plugins_url
1108
	 * @action wp_loaded
1109
	 * @return null
1110
	 */
1111
	public function register_assets() {
1112
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1113
			wp_register_script(
1114
				'spin',
1115
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1116
				false,
1117
				'1.3'
1118
			);
1119
		}
1120
1121 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1122
			wp_register_script(
1123
				'jquery.spin',
1124
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1125
				array( 'jquery', 'spin' ),
1126
				'1.3'
1127
			);
1128
		}
1129
1130 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1131
			wp_register_script(
1132
				'jetpack-gallery-settings',
1133
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1134
				array( 'media-views' ),
1135
				'20121225'
1136
			);
1137
		}
1138
1139 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1140
			wp_register_script(
1141
				'jetpack-twitter-timeline',
1142
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1143
				array( 'jquery' ),
1144
				'4.0.0',
1145
				true
1146
			);
1147
		}
1148
1149
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1150
			wp_register_script(
1151
				'jetpack-facebook-embed',
1152
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1153
				array( 'jquery' ),
1154
				null,
1155
				true
1156
			);
1157
1158
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1159
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1160
			if ( ! is_numeric( $fb_app_id ) ) {
1161
				$fb_app_id = '';
1162
			}
1163
			wp_localize_script(
1164
				'jetpack-facebook-embed',
1165
				'jpfbembed',
1166
				array(
1167
					'appid'  => $fb_app_id,
1168
					'locale' => $this->get_locale(),
1169
				)
1170
			);
1171
		}
1172
1173
		/**
1174
		 * As jetpack_register_genericons is by default fired off a hook,
1175
		 * the hook may have already fired by this point.
1176
		 * So, let's just trigger it manually.
1177
		 */
1178
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1179
		jetpack_register_genericons();
1180
1181
		/**
1182
		 * Register the social logos
1183
		 */
1184
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1185
		jetpack_register_social_logos();
1186
1187 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1188
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1189
		}
1190
	}
1191
1192
	/**
1193
	 * Guess locale from language code.
1194
	 *
1195
	 * @param string $lang Language code.
1196
	 * @return string|bool
1197
	 */
1198 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1199
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1200
			return 'en_US';
1201
		}
1202
1203
		if ( ! class_exists( 'GP_Locales' ) ) {
1204
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1205
				return false;
1206
			}
1207
1208
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1209
		}
1210
1211
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1212
			// WP.com: get_locale() returns 'it'
1213
			$locale = GP_Locales::by_slug( $lang );
1214
		} else {
1215
			// Jetpack: get_locale() returns 'it_IT';
1216
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1217
		}
1218
1219
		if ( ! $locale ) {
1220
			return false;
1221
		}
1222
1223
		if ( empty( $locale->facebook_locale ) ) {
1224
			if ( empty( $locale->wp_locale ) ) {
1225
				return false;
1226
			} else {
1227
				// Facebook SDK is smart enough to fall back to en_US if a
1228
				// locale isn't supported. Since supported Facebook locales
1229
				// can fall out of sync, we'll attempt to use the known
1230
				// wp_locale value and rely on said fallback.
1231
				return $locale->wp_locale;
1232
			}
1233
		}
1234
1235
		return $locale->facebook_locale;
1236
	}
1237
1238
	/**
1239
	 * Get the locale.
1240
	 *
1241
	 * @return string|bool
1242
	 */
1243
	function get_locale() {
1244
		$locale = $this->guess_locale_from_lang( get_locale() );
1245
1246
		if ( ! $locale ) {
1247
			$locale = 'en_US';
1248
		}
1249
1250
		return $locale;
1251
	}
1252
1253
	/**
1254
	 * Return the network_site_url so that .com knows what network this site is a part of.
1255
	 *
1256
	 * @param  bool $option
1257
	 * @return string
1258
	 */
1259
	public function jetpack_main_network_site_option( $option ) {
1260
		return network_site_url();
1261
	}
1262
	/**
1263
	 * Network Name.
1264
	 */
1265
	static function network_name( $option = null ) {
1266
		global $current_site;
1267
		return $current_site->site_name;
1268
	}
1269
	/**
1270
	 * Does the network allow new user and site registrations.
1271
	 *
1272
	 * @return string
1273
	 */
1274
	static function network_allow_new_registrations( $option = null ) {
1275
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1276
	}
1277
	/**
1278
	 * Does the network allow admins to add new users.
1279
	 *
1280
	 * @return boolian
1281
	 */
1282
	static function network_add_new_users( $option = null ) {
1283
		return (bool) get_site_option( 'add_new_users' );
1284
	}
1285
	/**
1286
	 * File upload psace left per site in MB.
1287
	 *  -1 means NO LIMIT.
1288
	 *
1289
	 * @return number
1290
	 */
1291
	static function network_site_upload_space( $option = null ) {
1292
		// value in MB
1293
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1294
	}
1295
1296
	/**
1297
	 * Network allowed file types.
1298
	 *
1299
	 * @return string
1300
	 */
1301
	static function network_upload_file_types( $option = null ) {
1302
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1303
	}
1304
1305
	/**
1306
	 * Maximum file upload size set by the network.
1307
	 *
1308
	 * @return number
1309
	 */
1310
	static function network_max_upload_file_size( $option = null ) {
1311
		// value in KB
1312
		return get_site_option( 'fileupload_maxk', 300 );
1313
	}
1314
1315
	/**
1316
	 * Lets us know if a site allows admins to manage the network.
1317
	 *
1318
	 * @return array
1319
	 */
1320
	static function network_enable_administration_menus( $option = null ) {
1321
		return get_site_option( 'menu_items' );
1322
	}
1323
1324
	/**
1325
	 * If a user has been promoted to or demoted from admin, we need to clear the
1326
	 * jetpack_other_linked_admins transient.
1327
	 *
1328
	 * @since 4.3.2
1329
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1330
	 *
1331
	 * @param int    $user_id   The user ID whose role changed.
1332
	 * @param string $role      The new role.
1333
	 * @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...
1334
	 */
1335
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1336
		if ( 'administrator' == $role
1337
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1338
			|| is_null( $old_roles )
1339
		) {
1340
			delete_transient( 'jetpack_other_linked_admins' );
1341
		}
1342
	}
1343
1344
	/**
1345
	 * Checks to see if there are any other users available to become primary
1346
	 * Users must both:
1347
	 * - Be linked to wpcom
1348
	 * - Be an admin
1349
	 *
1350
	 * @return mixed False if no other users are linked, Int if there are.
1351
	 */
1352
	static function get_other_linked_admins() {
1353
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1354
1355
		if ( false === $other_linked_users ) {
1356
			$admins = get_users( array( 'role' => 'administrator' ) );
1357
			if ( count( $admins ) > 1 ) {
1358
				$available = array();
1359
				foreach ( $admins as $admin ) {
1360
					if ( self::is_user_connected( $admin->ID ) ) {
1361
						$available[] = $admin->ID;
1362
					}
1363
				}
1364
1365
				$count_connected_admins = count( $available );
1366
				if ( count( $available ) > 1 ) {
1367
					$other_linked_users = $count_connected_admins;
1368
				} else {
1369
					$other_linked_users = 0;
1370
				}
1371
			} else {
1372
				$other_linked_users = 0;
1373
			}
1374
1375
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1376
		}
1377
1378
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1379
	}
1380
1381
	/**
1382
	 * Return whether we are dealing with a multi network setup or not.
1383
	 * The reason we are type casting this is because we want to avoid the situation where
1384
	 * the result is false since when is_main_network_option return false it cases
1385
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1386
	 * database which could be set to anything as opposed to what this function returns.
1387
	 *
1388
	 * @param  bool $option
1389
	 *
1390
	 * @return boolean
1391
	 */
1392
	public function is_main_network_option( $option ) {
1393
		// return '1' or ''
1394
		return (string) (bool) self::is_multi_network();
1395
	}
1396
1397
	/**
1398
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1399
	 *
1400
	 * @param  string $option
1401
	 * @return boolean
1402
	 */
1403
	public function is_multisite( $option ) {
1404
		return (string) (bool) is_multisite();
1405
	}
1406
1407
	/**
1408
	 * Implemented since there is no core is multi network function
1409
	 * Right now there is no way to tell if we which network is the dominant network on the system
1410
	 *
1411
	 * @since  3.3
1412
	 * @return boolean
1413
	 */
1414 View Code Duplication
	public static function is_multi_network() {
1415
		global  $wpdb;
1416
1417
		// if we don't have a multi site setup no need to do any more
1418
		if ( ! is_multisite() ) {
1419
			return false;
1420
		}
1421
1422
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1423
		if ( $num_sites > 1 ) {
1424
			return true;
1425
		} else {
1426
			return false;
1427
		}
1428
	}
1429
1430
	/**
1431
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1432
	 *
1433
	 * @return null
1434
	 */
1435
	function update_jetpack_main_network_site_option() {
1436
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1437
	}
1438
	/**
1439
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1440
	 */
1441
	function update_jetpack_network_settings() {
1442
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1443
		// Only sync this info for the main network site.
1444
	}
1445
1446
	/**
1447
	 * Get back if the current site is single user site.
1448
	 *
1449
	 * @return bool
1450
	 */
1451 View Code Duplication
	public static function is_single_user_site() {
1452
		global $wpdb;
1453
1454
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1455
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1456
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1457
		}
1458
		return 1 === (int) $some_users;
1459
	}
1460
1461
	/**
1462
	 * Returns true if the site has file write access false otherwise.
1463
	 *
1464
	 * @return string ( '1' | '0' )
1465
	 **/
1466
	public static function file_system_write_access() {
1467
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1468
			require_once ABSPATH . 'wp-admin/includes/file.php';
1469
		}
1470
1471
		require_once ABSPATH . 'wp-admin/includes/template.php';
1472
1473
		$filesystem_method = get_filesystem_method();
1474
		if ( $filesystem_method === 'direct' ) {
1475
			return 1;
1476
		}
1477
1478
		ob_start();
1479
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1480
		ob_end_clean();
1481
		if ( $filesystem_credentials_are_stored ) {
1482
			return 1;
1483
		}
1484
		return 0;
1485
	}
1486
1487
	/**
1488
	 * Finds out if a site is using a version control system.
1489
	 *
1490
	 * @return string ( '1' | '0' )
1491
	 **/
1492
	public static function is_version_controlled() {
1493
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1494
		return (string) (int) Functions::is_version_controlled();
1495
	}
1496
1497
	/**
1498
	 * Determines whether the current theme supports featured images or not.
1499
	 *
1500
	 * @return string ( '1' | '0' )
1501
	 */
1502
	public static function featured_images_enabled() {
1503
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1504
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1505
	}
1506
1507
	/**
1508
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1509
	 *
1510
	 * @deprecated 4.7 use get_avatar_url instead.
1511
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1512
	 * @param int               $size Size of the avatar image
1513
	 * @param string            $default URL to a default image to use if no avatar is available
1514
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1515
	 *
1516
	 * @return array
1517
	 */
1518
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1519
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1520
		return get_avatar_url(
1521
			$id_or_email,
1522
			array(
1523
				'size'          => $size,
1524
				'default'       => $default,
1525
				'force_default' => $force_display,
1526
			)
1527
		);
1528
	}
1529
1530
	/**
1531
	 * jetpack_updates is saved in the following schema:
1532
	 *
1533
	 * array (
1534
	 *      'plugins'                       => (int) Number of plugin updates available.
1535
	 *      'themes'                        => (int) Number of theme updates available.
1536
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1537
	 *      'translations'                  => (int) Number of translation updates available.
1538
	 *      'total'                         => (int) Total of all available updates.
1539
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1540
	 * )
1541
	 *
1542
	 * @return array
1543
	 */
1544
	public static function get_updates() {
1545
		$update_data = wp_get_update_data();
1546
1547
		// Stores the individual update counts as well as the total count.
1548
		if ( isset( $update_data['counts'] ) ) {
1549
			$updates = $update_data['counts'];
1550
		}
1551
1552
		// If we need to update WordPress core, let's find the latest version number.
1553 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1554
			$cur = get_preferred_from_update_core();
1555
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1556
				$updates['wp_update_version'] = $cur->current;
1557
			}
1558
		}
1559
		return isset( $updates ) ? $updates : array();
1560
	}
1561
1562
	public static function get_update_details() {
1563
		$update_details = array(
1564
			'update_core'    => get_site_transient( 'update_core' ),
1565
			'update_plugins' => get_site_transient( 'update_plugins' ),
1566
			'update_themes'  => get_site_transient( 'update_themes' ),
1567
		);
1568
		return $update_details;
1569
	}
1570
1571
	public static function refresh_update_data() {
1572
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1573
1574
	}
1575
1576
	public static function refresh_theme_data() {
1577
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1578
	}
1579
1580
	/**
1581
	 * Is Jetpack active?
1582
	 */
1583
	public static function is_active() {
1584
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
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...
1585
	}
1586
1587
	/**
1588
	 * Make an API call to WordPress.com for plan status
1589
	 *
1590
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1591
	 *
1592
	 * @return bool True if plan is updated, false if no update
1593
	 */
1594
	public static function refresh_active_plan_from_wpcom() {
1595
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1596
		return Jetpack_Plan::refresh_from_wpcom();
1597
	}
1598
1599
	/**
1600
	 * Get the plan that this Jetpack site is currently using
1601
	 *
1602
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1603
	 * @return array Active Jetpack plan details.
1604
	 */
1605
	public static function get_active_plan() {
1606
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1607
		return Jetpack_Plan::get();
1608
	}
1609
1610
	/**
1611
	 * Determine whether the active plan supports a particular feature
1612
	 *
1613
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1614
	 * @return bool True if plan supports feature, false if not.
1615
	 */
1616
	public static function active_plan_supports( $feature ) {
1617
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1618
		return Jetpack_Plan::supports( $feature );
1619
	}
1620
1621
	/**
1622
	 * Deprecated: Is Jetpack in development (offline) mode?
1623
	 *
1624
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1625
	 * and themes still use it, and we do not want to flood them with notices.
1626
	 *
1627
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1628
	 *
1629
	 * @deprecated since 8.0.
1630
	 */
1631
	public static function is_development_mode() {
1632
		return ( new Status() )->is_development_mode();
1633
	}
1634
1635
	/**
1636
	 * Whether the site is currently onboarding or not.
1637
	 * A site is considered as being onboarded if it currently has an onboarding token.
1638
	 *
1639
	 * @since 5.8
1640
	 *
1641
	 * @access public
1642
	 * @static
1643
	 *
1644
	 * @return bool True if the site is currently onboarding, false otherwise
1645
	 */
1646
	public static function is_onboarding() {
1647
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1648
	}
1649
1650
	/**
1651
	 * Determines reason for Jetpack development mode.
1652
	 */
1653
	public static function development_mode_trigger_text() {
1654
		if ( ! ( new Status() )->is_development_mode() ) {
1655
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1656
		}
1657
1658
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1659
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1660
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1661
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1662
		} else {
1663
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1664
		}
1665
1666
		return $notice;
1667
1668
	}
1669
	/**
1670
	 * Get Jetpack development mode notice text and notice class.
1671
	 *
1672
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1673
	 */
1674
	public static function show_development_mode_notice() {
1675 View Code Duplication
		if ( ( new Status() )->is_development_mode() ) {
1676
			$notice = sprintf(
1677
				/* translators: %s is a URL */
1678
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1679
				'https://jetpack.com/support/development-mode/'
1680
			);
1681
1682
			$notice .= ' ' . self::development_mode_trigger_text();
1683
1684
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1685
		}
1686
1687
		// Throw up a notice if using a development version and as for feedback.
1688
		if ( self::is_development_version() ) {
1689
			/* translators: %s is a URL */
1690
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), 'https://jetpack.com/contact-support/beta-group/' );
1691
1692
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1693
		}
1694
		// Throw up a notice if using staging mode
1695
		if ( ( new Status() )->is_staging_site() ) {
1696
			/* translators: %s is a URL */
1697
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1698
1699
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1700
		}
1701
	}
1702
1703
	/**
1704
	 * Whether Jetpack's version maps to a public release, or a development version.
1705
	 */
1706
	public static function is_development_version() {
1707
		/**
1708
		 * Allows filtering whether this is a development version of Jetpack.
1709
		 *
1710
		 * This filter is especially useful for tests.
1711
		 *
1712
		 * @since 4.3.0
1713
		 *
1714
		 * @param bool $development_version Is this a develoment version of Jetpack?
1715
		 */
1716
		return (bool) apply_filters(
1717
			'jetpack_development_version',
1718
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1719
		);
1720
	}
1721
1722
	/**
1723
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1724
	 */
1725
	public static function is_user_connected( $user_id = false ) {
1726
		return self::connection()->is_user_connected( $user_id );
1727
	}
1728
1729
	/**
1730
	 * Get the wpcom user data of the current|specified connected user.
1731
	 */
1732 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1733
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1734
		if ( ! $user_id ) {
1735
			$user_id = get_current_user_id();
1736
		}
1737
1738
		$transient_key = "jetpack_connected_user_data_$user_id";
1739
1740
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1741
			return $cached_user_data;
1742
		}
1743
1744
		$xml = new Jetpack_IXR_Client(
1745
			array(
1746
				'user_id' => $user_id,
1747
			)
1748
		);
1749
		$xml->query( 'wpcom.getUser' );
1750
		if ( ! $xml->isError() ) {
1751
			$user_data = $xml->getResponse();
1752
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1753
			return $user_data;
1754
		}
1755
1756
		return false;
1757
	}
1758
1759
	/**
1760
	 * Get the wpcom email of the current|specified connected user.
1761
	 */
1762 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1763
		if ( ! $user_id ) {
1764
			$user_id = get_current_user_id();
1765
		}
1766
1767
		$xml = new Jetpack_IXR_Client(
1768
			array(
1769
				'user_id' => $user_id,
1770
			)
1771
		);
1772
		$xml->query( 'wpcom.getUserEmail' );
1773
		if ( ! $xml->isError() ) {
1774
			return $xml->getResponse();
1775
		}
1776
		return false;
1777
	}
1778
1779
	/**
1780
	 * Get the wpcom email of the master user.
1781
	 */
1782
	public static function get_master_user_email() {
1783
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1784
		if ( $master_user_id ) {
1785
			return self::get_connected_user_email( $master_user_id );
1786
		}
1787
		return '';
1788
	}
1789
1790
	/**
1791
	 * Whether the current user is the connection owner.
1792
	 *
1793
	 * @deprecated since 7.7
1794
	 *
1795
	 * @return bool Whether the current user is the connection owner.
1796
	 */
1797
	public function current_user_is_connection_owner() {
1798
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1799
		return self::connection()->is_connection_owner();
1800
	}
1801
1802
	/**
1803
	 * Gets current user IP address.
1804
	 *
1805
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1806
	 *
1807
	 * @return string                  Current user IP address.
1808
	 */
1809
	public static function current_user_ip( $check_all_headers = false ) {
1810
		if ( $check_all_headers ) {
1811
			foreach ( array(
1812
				'HTTP_CF_CONNECTING_IP',
1813
				'HTTP_CLIENT_IP',
1814
				'HTTP_X_FORWARDED_FOR',
1815
				'HTTP_X_FORWARDED',
1816
				'HTTP_X_CLUSTER_CLIENT_IP',
1817
				'HTTP_FORWARDED_FOR',
1818
				'HTTP_FORWARDED',
1819
				'HTTP_VIA',
1820
			) as $key ) {
1821
				if ( ! empty( $_SERVER[ $key ] ) ) {
1822
					return $_SERVER[ $key ];
1823
				}
1824
			}
1825
		}
1826
1827
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1828
	}
1829
1830
	/**
1831
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1832
	 */
1833
	function extra_oembed_providers() {
1834
		// Cloudup: https://dev.cloudup.com/#oembed
1835
		wp_oembed_add_provider( 'https://cloudup.com/*', 'https://cloudup.com/oembed' );
1836
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1837
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1838
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1839
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1840
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1841
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1842
	}
1843
1844
	/**
1845
	 * Synchronize connected user role changes
1846
	 */
1847
	function user_role_change( $user_id ) {
1848
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1849
		Users::user_role_change( $user_id );
1850
	}
1851
1852
	/**
1853
	 * Loads the currently active modules.
1854
	 */
1855
	public static function load_modules() {
1856
		$is_development_mode = ( new Status() )->is_development_mode();
1857
		if (
1858
			! self::is_active()
1859
			&& ! $is_development_mode
1860
			&& ! self::is_onboarding()
1861
			&& (
1862
				! is_multisite()
1863
				|| ! get_site_option( 'jetpack_protect_active' )
1864
			)
1865
		) {
1866
			return;
1867
		}
1868
1869
		$version = Jetpack_Options::get_option( 'version' );
1870 View Code Duplication
		if ( ! $version ) {
1871
			$version = $old_version = JETPACK__VERSION . ':' . time();
1872
			/** This action is documented in class.jetpack.php */
1873
			do_action( 'updating_jetpack_version', $version, false );
1874
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1875
		}
1876
		list( $version ) = explode( ':', $version );
1877
1878
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1879
1880
		$modules_data = array();
1881
1882
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1883
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1884
			$updated_modules = array();
1885
			foreach ( $modules as $module ) {
1886
				$modules_data[ $module ] = self::get_module( $module );
1887
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1888
					continue;
1889
				}
1890
1891
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1892
					continue;
1893
				}
1894
1895
				$updated_modules[] = $module;
1896
			}
1897
1898
			$modules = array_diff( $modules, $updated_modules );
1899
		}
1900
1901
		foreach ( $modules as $index => $module ) {
1902
			// If we're in dev mode, disable modules requiring a connection
1903
			if ( $is_development_mode ) {
1904
				// Prime the pump if we need to
1905
				if ( empty( $modules_data[ $module ] ) ) {
1906
					$modules_data[ $module ] = self::get_module( $module );
1907
				}
1908
				// If the module requires a connection, but we're in local mode, don't include it.
1909
				if ( $modules_data[ $module ]['requires_connection'] ) {
1910
					continue;
1911
				}
1912
			}
1913
1914
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1915
				continue;
1916
			}
1917
1918
			if ( ! include_once self::get_module_path( $module ) ) {
1919
				unset( $modules[ $index ] );
1920
				self::update_active_modules( array_values( $modules ) );
1921
				continue;
1922
			}
1923
1924
			/**
1925
			 * Fires when a specific module is loaded.
1926
			 * The dynamic part of the hook, $module, is the module slug.
1927
			 *
1928
			 * @since 1.1.0
1929
			 */
1930
			do_action( 'jetpack_module_loaded_' . $module );
1931
		}
1932
1933
		/**
1934
		 * Fires when all the modules are loaded.
1935
		 *
1936
		 * @since 1.1.0
1937
		 */
1938
		do_action( 'jetpack_modules_loaded' );
1939
1940
		// 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.
1941
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1942
	}
1943
1944
	/**
1945
	 * Check if Jetpack's REST API compat file should be included
1946
	 *
1947
	 * @action plugins_loaded
1948
	 * @return null
1949
	 */
1950
	public function check_rest_api_compat() {
1951
		/**
1952
		 * Filters the list of REST API compat files to be included.
1953
		 *
1954
		 * @since 2.2.5
1955
		 *
1956
		 * @param array $args Array of REST API compat files to include.
1957
		 */
1958
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1959
1960
		if ( function_exists( 'bbpress' ) ) {
1961
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1962
		}
1963
1964
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1965
			require_once $_jetpack_rest_api_compat_include;
1966
		}
1967
	}
1968
1969
	/**
1970
	 * Gets all plugins currently active in values, regardless of whether they're
1971
	 * traditionally activated or network activated.
1972
	 *
1973
	 * @todo Store the result in core's object cache maybe?
1974
	 */
1975
	public static function get_active_plugins() {
1976
		$active_plugins = (array) get_option( 'active_plugins', array() );
1977
1978
		if ( is_multisite() ) {
1979
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1980
			// whereas active_plugins stores them in the values.
1981
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1982
			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...
1983
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1984
			}
1985
		}
1986
1987
		sort( $active_plugins );
1988
1989
		return array_unique( $active_plugins );
1990
	}
1991
1992
	/**
1993
	 * Gets and parses additional plugin data to send with the heartbeat data
1994
	 *
1995
	 * @since 3.8.1
1996
	 *
1997
	 * @return array Array of plugin data
1998
	 */
1999
	public static function get_parsed_plugin_data() {
2000
		if ( ! function_exists( 'get_plugins' ) ) {
2001
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2002
		}
2003
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2004
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2005
		$active_plugins = self::get_active_plugins();
2006
2007
		$plugins = array();
2008
		foreach ( $all_plugins as $path => $plugin_data ) {
2009
			$plugins[ $path ] = array(
2010
				'is_active' => in_array( $path, $active_plugins ),
2011
				'file'      => $path,
2012
				'name'      => $plugin_data['Name'],
2013
				'version'   => $plugin_data['Version'],
2014
				'author'    => $plugin_data['Author'],
2015
			);
2016
		}
2017
2018
		return $plugins;
2019
	}
2020
2021
	/**
2022
	 * Gets and parses theme data to send with the heartbeat data
2023
	 *
2024
	 * @since 3.8.1
2025
	 *
2026
	 * @return array Array of theme data
2027
	 */
2028
	public static function get_parsed_theme_data() {
2029
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2030
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2031
2032
		$themes = array();
2033
		foreach ( $all_themes as $slug => $theme_data ) {
2034
			$theme_headers = array();
2035
			foreach ( $header_keys as $header_key ) {
2036
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2037
			}
2038
2039
			$themes[ $slug ] = array(
2040
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2041
				'slug'            => $slug,
2042
				'theme_root'      => $theme_data->get_theme_root_uri(),
2043
				'parent'          => $theme_data->parent(),
2044
				'headers'         => $theme_headers,
2045
			);
2046
		}
2047
2048
		return $themes;
2049
	}
2050
2051
	/**
2052
	 * Checks whether a specific plugin is active.
2053
	 *
2054
	 * We don't want to store these in a static variable, in case
2055
	 * there are switch_to_blog() calls involved.
2056
	 */
2057
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2058
		return in_array( $plugin, self::get_active_plugins() );
2059
	}
2060
2061
	/**
2062
	 * Check if Jetpack's Open Graph tags should be used.
2063
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2064
	 *
2065
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2066
	 * @action plugins_loaded
2067
	 * @return null
2068
	 */
2069
	public function check_open_graph() {
2070
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2071
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2072
		}
2073
2074
		$active_plugins = self::get_active_plugins();
2075
2076
		if ( ! empty( $active_plugins ) ) {
2077
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2078
				if ( in_array( $plugin, $active_plugins ) ) {
2079
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2080
					break;
2081
				}
2082
			}
2083
		}
2084
2085
		/**
2086
		 * Allow the addition of Open Graph Meta Tags to all pages.
2087
		 *
2088
		 * @since 2.0.3
2089
		 *
2090
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2091
		 */
2092
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2093
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2094
		}
2095
	}
2096
2097
	/**
2098
	 * Check if Jetpack's Twitter tags should be used.
2099
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2100
	 *
2101
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2102
	 * @action plugins_loaded
2103
	 * @return null
2104
	 */
2105
	public function check_twitter_tags() {
2106
2107
		$active_plugins = self::get_active_plugins();
2108
2109
		if ( ! empty( $active_plugins ) ) {
2110
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2111
				if ( in_array( $plugin, $active_plugins ) ) {
2112
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2113
					break;
2114
				}
2115
			}
2116
		}
2117
2118
		/**
2119
		 * Allow Twitter Card Meta tags to be disabled.
2120
		 *
2121
		 * @since 2.6.0
2122
		 *
2123
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2124
		 */
2125
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2126
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2127
		}
2128
	}
2129
2130
	/**
2131
	 * Allows plugins to submit security reports.
2132
	 *
2133
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2134
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2135
	 * @param array  $args         See definitions above
2136
	 */
2137
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2138
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2139
	}
2140
2141
	/* Jetpack Options API */
2142
2143
	public static function get_option_names( $type = 'compact' ) {
2144
		return Jetpack_Options::get_option_names( $type );
2145
	}
2146
2147
	/**
2148
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2149
	 *
2150
	 * @param string $name    Option name
2151
	 * @param mixed  $default (optional)
2152
	 */
2153
	public static function get_option( $name, $default = false ) {
2154
		return Jetpack_Options::get_option( $name, $default );
2155
	}
2156
2157
	/**
2158
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2159
	 *
2160
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2161
	 * @param string $name  Option name
2162
	 * @param mixed  $value Option value
2163
	 */
2164
	public static function update_option( $name, $value ) {
2165
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2166
		return Jetpack_Options::update_option( $name, $value );
2167
	}
2168
2169
	/**
2170
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2171
	 *
2172
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2173
	 * @param array $array array( option name => option value, ... )
2174
	 */
2175
	public static function update_options( $array ) {
2176
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2177
		return Jetpack_Options::update_options( $array );
2178
	}
2179
2180
	/**
2181
	 * Deletes the given option.  May be passed multiple option names as an array.
2182
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2183
	 *
2184
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2185
	 * @param string|array $names
2186
	 */
2187
	public static function delete_option( $names ) {
2188
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2189
		return Jetpack_Options::delete_option( $names );
2190
	}
2191
2192
	/**
2193
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2194
	 *
2195
	 * Enters a user token into the user_tokens option
2196
	 *
2197
	 * @param int    $user_id The user id.
2198
	 * @param string $token The user token.
2199
	 * @param bool   $is_master_user Whether the user is the master user.
2200
	 * @return bool
2201
	 */
2202
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2203
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2204
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2205
	}
2206
2207
	/**
2208
	 * Returns an array of all PHP files in the specified absolute path.
2209
	 * Equivalent to glob( "$absolute_path/*.php" ).
2210
	 *
2211
	 * @param string $absolute_path The absolute path of the directory to search.
2212
	 * @return array Array of absolute paths to the PHP files.
2213
	 */
2214
	public static function glob_php( $absolute_path ) {
2215
		if ( function_exists( 'glob' ) ) {
2216
			return glob( "$absolute_path/*.php" );
2217
		}
2218
2219
		$absolute_path = untrailingslashit( $absolute_path );
2220
		$files         = array();
2221
		if ( ! $dir = @opendir( $absolute_path ) ) {
2222
			return $files;
2223
		}
2224
2225
		while ( false !== $file = readdir( $dir ) ) {
2226
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2227
				continue;
2228
			}
2229
2230
			$file = "$absolute_path/$file";
2231
2232
			if ( ! is_file( $file ) ) {
2233
				continue;
2234
			}
2235
2236
			$files[] = $file;
2237
		}
2238
2239
		closedir( $dir );
2240
2241
		return $files;
2242
	}
2243
2244
	public static function activate_new_modules( $redirect = false ) {
2245
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2246
			return;
2247
		}
2248
2249
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2250 View Code Duplication
		if ( ! $jetpack_old_version ) {
2251
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2252
			/** This action is documented in class.jetpack.php */
2253
			do_action( 'updating_jetpack_version', $version, false );
2254
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2255
		}
2256
2257
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2258
2259
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2260
			return;
2261
		}
2262
2263
		$active_modules     = self::get_active_modules();
2264
		$reactivate_modules = array();
2265
		foreach ( $active_modules as $active_module ) {
2266
			$module = self::get_module( $active_module );
2267
			if ( ! isset( $module['changed'] ) ) {
2268
				continue;
2269
			}
2270
2271
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2272
				continue;
2273
			}
2274
2275
			$reactivate_modules[] = $active_module;
2276
			self::deactivate_module( $active_module );
2277
		}
2278
2279
		$new_version = JETPACK__VERSION . ':' . time();
2280
		/** This action is documented in class.jetpack.php */
2281
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2282
		Jetpack_Options::update_options(
2283
			array(
2284
				'version'     => $new_version,
2285
				'old_version' => $jetpack_old_version,
2286
			)
2287
		);
2288
2289
		self::state( 'message', 'modules_activated' );
2290
		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...
2291
2292
		if ( $redirect ) {
2293
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2294
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2295
				$page = $_GET['page'];
2296
			}
2297
2298
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2299
			exit;
2300
		}
2301
	}
2302
2303
	/**
2304
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2305
	 * Make sure to tuck away module "library" files in a sub-directory.
2306
	 */
2307
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2308
		static $modules = null;
2309
2310
		if ( ! isset( $modules ) ) {
2311
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2312
			// Use the cache if we're on the front-end and it's available...
2313
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2314
				$modules = $available_modules_option[ JETPACK__VERSION ];
2315
			} else {
2316
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2317
2318
				$modules = array();
2319
2320
				foreach ( $files as $file ) {
2321
					if ( ! $headers = self::get_module( $file ) ) {
2322
						continue;
2323
					}
2324
2325
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2326
				}
2327
2328
				Jetpack_Options::update_option(
2329
					'available_modules',
2330
					array(
2331
						JETPACK__VERSION => $modules,
2332
					)
2333
				);
2334
			}
2335
		}
2336
2337
		/**
2338
		 * Filters the array of modules available to be activated.
2339
		 *
2340
		 * @since 2.4.0
2341
		 *
2342
		 * @param array $modules Array of available modules.
2343
		 * @param string $min_version Minimum version number required to use modules.
2344
		 * @param string $max_version Maximum version number required to use modules.
2345
		 */
2346
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2347
2348
		if ( ! $min_version && ! $max_version ) {
2349
			return array_keys( $mods );
2350
		}
2351
2352
		$r = array();
2353
		foreach ( $mods as $slug => $introduced ) {
2354
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2355
				continue;
2356
			}
2357
2358
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2359
				continue;
2360
			}
2361
2362
			$r[] = $slug;
2363
		}
2364
2365
		return $r;
2366
	}
2367
2368
	/**
2369
	 * Default modules loaded on activation.
2370
	 */
2371
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2372
		$return = array();
2373
2374
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2375
			$module_data = self::get_module( $module );
2376
2377
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2378
				case 'yes':
2379
					$return[] = $module;
2380
					break;
2381
				case 'public':
2382
					if ( Jetpack_Options::get_option( 'public' ) ) {
2383
						$return[] = $module;
2384
					}
2385
					break;
2386
				case 'no':
2387
				default:
2388
					break;
2389
			}
2390
		}
2391
		/**
2392
		 * Filters the array of default modules.
2393
		 *
2394
		 * @since 2.5.0
2395
		 *
2396
		 * @param array $return Array of default modules.
2397
		 * @param string $min_version Minimum version number required to use modules.
2398
		 * @param string $max_version Maximum version number required to use modules.
2399
		 */
2400
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2401
	}
2402
2403
	/**
2404
	 * Checks activated modules during auto-activation to determine
2405
	 * if any of those modules are being deprecated.  If so, close
2406
	 * them out, and add any replacement modules.
2407
	 *
2408
	 * Runs at priority 99 by default.
2409
	 *
2410
	 * This is run late, so that it can still activate a module if
2411
	 * the new module is a replacement for another that the user
2412
	 * currently has active, even if something at the normal priority
2413
	 * would kibosh everything.
2414
	 *
2415
	 * @since 2.6
2416
	 * @uses jetpack_get_default_modules filter
2417
	 * @param array $modules
2418
	 * @return array
2419
	 */
2420
	function handle_deprecated_modules( $modules ) {
2421
		$deprecated_modules = array(
2422
			'debug'            => null,  // Closed out and moved to the debugger library.
2423
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2424
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2425
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2426
		);
2427
2428
		// Don't activate SSO if they never completed activating WPCC.
2429
		if ( self::is_module_active( 'wpcc' ) ) {
2430
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2431
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2432
				$deprecated_modules['wpcc'] = null;
2433
			}
2434
		}
2435
2436
		foreach ( $deprecated_modules as $module => $replacement ) {
2437
			if ( self::is_module_active( $module ) ) {
2438
				self::deactivate_module( $module );
2439
				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...
2440
					$modules[] = $replacement;
2441
				}
2442
			}
2443
		}
2444
2445
		return array_unique( $modules );
2446
	}
2447
2448
	/**
2449
	 * Checks activated plugins during auto-activation to determine
2450
	 * if any of those plugins are in the list with a corresponding module
2451
	 * that is not compatible with the plugin. The module will not be allowed
2452
	 * to auto-activate.
2453
	 *
2454
	 * @since 2.6
2455
	 * @uses jetpack_get_default_modules filter
2456
	 * @param array $modules
2457
	 * @return array
2458
	 */
2459
	function filter_default_modules( $modules ) {
2460
2461
		$active_plugins = self::get_active_plugins();
2462
2463
		if ( ! empty( $active_plugins ) ) {
2464
2465
			// For each module we'd like to auto-activate...
2466
			foreach ( $modules as $key => $module ) {
2467
				// If there are potential conflicts for it...
2468
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2469
					// For each potential conflict...
2470
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2471
						// If that conflicting plugin is active...
2472
						if ( in_array( $plugin, $active_plugins ) ) {
2473
							// Remove that item from being auto-activated.
2474
							unset( $modules[ $key ] );
2475
						}
2476
					}
2477
				}
2478
			}
2479
		}
2480
2481
		return $modules;
2482
	}
2483
2484
	/**
2485
	 * Extract a module's slug from its full path.
2486
	 */
2487
	public static function get_module_slug( $file ) {
2488
		return str_replace( '.php', '', basename( $file ) );
2489
	}
2490
2491
	/**
2492
	 * Generate a module's path from its slug.
2493
	 */
2494
	public static function get_module_path( $slug ) {
2495
		/**
2496
		 * Filters the path of a modules.
2497
		 *
2498
		 * @since 7.4.0
2499
		 *
2500
		 * @param array $return The absolute path to a module's root php file
2501
		 * @param string $slug The module slug
2502
		 */
2503
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2504
	}
2505
2506
	/**
2507
	 * Load module data from module file. Headers differ from WordPress
2508
	 * plugin headers to avoid them being identified as standalone
2509
	 * plugins on the WordPress plugins page.
2510
	 */
2511
	public static function get_module( $module ) {
2512
		$headers = array(
2513
			'name'                      => 'Module Name',
2514
			'description'               => 'Module Description',
2515
			'sort'                      => 'Sort Order',
2516
			'recommendation_order'      => 'Recommendation Order',
2517
			'introduced'                => 'First Introduced',
2518
			'changed'                   => 'Major Changes In',
2519
			'deactivate'                => 'Deactivate',
2520
			'free'                      => 'Free',
2521
			'requires_connection'       => 'Requires Connection',
2522
			'auto_activate'             => 'Auto Activate',
2523
			'module_tags'               => 'Module Tags',
2524
			'feature'                   => 'Feature',
2525
			'additional_search_queries' => 'Additional Search Queries',
2526
			'plan_classes'              => 'Plans',
2527
		);
2528
2529
		$file = self::get_module_path( self::get_module_slug( $module ) );
2530
2531
		$mod = self::get_file_data( $file, $headers );
2532
		if ( empty( $mod['name'] ) ) {
2533
			return false;
2534
		}
2535
2536
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2537
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2538
		$mod['deactivate']           = empty( $mod['deactivate'] );
2539
		$mod['free']                 = empty( $mod['free'] );
2540
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2541
2542
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2543
			$mod['auto_activate'] = 'No';
2544
		} else {
2545
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2546
		}
2547
2548
		if ( $mod['module_tags'] ) {
2549
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2550
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2551
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2552
		} else {
2553
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2554
		}
2555
2556 View Code Duplication
		if ( $mod['plan_classes'] ) {
2557
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2558
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2559
		} else {
2560
			$mod['plan_classes'] = array( 'free' );
2561
		}
2562
2563 View Code Duplication
		if ( $mod['feature'] ) {
2564
			$mod['feature'] = explode( ',', $mod['feature'] );
2565
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2566
		} else {
2567
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2568
		}
2569
2570
		/**
2571
		 * Filters the feature array on a module.
2572
		 *
2573
		 * This filter allows you to control where each module is filtered: Recommended,
2574
		 * and the default "Other" listing.
2575
		 *
2576
		 * @since 3.5.0
2577
		 *
2578
		 * @param array   $mod['feature'] The areas to feature this module:
2579
		 *     'Recommended' shows on the main Jetpack admin screen.
2580
		 *     'Other' should be the default if no other value is in the array.
2581
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2582
		 * @param array   $mod All the currently assembled module data.
2583
		 */
2584
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2585
2586
		/**
2587
		 * Filter the returned data about a module.
2588
		 *
2589
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2590
		 * so please be careful.
2591
		 *
2592
		 * @since 3.6.0
2593
		 *
2594
		 * @param array   $mod    The details of the requested module.
2595
		 * @param string  $module The slug of the module, e.g. sharedaddy
2596
		 * @param string  $file   The path to the module source file.
2597
		 */
2598
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2599
	}
2600
2601
	/**
2602
	 * Like core's get_file_data implementation, but caches the result.
2603
	 */
2604
	public static function get_file_data( $file, $headers ) {
2605
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2606
		$file_name = basename( $file );
2607
2608
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2609
2610
		$file_data_option = get_transient( $cache_key );
2611
2612
		if ( ! is_array( $file_data_option ) ) {
2613
			delete_transient( $cache_key );
2614
			$file_data_option = false;
2615
		}
2616
2617
		if ( false === $file_data_option ) {
2618
			$file_data_option = array();
2619
		}
2620
2621
		$key           = md5( $file_name . serialize( $headers ) );
2622
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2623
2624
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2625
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2626
			return $file_data_option[ $key ];
2627
		}
2628
2629
		$data = get_file_data( $file, $headers );
2630
2631
		$file_data_option[ $key ] = $data;
2632
2633
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2634
2635
		return $data;
2636
	}
2637
2638
2639
	/**
2640
	 * Return translated module tag.
2641
	 *
2642
	 * @param string $tag Tag as it appears in each module heading.
2643
	 *
2644
	 * @return mixed
2645
	 */
2646
	public static function translate_module_tag( $tag ) {
2647
		return jetpack_get_module_i18n_tag( $tag );
2648
	}
2649
2650
	/**
2651
	 * Get i18n strings as a JSON-encoded string
2652
	 *
2653
	 * @return string The locale as JSON
2654
	 */
2655
	public static function get_i18n_data_json() {
2656
2657
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2658
		// JSON files with the file they should be included for. This is an md5
2659
		// of '_inc/build/admin.js'.
2660
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2661
2662
		$i18n_json =
2663
				   JETPACK__PLUGIN_DIR
2664
				   . 'languages/json/jetpack-'
2665
				   . get_user_locale()
2666
				   . '-'
2667
				   . $path_md5
2668
				   . '.json';
2669
2670
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2671
			$locale_data = @file_get_contents( $i18n_json );
2672
			if ( $locale_data ) {
2673
				return $locale_data;
2674
			}
2675
		}
2676
2677
		// Return valid empty Jed locale
2678
		return '{ "locale_data": { "messages": { "": {} } } }';
2679
	}
2680
2681
	/**
2682
	 * Add locale data setup to wp-i18n
2683
	 *
2684
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2685
	 *
2686
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2687
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2688
	 *
2689
	 * This method provides a safe way to request the setup multiple times but add the script at
2690
	 * most once.
2691
	 *
2692
	 * @since 6.7.0
2693
	 *
2694
	 * @return void
2695
	 */
2696
	public static function setup_wp_i18n_locale_data() {
2697
		static $script_added = false;
2698
		if ( ! $script_added ) {
2699
			$script_added = true;
2700
			wp_add_inline_script(
2701
				'wp-i18n',
2702
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2703
			);
2704
		}
2705
	}
2706
2707
	/**
2708
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2709
	 *
2710
	 * @since 3.9.2
2711
	 *
2712
	 * @param array $modules
2713
	 *
2714
	 * @return string|void
2715
	 */
2716
	public static function get_translated_modules( $modules ) {
2717
		foreach ( $modules as $index => $module ) {
2718
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2719
			if ( isset( $module['name'] ) ) {
2720
				$modules[ $index ]['name'] = $i18n_module['name'];
2721
			}
2722
			if ( isset( $module['description'] ) ) {
2723
				$modules[ $index ]['description']       = $i18n_module['description'];
2724
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2725
			}
2726
		}
2727
		return $modules;
2728
	}
2729
2730
	/**
2731
	 * Get a list of activated modules as an array of module slugs.
2732
	 */
2733
	public static function get_active_modules() {
2734
		$active = Jetpack_Options::get_option( 'active_modules' );
2735
2736
		if ( ! is_array( $active ) ) {
2737
			$active = array();
2738
		}
2739
2740
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2741
			$active[] = 'vaultpress';
2742
		} else {
2743
			$active = array_diff( $active, array( 'vaultpress' ) );
2744
		}
2745
2746
		// If protect is active on the main site of a multisite, it should be active on all sites.
2747
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2748
			$active[] = 'protect';
2749
		}
2750
2751
		/**
2752
		 * Allow filtering of the active modules.
2753
		 *
2754
		 * Gives theme and plugin developers the power to alter the modules that
2755
		 * are activated on the fly.
2756
		 *
2757
		 * @since 5.8.0
2758
		 *
2759
		 * @param array $active Array of active module slugs.
2760
		 */
2761
		$active = apply_filters( 'jetpack_active_modules', $active );
2762
2763
		return array_unique( $active );
2764
	}
2765
2766
	/**
2767
	 * Check whether or not a Jetpack module is active.
2768
	 *
2769
	 * @param string $module The slug of a Jetpack module.
2770
	 * @return bool
2771
	 *
2772
	 * @static
2773
	 */
2774
	public static function is_module_active( $module ) {
2775
		return in_array( $module, self::get_active_modules() );
2776
	}
2777
2778
	public static function is_module( $module ) {
2779
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2780
	}
2781
2782
	/**
2783
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2784
	 *
2785
	 * @param bool $catch True to start catching, False to stop.
2786
	 *
2787
	 * @static
2788
	 */
2789
	public static function catch_errors( $catch ) {
2790
		static $display_errors, $error_reporting;
2791
2792
		if ( $catch ) {
2793
			$display_errors  = @ini_set( 'display_errors', 1 );
2794
			$error_reporting = @error_reporting( E_ALL );
2795
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2796
		} else {
2797
			@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...
2798
			@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...
2799
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2800
		}
2801
	}
2802
2803
	/**
2804
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2805
	 */
2806
	public static function catch_errors_on_shutdown() {
2807
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2808
	}
2809
2810
	/**
2811
	 * Rewrite any string to make paths easier to read.
2812
	 *
2813
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2814
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2815
	 *
2816
	 * @param $string
2817
	 * @return mixed
2818
	 */
2819
	public static function alias_directories( $string ) {
2820
		// ABSPATH has a trailing slash.
2821
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2822
		// WP_CONTENT_DIR does not have a trailing slash.
2823
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2824
2825
		return $string;
2826
	}
2827
2828
	public static function activate_default_modules(
2829
		$min_version = false,
2830
		$max_version = false,
2831
		$other_modules = array(),
2832
		$redirect = null,
2833
		$send_state_messages = null
2834
	) {
2835
		$jetpack = self::init();
2836
2837
		if ( is_null( $redirect ) ) {
2838
			if (
2839
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2840
			||
2841
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2842
			||
2843
				( defined( 'WP_CLI' ) && WP_CLI )
2844
			||
2845
				( defined( 'DOING_CRON' ) && DOING_CRON )
2846
			||
2847
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2848
			) {
2849
				$redirect = false;
2850
			} elseif ( is_admin() ) {
2851
				$redirect = true;
2852
			} else {
2853
				$redirect = false;
2854
			}
2855
		}
2856
2857
		if ( is_null( $send_state_messages ) ) {
2858
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2859
		}
2860
2861
		$modules = self::get_default_modules( $min_version, $max_version );
2862
		$modules = array_merge( $other_modules, $modules );
2863
2864
		// Look for standalone plugins and disable if active.
2865
2866
		$to_deactivate = array();
2867
		foreach ( $modules as $module ) {
2868
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2869
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2870
			}
2871
		}
2872
2873
		$deactivated = array();
2874
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2875
			list( $probable_file, $probable_title ) = $deactivate_me;
2876
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2877
				$deactivated[] = $module;
2878
			}
2879
		}
2880
2881
		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...
2882
			if ( $send_state_messages ) {
2883
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2884
			}
2885
2886
			if ( $redirect ) {
2887
				$url = add_query_arg(
2888
					array(
2889
						'action'   => 'activate_default_modules',
2890
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2891
					),
2892
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2893
				);
2894
				wp_safe_redirect( $url );
2895
				exit;
2896
			}
2897
		}
2898
2899
		/**
2900
		 * Fires before default modules are activated.
2901
		 *
2902
		 * @since 1.9.0
2903
		 *
2904
		 * @param string $min_version Minimum version number required to use modules.
2905
		 * @param string $max_version Maximum version number required to use modules.
2906
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2907
		 */
2908
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2909
2910
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2911
		if ( $send_state_messages ) {
2912
			self::restate();
2913
			self::catch_errors( true );
2914
		}
2915
2916
		$active = self::get_active_modules();
2917
2918
		foreach ( $modules as $module ) {
2919
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2920
				$active[] = $module;
2921
				self::update_active_modules( $active );
2922
				continue;
2923
			}
2924
2925
			if ( $send_state_messages && in_array( $module, $active ) ) {
2926
				$module_info = self::get_module( $module );
2927 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2928
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2929
					if ( $active_state = self::state( $state ) ) {
2930
						$active_state = explode( ',', $active_state );
2931
					} else {
2932
						$active_state = array();
2933
					}
2934
					$active_state[] = $module;
2935
					self::state( $state, implode( ',', $active_state ) );
2936
				}
2937
				continue;
2938
			}
2939
2940
			$file = self::get_module_path( $module );
2941
			if ( ! file_exists( $file ) ) {
2942
				continue;
2943
			}
2944
2945
			// we'll override this later if the plugin can be included without fatal error
2946
			if ( $redirect ) {
2947
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2948
			}
2949
2950
			if ( $send_state_messages ) {
2951
				self::state( 'error', 'module_activation_failed' );
2952
				self::state( 'module', $module );
2953
			}
2954
2955
			ob_start();
2956
			require_once $file;
2957
2958
			$active[] = $module;
2959
2960 View Code Duplication
			if ( $send_state_messages ) {
2961
2962
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2963
				if ( $active_state = self::state( $state ) ) {
2964
					$active_state = explode( ',', $active_state );
2965
				} else {
2966
					$active_state = array();
2967
				}
2968
				$active_state[] = $module;
2969
				self::state( $state, implode( ',', $active_state ) );
2970
			}
2971
2972
			self::update_active_modules( $active );
2973
2974
			ob_end_clean();
2975
		}
2976
2977
		if ( $send_state_messages ) {
2978
			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...
2979
			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...
2980
		}
2981
2982
		self::catch_errors( false );
2983
		/**
2984
		 * Fires when default modules are activated.
2985
		 *
2986
		 * @since 1.9.0
2987
		 *
2988
		 * @param string $min_version Minimum version number required to use modules.
2989
		 * @param string $max_version Maximum version number required to use modules.
2990
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2991
		 */
2992
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2993
	}
2994
2995
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2996
		/**
2997
		 * Fires before a module is activated.
2998
		 *
2999
		 * @since 2.6.0
3000
		 *
3001
		 * @param string $module Module slug.
3002
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3003
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3004
		 */
3005
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3006
3007
		$jetpack = self::init();
3008
3009
		if ( ! strlen( $module ) ) {
3010
			return false;
3011
		}
3012
3013
		if ( ! self::is_module( $module ) ) {
3014
			return false;
3015
		}
3016
3017
		// If it's already active, then don't do it again
3018
		$active = self::get_active_modules();
3019
		foreach ( $active as $act ) {
3020
			if ( $act == $module ) {
3021
				return true;
3022
			}
3023
		}
3024
3025
		$module_data = self::get_module( $module );
3026
3027
		$is_development_mode = ( new Status() )->is_development_mode();
3028
		if ( ! self::is_active() ) {
3029
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
3030
				return false;
3031
			}
3032
3033
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3034
			if ( $is_development_mode && $module_data['requires_connection'] ) {
3035
				return false;
3036
			}
3037
		}
3038
3039
		// Check and see if the old plugin is active
3040
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3041
			// Deactivate the old plugin
3042
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3043
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3044
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3045
				self::state( 'deactivated_plugins', $module );
3046
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3047
				exit;
3048
			}
3049
		}
3050
3051
		// Protect won't work with mis-configured IPs
3052
		if ( 'protect' === $module ) {
3053
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3054
			if ( ! jetpack_protect_get_ip() ) {
3055
				self::state( 'message', 'protect_misconfigured_ip' );
3056
				return false;
3057
			}
3058
		}
3059
3060
		if ( ! Jetpack_Plan::supports( $module ) ) {
3061
			return false;
3062
		}
3063
3064
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3065
		self::state( 'module', $module );
3066
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3067
3068
		self::catch_errors( true );
3069
		ob_start();
3070
		require self::get_module_path( $module );
3071
		/** This action is documented in class.jetpack.php */
3072
		do_action( 'jetpack_activate_module', $module );
3073
		$active[] = $module;
3074
		self::update_active_modules( $active );
3075
3076
		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...
3077
		ob_end_clean();
3078
		self::catch_errors( false );
3079
3080
		if ( $redirect ) {
3081
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3082
		}
3083
		if ( $exit ) {
3084
			exit;
3085
		}
3086
		return true;
3087
	}
3088
3089
	function activate_module_actions( $module ) {
3090
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3091
	}
3092
3093
	public static function deactivate_module( $module ) {
3094
		/**
3095
		 * Fires when a module is deactivated.
3096
		 *
3097
		 * @since 1.9.0
3098
		 *
3099
		 * @param string $module Module slug.
3100
		 */
3101
		do_action( 'jetpack_pre_deactivate_module', $module );
3102
3103
		$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...
3104
3105
		$active = self::get_active_modules();
3106
		$new    = array_filter( array_diff( $active, (array) $module ) );
3107
3108
		return self::update_active_modules( $new );
3109
	}
3110
3111
	public static function enable_module_configurable( $module ) {
3112
		$module = self::get_module_slug( $module );
3113
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3114
	}
3115
3116
	/**
3117
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3118
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3119
	 *
3120
	 * @param string $module Module slug
3121
	 * @return string $url module configuration URL
3122
	 */
3123
	public static function module_configuration_url( $module ) {
3124
		$module      = self::get_module_slug( $module );
3125
		$default_url = self::admin_url() . "#/settings?term=$module";
3126
		/**
3127
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3128
		 *
3129
		 * @since 6.9.0
3130
		 *
3131
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3132
		 */
3133
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3134
3135
		return $url;
3136
	}
3137
3138
	/* Installation */
3139
	public static function bail_on_activation( $message, $deactivate = true ) {
3140
		?>
3141
<!doctype html>
3142
<html>
3143
<head>
3144
<meta charset="<?php bloginfo( 'charset' ); ?>">
3145
<style>
3146
* {
3147
	text-align: center;
3148
	margin: 0;
3149
	padding: 0;
3150
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3151
}
3152
p {
3153
	margin-top: 1em;
3154
	font-size: 18px;
3155
}
3156
</style>
3157
<body>
3158
<p><?php echo esc_html( $message ); ?></p>
3159
</body>
3160
</html>
3161
		<?php
3162
		if ( $deactivate ) {
3163
			$plugins = get_option( 'active_plugins' );
3164
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3165
			$update  = false;
3166
			foreach ( $plugins as $i => $plugin ) {
3167
				if ( $plugin === $jetpack ) {
3168
					$plugins[ $i ] = false;
3169
					$update        = true;
3170
				}
3171
			}
3172
3173
			if ( $update ) {
3174
				update_option( 'active_plugins', array_filter( $plugins ) );
3175
			}
3176
		}
3177
		exit;
3178
	}
3179
3180
	/**
3181
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3182
	 *
3183
	 * @static
3184
	 */
3185
	public static function plugin_activation( $network_wide ) {
3186
		Jetpack_Options::update_option( 'activated', 1 );
3187
3188
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3189
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3190
		}
3191
3192
		if ( $network_wide ) {
3193
			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...
3194
		}
3195
3196
		// For firing one-off events (notices) immediately after activation
3197
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3198
3199
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3200
3201
		Health::on_jetpack_activated();
3202
3203
		self::plugin_initialize();
3204
	}
3205
3206
	public static function get_activation_source( $referer_url ) {
3207
3208
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3209
			return array( 'wp-cli', null );
3210
		}
3211
3212
		$referer = wp_parse_url( $referer_url );
3213
3214
		$source_type  = 'unknown';
3215
		$source_query = null;
3216
3217
		if ( ! is_array( $referer ) ) {
3218
			return array( $source_type, $source_query );
3219
		}
3220
3221
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3222
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3223
3224
		if ( isset( $referer['query'] ) ) {
3225
			parse_str( $referer['query'], $query_parts );
3226
		} else {
3227
			$query_parts = array();
3228
		}
3229
3230
		if ( $plugins_path === $referer['path'] ) {
3231
			$source_type = 'list';
3232
		} elseif ( $plugins_install_path === $referer['path'] ) {
3233
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3234
			switch ( $tab ) {
3235
				case 'popular':
3236
					$source_type = 'popular';
3237
					break;
3238
				case 'recommended':
3239
					$source_type = 'recommended';
3240
					break;
3241
				case 'favorites':
3242
					$source_type = 'favorites';
3243
					break;
3244
				case 'search':
3245
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3246
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3247
					break;
3248
				default:
3249
					$source_type = 'featured';
3250
			}
3251
		}
3252
3253
		return array( $source_type, $source_query );
3254
	}
3255
3256
	/**
3257
	 * Runs before bumping version numbers up to a new version
3258
	 *
3259
	 * @param  string $version    Version:timestamp
3260
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3261
	 * @return null              [description]
3262
	 */
3263
	public static function do_version_bump( $version, $old_version ) {
3264
		if ( ! $old_version ) { // For new sites
3265
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3266
		}
3267
	}
3268
3269
	/**
3270
	 * Sets the internal version number and activation state.
3271
	 *
3272
	 * @static
3273
	 */
3274
	public static function plugin_initialize() {
3275
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3276
			Jetpack_Options::update_option( 'activated', 2 );
3277
		}
3278
3279 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3280
			$version = $old_version = JETPACK__VERSION . ':' . time();
3281
			/** This action is documented in class.jetpack.php */
3282
			do_action( 'updating_jetpack_version', $version, false );
3283
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3284
		}
3285
3286
		self::load_modules();
3287
3288
		Jetpack_Options::delete_option( 'do_activate' );
3289
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3290
	}
3291
3292
	/**
3293
	 * Removes all connection options
3294
	 *
3295
	 * @static
3296
	 */
3297
	public static function plugin_deactivation() {
3298
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3299
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3300
			Jetpack_Network::init()->deactivate();
3301
		} else {
3302
			self::disconnect( false );
3303
			// Jetpack_Heartbeat::init()->deactivate();
3304
		}
3305
	}
3306
3307
	/**
3308
	 * Disconnects from the Jetpack servers.
3309
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3310
	 *
3311
	 * @static
3312
	 */
3313
	public static function disconnect( $update_activated_state = true ) {
3314
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3315
		$connection = self::connection();
3316
		$connection->clean_nonces( true );
3317
3318
		// If the site is in an IDC because sync is not allowed,
3319
		// let's make sure to not disconnect the production site.
3320
		if ( ! self::validate_sync_error_idc_option() ) {
3321
			$tracking = new Tracking();
3322
			$tracking->record_user_event( 'disconnect_site', array() );
3323
3324
			$connection->disconnect_site_wpcom();
3325
		}
3326
3327
		$connection->delete_all_connection_tokens();
3328
		Jetpack_IDC::clear_all_idc_options();
3329
3330
		if ( $update_activated_state ) {
3331
			Jetpack_Options::update_option( 'activated', 4 );
3332
		}
3333
3334
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3335
			// Check then record unique disconnection if site has never been disconnected previously
3336
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3337
				$jetpack_unique_connection['disconnected'] = 1;
3338
			} else {
3339
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3340
					// track unique disconnect
3341
					$jetpack = self::init();
3342
3343
					$jetpack->stat( 'connections', 'unique-disconnect' );
3344
					$jetpack->do_stats( 'server_side' );
3345
				}
3346
				// increment number of times disconnected
3347
				$jetpack_unique_connection['disconnected'] += 1;
3348
			}
3349
3350
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3351
		}
3352
3353
		// Delete all the sync related data. Since it could be taking up space.
3354
		Sender::get_instance()->uninstall();
3355
3356
		// Disable the Heartbeat cron
3357
		Jetpack_Heartbeat::init()->deactivate();
3358
	}
3359
3360
	/**
3361
	 * Unlinks the current user from the linked WordPress.com user.
3362
	 *
3363
	 * @deprecated since 7.7
3364
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3365
	 *
3366
	 * @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...
3367
	 * @return Boolean Whether the disconnection of the user was successful.
3368
	 */
3369
	public static function unlink_user( $user_id = null ) {
3370
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3371
		return Connection_Manager::disconnect_user( $user_id );
3372
	}
3373
3374
	/**
3375
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3376
	 */
3377
	public static function try_registration() {
3378
		$terms_of_service = new Terms_Of_Service();
3379
		// The user has agreed to the TOS at some point by now.
3380
		$terms_of_service->agree();
3381
3382
		// Let's get some testing in beta versions and such.
3383
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3384
			// Before attempting to connect, let's make sure that the domains are viable.
3385
			$domains_to_check = array_unique(
3386
				array(
3387
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3388
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3389
				)
3390
			);
3391
			foreach ( $domains_to_check as $domain ) {
3392
				$result = self::connection()->is_usable_domain( $domain );
3393
				if ( is_wp_error( $result ) ) {
3394
					return $result;
3395
				}
3396
			}
3397
		}
3398
3399
		$result = self::register();
3400
3401
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3402
		if ( ! $result || is_wp_error( $result ) ) {
3403
			return $result;
3404
		} else {
3405
			return true;
3406
		}
3407
	}
3408
3409
	/**
3410
	 * Tracking an internal event log. Try not to put too much chaff in here.
3411
	 *
3412
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3413
	 */
3414
	public static function log( $code, $data = null ) {
3415
		// only grab the latest 200 entries
3416
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3417
3418
		// Append our event to the log
3419
		$log_entry = array(
3420
			'time'    => time(),
3421
			'user_id' => get_current_user_id(),
3422
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3423
			'code'    => $code,
3424
		);
3425
		// Don't bother storing it unless we've got some.
3426
		if ( ! is_null( $data ) ) {
3427
			$log_entry['data'] = $data;
3428
		}
3429
		$log[] = $log_entry;
3430
3431
		// Try add_option first, to make sure it's not autoloaded.
3432
		// @todo: Add an add_option method to Jetpack_Options
3433
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3434
			Jetpack_Options::update_option( 'log', $log );
3435
		}
3436
3437
		/**
3438
		 * Fires when Jetpack logs an internal event.
3439
		 *
3440
		 * @since 3.0.0
3441
		 *
3442
		 * @param array $log_entry {
3443
		 *  Array of details about the log entry.
3444
		 *
3445
		 *  @param string time Time of the event.
3446
		 *  @param int user_id ID of the user who trigerred the event.
3447
		 *  @param int blog_id Jetpack Blog ID.
3448
		 *  @param string code Unique name for the event.
3449
		 *  @param string data Data about the event.
3450
		 * }
3451
		 */
3452
		do_action( 'jetpack_log_entry', $log_entry );
3453
	}
3454
3455
	/**
3456
	 * Get the internal event log.
3457
	 *
3458
	 * @param $event (string) - only return the specific log events
3459
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3460
	 *
3461
	 * @return array of log events || WP_Error for invalid params
3462
	 */
3463
	public static function get_log( $event = false, $num = false ) {
3464
		if ( $event && ! is_string( $event ) ) {
3465
			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...
3466
		}
3467
3468
		if ( $num && ! is_numeric( $num ) ) {
3469
			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...
3470
		}
3471
3472
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3473
3474
		// If nothing set - act as it did before, otherwise let's start customizing the output
3475
		if ( ! $num && ! $event ) {
3476
			return $entire_log;
3477
		} else {
3478
			$entire_log = array_reverse( $entire_log );
3479
		}
3480
3481
		$custom_log_output = array();
3482
3483
		if ( $event ) {
3484
			foreach ( $entire_log as $log_event ) {
3485
				if ( $event == $log_event['code'] ) {
3486
					$custom_log_output[] = $log_event;
3487
				}
3488
			}
3489
		} else {
3490
			$custom_log_output = $entire_log;
3491
		}
3492
3493
		if ( $num ) {
3494
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3495
		}
3496
3497
		return $custom_log_output;
3498
	}
3499
3500
	/**
3501
	 * Log modification of important settings.
3502
	 */
3503
	public static function log_settings_change( $option, $old_value, $value ) {
3504
		switch ( $option ) {
3505
			case 'jetpack_sync_non_public_post_stati':
3506
				self::log( $option, $value );
3507
				break;
3508
		}
3509
	}
3510
3511
	/**
3512
	 * Return stat data for WPCOM sync
3513
	 */
3514
	public static function get_stat_data( $encode = true, $extended = true ) {
3515
		$data = Jetpack_Heartbeat::generate_stats_array();
3516
3517
		if ( $extended ) {
3518
			$additional_data = self::get_additional_stat_data();
3519
			$data            = array_merge( $data, $additional_data );
3520
		}
3521
3522
		if ( $encode ) {
3523
			return json_encode( $data );
3524
		}
3525
3526
		return $data;
3527
	}
3528
3529
	/**
3530
	 * Get additional stat data to sync to WPCOM
3531
	 */
3532
	public static function get_additional_stat_data( $prefix = '' ) {
3533
		$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...
3534
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3535
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3536
		$return[ "{$prefix}site-count" ]    = 0;
3537
3538
		if ( function_exists( 'get_blog_count' ) ) {
3539
			$return[ "{$prefix}site-count" ] = get_blog_count();
3540
		}
3541
		return $return;
3542
	}
3543
3544
	private static function get_site_user_count() {
3545
		global $wpdb;
3546
3547
		if ( function_exists( 'wp_is_large_network' ) ) {
3548
			if ( wp_is_large_network( 'users' ) ) {
3549
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3550
			}
3551
		}
3552
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3553
			// It wasn't there, so regenerate the data and save the transient
3554
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3555
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3556
		}
3557
		return $user_count;
3558
	}
3559
3560
	/* Admin Pages */
3561
3562
	function admin_init() {
3563
		// If the plugin is not connected, display a connect message.
3564
		if (
3565
			// the plugin was auto-activated and needs its candy
3566
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3567
		||
3568
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3569
			! Jetpack_Options::get_option( 'activated' )
3570
		) {
3571
			self::plugin_initialize();
3572
		}
3573
3574
		$is_development_mode = ( new Status() )->is_development_mode();
3575
		if ( ! self::is_active() && ! $is_development_mode ) {
3576
			Jetpack_Connection_Banner::init();
3577
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3578
			// Upgrade: 1.1 -> 1.1.1
3579
			// Check and see if host can verify the Jetpack servers' SSL certificate
3580
			$args       = array();
3581
			$connection = self::connection();
3582
			Client::_wp_remote_request(
3583
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3584
				$args,
3585
				true
3586
			);
3587
		}
3588
3589
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3590
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3591
		}
3592
3593
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3594
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3595
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3596
3597
		if ( self::is_active() || $is_development_mode ) {
3598
			// Artificially throw errors in certain whitelisted cases during plugin activation
3599
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3600
		}
3601
3602
		// Add custom column in wp-admin/users.php to show whether user is linked.
3603
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3604
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3605
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3606
	}
3607
3608
	function admin_body_class( $admin_body_class = '' ) {
3609
		$classes = explode( ' ', trim( $admin_body_class ) );
3610
3611
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3612
3613
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3614
		return " $admin_body_class ";
3615
	}
3616
3617
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3618
		return $admin_body_class . ' jetpack-pagestyles ';
3619
	}
3620
3621
	/**
3622
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3623
	 * This function artificially throws errors for such cases (whitelisted).
3624
	 *
3625
	 * @param string $plugin The activated plugin.
3626
	 */
3627
	function throw_error_on_activate_plugin( $plugin ) {
3628
		$active_modules = self::get_active_modules();
3629
3630
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3631
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3632
			$throw = false;
3633
3634
			// Try and make sure it really was the stats plugin
3635
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3636
				if ( 'stats.php' == basename( $plugin ) ) {
3637
					$throw = true;
3638
				}
3639
			} else {
3640
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3641
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3642
					$throw = true;
3643
				}
3644
			}
3645
3646
			if ( $throw ) {
3647
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3648
			}
3649
		}
3650
	}
3651
3652
	function intercept_plugin_error_scrape_init() {
3653
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3654
	}
3655
3656
	function intercept_plugin_error_scrape( $action, $result ) {
3657
		if ( ! $result ) {
3658
			return;
3659
		}
3660
3661
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3662
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3663
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3664
			}
3665
		}
3666
	}
3667
3668
	/**
3669
	 * Register the remote file upload request handlers, if needed.
3670
	 *
3671
	 * @access public
3672
	 */
3673
	public function add_remote_request_handlers() {
3674
		// Remote file uploads are allowed only via AJAX requests.
3675
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3676
			return;
3677
		}
3678
3679
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3680
		$remote_request_actions = array(
3681
			'jetpack_upload_file',
3682
			'jetpack_update_file',
3683
		);
3684
3685
		// phpcs:ignore WordPress.Security.NonceVerification
3686
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3687
			return;
3688
		}
3689
3690
		// Require Jetpack authentication for the remote file upload AJAX requests.
3691
		$this->connection_manager->require_jetpack_authentication();
3692
3693
		// Register the remote file upload AJAX handlers.
3694
		foreach ( $remote_request_actions as $action ) {
3695
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3696
		}
3697
	}
3698
3699
	/**
3700
	 * Handler for Jetpack remote file uploads.
3701
	 *
3702
	 * @access public
3703
	 */
3704
	public function remote_request_handlers() {
3705
		$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...
3706
3707
		switch ( current_filter() ) {
3708
			case 'wp_ajax_nopriv_jetpack_upload_file':
3709
				$response = $this->upload_handler();
3710
				break;
3711
3712
			case 'wp_ajax_nopriv_jetpack_update_file':
3713
				$response = $this->upload_handler( true );
3714
				break;
3715
			default:
3716
				$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3717
				break;
3718
		}
3719
3720
		if ( ! $response ) {
3721
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3722
		}
3723
3724
		if ( is_wp_error( $response ) ) {
3725
			$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<Jetpack_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...
3726
			$error             = $response->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<Jetpack_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...
3727
			$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<Jetpack_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...
3728
3729
			if ( ! is_int( $status_code ) ) {
3730
				$status_code = 400;
3731
			}
3732
3733
			status_header( $status_code );
3734
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3735
		}
3736
3737
		status_header( 200 );
3738
		if ( true === $response ) {
3739
			exit;
3740
		}
3741
3742
		die( json_encode( (object) $response ) );
3743
	}
3744
3745
	/**
3746
	 * Uploads a file gotten from the global $_FILES.
3747
	 * If `$update_media_item` is true and `post_id` is defined
3748
	 * the attachment file of the media item (gotten through of the post_id)
3749
	 * will be updated instead of add a new one.
3750
	 *
3751
	 * @param  boolean $update_media_item - update media attachment
3752
	 * @return array - An array describing the uploadind files process
3753
	 */
3754
	function upload_handler( $update_media_item = false ) {
3755
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3756
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3757
		}
3758
3759
		$user = wp_authenticate( '', '' );
3760
		if ( ! $user || is_wp_error( $user ) ) {
3761
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3762
		}
3763
3764
		wp_set_current_user( $user->ID );
3765
3766
		if ( ! current_user_can( 'upload_files' ) ) {
3767
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3768
		}
3769
3770
		if ( empty( $_FILES ) ) {
3771
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3772
		}
3773
3774
		foreach ( array_keys( $_FILES ) as $files_key ) {
3775
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3776
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3777
			}
3778
		}
3779
3780
		$media_keys = array_keys( $_FILES['media'] );
3781
3782
		$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...
3783
		if ( ! $token || is_wp_error( $token ) ) {
3784
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3785
		}
3786
3787
		$uploaded_files = array();
3788
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3789
		unset( $GLOBALS['post'] );
3790
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3791
			$file = array();
3792
			foreach ( $media_keys as $media_key ) {
3793
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3794
			}
3795
3796
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3797
3798
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3799
			if ( $hmac_provided !== $hmac_file ) {
3800
				$uploaded_files[ $index ] = (object) array(
3801
					'error'             => 'invalid_hmac',
3802
					'error_description' => 'The corresponding HMAC for this file does not match',
3803
				);
3804
				continue;
3805
			}
3806
3807
			$_FILES['.jetpack.upload.'] = $file;
3808
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3809
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3810
				$post_id = 0;
3811
			}
3812
3813
			if ( $update_media_item ) {
3814
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3815
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3816
				}
3817
3818
				$media_array = $_FILES['media'];
3819
3820
				$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...
3821
				$file_array['type']     = $media_array['type'][0];
3822
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3823
				$file_array['error']    = $media_array['error'][0];
3824
				$file_array['size']     = $media_array['size'][0];
3825
3826
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3827
3828
				if ( is_wp_error( $edited_media_item ) ) {
3829
					return $edited_media_item;
3830
				}
3831
3832
				$response = (object) array(
3833
					'id'   => (string) $post_id,
3834
					'file' => (string) $edited_media_item->post_title,
3835
					'url'  => (string) wp_get_attachment_url( $post_id ),
3836
					'type' => (string) $edited_media_item->post_mime_type,
3837
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3838
				);
3839
3840
				return (array) array( $response );
3841
			}
3842
3843
			$attachment_id = media_handle_upload(
3844
				'.jetpack.upload.',
3845
				$post_id,
3846
				array(),
3847
				array(
3848
					'action' => 'jetpack_upload_file',
3849
				)
3850
			);
3851
3852
			if ( ! $attachment_id ) {
3853
				$uploaded_files[ $index ] = (object) array(
3854
					'error'             => 'unknown',
3855
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3856
				);
3857
			} elseif ( is_wp_error( $attachment_id ) ) {
3858
				$uploaded_files[ $index ] = (object) array(
3859
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3860
					'error_description' => $attachment_id->get_error_message(),
3861
				);
3862
			} else {
3863
				$attachment               = get_post( $attachment_id );
3864
				$uploaded_files[ $index ] = (object) array(
3865
					'id'   => (string) $attachment_id,
3866
					'file' => $attachment->post_title,
3867
					'url'  => wp_get_attachment_url( $attachment_id ),
3868
					'type' => $attachment->post_mime_type,
3869
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3870
				);
3871
				// Zip files uploads are not supported unless they are done for installation purposed
3872
				// lets delete them in case something goes wrong in this whole process
3873
				if ( 'application/zip' === $attachment->post_mime_type ) {
3874
					// Schedule a cleanup for 2 hours from now in case of failed install.
3875
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3876
				}
3877
			}
3878
		}
3879
		if ( ! is_null( $global_post ) ) {
3880
			$GLOBALS['post'] = $global_post;
3881
		}
3882
3883
		return $uploaded_files;
3884
	}
3885
3886
	/**
3887
	 * Add help to the Jetpack page
3888
	 *
3889
	 * @since Jetpack (1.2.3)
3890
	 * @return false if not the Jetpack page
3891
	 */
3892
	function admin_help() {
3893
		$current_screen = get_current_screen();
3894
3895
		// Overview
3896
		$current_screen->add_help_tab(
3897
			array(
3898
				'id'      => 'home',
3899
				'title'   => __( 'Home', 'jetpack' ),
3900
				'content' =>
3901
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3902
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3903
					'<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>',
3904
			)
3905
		);
3906
3907
		// Screen Content
3908
		if ( current_user_can( 'manage_options' ) ) {
3909
			$current_screen->add_help_tab(
3910
				array(
3911
					'id'      => 'settings',
3912
					'title'   => __( 'Settings', 'jetpack' ),
3913
					'content' =>
3914
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3915
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3916
						'<ol>' .
3917
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3918
							'<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>' .
3919
						'</ol>' .
3920
						'<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>',
3921
				)
3922
			);
3923
		}
3924
3925
		// Help Sidebar
3926
		$current_screen->set_help_sidebar(
3927
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3928
			'<p><a href="https://jetpack.com/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3929
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3930
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3931
		);
3932
	}
3933
3934
	function admin_menu_css() {
3935
		wp_enqueue_style( 'jetpack-icons' );
3936
	}
3937
3938
	function admin_menu_order() {
3939
		return true;
3940
	}
3941
3942 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3943
		$jp_menu_order = array();
3944
3945
		foreach ( $menu_order as $index => $item ) {
3946
			if ( $item != 'jetpack' ) {
3947
				$jp_menu_order[] = $item;
3948
			}
3949
3950
			if ( $index == 0 ) {
3951
				$jp_menu_order[] = 'jetpack';
3952
			}
3953
		}
3954
3955
		return $jp_menu_order;
3956
	}
3957
3958
	function admin_banner_styles() {
3959
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3960
3961 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3962
			wp_register_style(
3963
				'jetpack-dops-style',
3964
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3965
				array(),
3966
				JETPACK__VERSION
3967
			);
3968
		}
3969
3970
		wp_enqueue_style(
3971
			'jetpack',
3972
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3973
			array( 'jetpack-dops-style' ),
3974
			JETPACK__VERSION . '-20121016'
3975
		);
3976
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3977
		wp_style_add_data( 'jetpack', 'suffix', $min );
3978
	}
3979
3980
	function plugin_action_links( $actions ) {
3981
3982
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3983
3984
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
3985
			return array_merge(
3986
				$jetpack_home,
3987
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3988
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3989
				$actions
3990
			);
3991
		}
3992
3993
		return array_merge( $jetpack_home, $actions );
3994
	}
3995
3996
	/*
3997
	 * Registration flow:
3998
	 * 1 - ::admin_page_load() action=register
3999
	 * 2 - ::try_registration()
4000
	 * 3 - ::register()
4001
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4002
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4003
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4004
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4005
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4006
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4007
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4008
	 *       jetpack_id, jetpack_secret, jetpack_public
4009
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4010
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4011
	 * 5 - user logs in with WP.com account
4012
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4013
	 *		- Manager::authorize()
4014
	 *		- Manager::get_token()
4015
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4016
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4017
	 *			- which responds with access_token, token_type, scope
4018
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4019
	 *		- Jetpack::activate_default_modules()
4020
	 *     		- Deactivates deprecated plugins
4021
	 *     		- Activates all default modules
4022
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4023
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4024
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4025
	 *     Done!
4026
	 */
4027
4028
	/**
4029
	 * Handles the page load events for the Jetpack admin page
4030
	 */
4031
	function admin_page_load() {
4032
		$error = false;
4033
4034
		// Make sure we have the right body class to hook stylings for subpages off of.
4035
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4036
4037
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4038
			// Should only be used in intermediate redirects to preserve state across redirects
4039
			self::restate();
4040
		}
4041
4042
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4043
			// @todo: Add validation against a known whitelist
4044
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4045
			// User clicked in the iframe to link their accounts
4046
			if ( ! self::is_user_connected() ) {
4047
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4048
4049
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4050
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4051
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4052
4053
				if ( isset( $_GET['notes_iframe'] ) ) {
4054
					$connect_url .= '&notes_iframe';
4055
				}
4056
				wp_redirect( $connect_url );
4057
				exit;
4058
			} else {
4059
				if ( ! isset( $_GET['calypso_env'] ) ) {
4060
					self::state( 'message', 'already_authorized' );
4061
					wp_safe_redirect( self::admin_url() );
4062
					exit;
4063
				} else {
4064
					$connect_url  = $this->build_connect_url( true, false, $from );
4065
					$connect_url .= '&already_authorized=true';
4066
					wp_redirect( $connect_url );
4067
					exit;
4068
				}
4069
			}
4070
		}
4071
4072
		if ( isset( $_GET['action'] ) ) {
4073
			switch ( $_GET['action'] ) {
4074
				case 'authorize':
4075
					if ( self::is_active() && self::is_user_connected() ) {
4076
						self::state( 'message', 'already_authorized' );
4077
						wp_safe_redirect( self::admin_url() );
4078
						exit;
4079
					}
4080
					self::log( 'authorize' );
4081
					$client_server = new Jetpack_Client_Server();
4082
					$client_server->client_authorize();
4083
					exit;
4084
				case 'register':
4085
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4086
						$error = 'cheatin';
4087
						break;
4088
					}
4089
					check_admin_referer( 'jetpack-register' );
4090
					self::log( 'register' );
4091
					self::maybe_set_version_option();
4092
					$registered = self::try_registration();
4093 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4094
						$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...
4095
						self::state( 'error', $error );
4096
						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...
4097
4098
						/**
4099
						 * Jetpack registration Error.
4100
						 *
4101
						 * @since 7.5.0
4102
						 *
4103
						 * @param string|int $error The error code.
4104
						 * @param \WP_Error $registered The error object.
4105
						 */
4106
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4107
						break;
4108
					}
4109
4110
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4111
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4112
4113
					/**
4114
					 * Jetpack registration Success.
4115
					 *
4116
					 * @since 7.5.0
4117
					 *
4118
					 * @param string $from 'from' GET parameter;
4119
					 */
4120
					do_action( 'jetpack_connection_register_success', $from );
4121
4122
					$url = $this->build_connect_url( true, $redirect, $from );
4123
4124
					if ( ! empty( $_GET['onboarding'] ) ) {
4125
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4126
					}
4127
4128
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4129
						$url = add_query_arg( 'auth_approved', 'true', $url );
4130
					}
4131
4132
					wp_redirect( $url );
4133
					exit;
4134
				case 'activate':
4135
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4136
						$error = 'cheatin';
4137
						break;
4138
					}
4139
4140
					$module = stripslashes( $_GET['module'] );
4141
					check_admin_referer( "jetpack_activate-$module" );
4142
					self::log( 'activate', $module );
4143
					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...
4144
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4145
					}
4146
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4147
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4148
					exit;
4149
				case 'activate_default_modules':
4150
					check_admin_referer( 'activate_default_modules' );
4151
					self::log( 'activate_default_modules' );
4152
					self::restate();
4153
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4154
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4155
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4156
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4157
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4158
					exit;
4159
				case 'disconnect':
4160
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4161
						$error = 'cheatin';
4162
						break;
4163
					}
4164
4165
					check_admin_referer( 'jetpack-disconnect' );
4166
					self::log( 'disconnect' );
4167
					self::disconnect();
4168
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4169
					exit;
4170
				case 'reconnect':
4171
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4172
						$error = 'cheatin';
4173
						break;
4174
					}
4175
4176
					check_admin_referer( 'jetpack-reconnect' );
4177
					self::log( 'reconnect' );
4178
					$this->disconnect();
4179
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4180
					exit;
4181 View Code Duplication
				case 'deactivate':
4182
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4183
						$error = 'cheatin';
4184
						break;
4185
					}
4186
4187
					$modules = stripslashes( $_GET['module'] );
4188
					check_admin_referer( "jetpack_deactivate-$modules" );
4189
					foreach ( explode( ',', $modules ) as $module ) {
4190
						self::log( 'deactivate', $module );
4191
						self::deactivate_module( $module );
4192
						self::state( 'message', 'module_deactivated' );
4193
					}
4194
					self::state( 'module', $modules );
4195
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4196
					exit;
4197
				case 'unlink':
4198
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4199
					check_admin_referer( 'jetpack-unlink' );
4200
					self::log( 'unlink' );
4201
					Connection_Manager::disconnect_user();
4202
					self::state( 'message', 'unlinked' );
4203
					if ( 'sub-unlink' == $redirect ) {
4204
						wp_safe_redirect( admin_url() );
4205
					} else {
4206
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4207
					}
4208
					exit;
4209
				case 'onboard':
4210
					if ( ! current_user_can( 'manage_options' ) ) {
4211
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4212
					} else {
4213
						self::create_onboarding_token();
4214
						$url = $this->build_connect_url( true );
4215
4216
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4217
							$url = add_query_arg( 'onboarding', $token, $url );
4218
						}
4219
4220
						$calypso_env = $this->get_calypso_env();
4221
						if ( ! empty( $calypso_env ) ) {
4222
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4223
						}
4224
4225
						wp_redirect( $url );
4226
						exit;
4227
					}
4228
					exit;
4229
				default:
4230
					/**
4231
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4232
					 *
4233
					 * @since 2.6.0
4234
					 *
4235
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4236
					 */
4237
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4238
			}
4239
		}
4240
4241
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4242
			self::activate_new_modules( true );
4243
		}
4244
4245
		$message_code = self::state( 'message' );
4246
		if ( self::state( 'optin-manage' ) ) {
4247
			$activated_manage = $message_code;
4248
			$message_code     = 'jetpack-manage';
4249
		}
4250
4251
		switch ( $message_code ) {
4252
			case 'jetpack-manage':
4253
				$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' ), 'https://wordpress.com/sites' ) . '</strong>';
4254
				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...
4255
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4256
				}
4257
				break;
4258
4259
		}
4260
4261
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4262
4263
		if ( ! empty( $deactivated_plugins ) ) {
4264
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4265
			$deactivated_titles  = array();
4266
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4267
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4268
					continue;
4269
				}
4270
4271
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4272
			}
4273
4274
			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...
4275
				if ( $this->message ) {
4276
					$this->message .= "<br /><br />\n";
4277
				}
4278
4279
				$this->message .= wp_sprintf(
4280
					_n(
4281
						'Jetpack contains the most recent version of the old %l plugin.',
4282
						'Jetpack contains the most recent versions of the old %l plugins.',
4283
						count( $deactivated_titles ),
4284
						'jetpack'
4285
					),
4286
					$deactivated_titles
4287
				);
4288
4289
				$this->message .= "<br />\n";
4290
4291
				$this->message .= _n(
4292
					'The old version has been deactivated and can be removed from your site.',
4293
					'The old versions have been deactivated and can be removed from your site.',
4294
					count( $deactivated_titles ),
4295
					'jetpack'
4296
				);
4297
			}
4298
		}
4299
4300
		$this->privacy_checks = self::state( 'privacy_checks' );
4301
4302
		if ( $this->message || $this->error || $this->privacy_checks ) {
4303
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4304
		}
4305
4306
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4307
	}
4308
4309
	function admin_notices() {
4310
4311
		if ( $this->error ) {
4312
			?>
4313
<div id="message" class="jetpack-message jetpack-err">
4314
	<div class="squeezer">
4315
		<h2>
4316
			<?php
4317
			echo wp_kses(
4318
				$this->error,
4319
				array(
4320
					'a'      => array( 'href' => array() ),
4321
					'small'  => true,
4322
					'code'   => true,
4323
					'strong' => true,
4324
					'br'     => true,
4325
					'b'      => true,
4326
				)
4327
			);
4328
			?>
4329
			</h2>
4330
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4331
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4332
<?php	endif; ?>
4333
	</div>
4334
</div>
4335
			<?php
4336
		}
4337
4338
		if ( $this->message ) {
4339
			?>
4340
<div id="message" class="jetpack-message">
4341
	<div class="squeezer">
4342
		<h2>
4343
			<?php
4344
			echo wp_kses(
4345
				$this->message,
4346
				array(
4347
					'strong' => array(),
4348
					'a'      => array( 'href' => true ),
4349
					'br'     => true,
4350
				)
4351
			);
4352
			?>
4353
			</h2>
4354
	</div>
4355
</div>
4356
			<?php
4357
		}
4358
4359
		if ( $this->privacy_checks ) :
4360
			$module_names = $module_slugs = array();
4361
4362
			$privacy_checks = explode( ',', $this->privacy_checks );
4363
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4364
			foreach ( $privacy_checks as $module_slug ) {
4365
				$module = self::get_module( $module_slug );
4366
				if ( ! $module ) {
4367
					continue;
4368
				}
4369
4370
				$module_slugs[] = $module_slug;
4371
				$module_names[] = "<strong>{$module['name']}</strong>";
4372
			}
4373
4374
			$module_slugs = join( ',', $module_slugs );
4375
			?>
4376
<div id="message" class="jetpack-message jetpack-err">
4377
	<div class="squeezer">
4378
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4379
		<p>
4380
			<?php
4381
			echo wp_kses(
4382
				wptexturize(
4383
					wp_sprintf(
4384
						_nx(
4385
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4386
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4387
							count( $privacy_checks ),
4388
							'%l = list of Jetpack module/feature names',
4389
							'jetpack'
4390
						),
4391
						$module_names
4392
					)
4393
				),
4394
				array( 'strong' => true )
4395
			);
4396
4397
			echo "\n<br />\n";
4398
4399
			echo wp_kses(
4400
				sprintf(
4401
					_nx(
4402
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4403
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4404
						count( $privacy_checks ),
4405
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4406
						'jetpack'
4407
					),
4408
					wp_nonce_url(
4409
						self::admin_url(
4410
							array(
4411
								'page'   => 'jetpack',
4412
								'action' => 'deactivate',
4413
								'module' => urlencode( $module_slugs ),
4414
							)
4415
						),
4416
						"jetpack_deactivate-$module_slugs"
4417
					),
4418
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4419
				),
4420
				array(
4421
					'a' => array(
4422
						'href'  => true,
4423
						'title' => true,
4424
					),
4425
				)
4426
			);
4427
			?>
4428
		</p>
4429
	</div>
4430
</div>
4431
			<?php
4432
endif;
4433
	}
4434
4435
	/**
4436
	 * We can't always respond to a signed XML-RPC request with a
4437
	 * helpful error message. In some circumstances, doing so could
4438
	 * leak information.
4439
	 *
4440
	 * Instead, track that the error occurred via a Jetpack_Option,
4441
	 * and send that data back in the heartbeat.
4442
	 * All this does is increment a number, but it's enough to find
4443
	 * trends.
4444
	 *
4445
	 * @param WP_Error $xmlrpc_error The error produced during
4446
	 *                               signature validation.
4447
	 */
4448
	function track_xmlrpc_error( $xmlrpc_error ) {
4449
		$code = is_wp_error( $xmlrpc_error )
4450
			? $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...
4451
			: 'should-not-happen';
4452
4453
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4454
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4455
			// No need to update the option if we already have
4456
			// this code stored.
4457
			return;
4458
		}
4459
		$xmlrpc_errors[ $code ] = true;
4460
4461
		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...
4462
	}
4463
4464
	/**
4465
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4466
	 */
4467
	function stat( $group, $detail ) {
4468
		if ( ! isset( $this->stats[ $group ] ) ) {
4469
			$this->stats[ $group ] = array();
4470
		}
4471
		$this->stats[ $group ][] = $detail;
4472
	}
4473
4474
	/**
4475
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4476
	 */
4477
	function do_stats( $method = '' ) {
4478
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4479
			foreach ( $this->stats as $group => $stats ) {
4480
				if ( is_array( $stats ) && count( $stats ) ) {
4481
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4482
					if ( 'server_side' === $method ) {
4483
						self::do_server_side_stat( $args );
4484
					} else {
4485
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4486
					}
4487
				}
4488
				unset( $this->stats[ $group ] );
4489
			}
4490
		}
4491
	}
4492
4493
	/**
4494
	 * Runs stats code for a one-off, server-side.
4495
	 *
4496
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4497
	 *
4498
	 * @return bool If it worked.
4499
	 */
4500
	static function do_server_side_stat( $args ) {
4501
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4502
		if ( is_wp_error( $response ) ) {
4503
			return false;
4504
		}
4505
4506
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4507
			return false;
4508
		}
4509
4510
		return true;
4511
	}
4512
4513
	/**
4514
	 * Builds the stats url.
4515
	 *
4516
	 * @param $args array|string The arguments to append to the URL.
4517
	 *
4518
	 * @return string The URL to be pinged.
4519
	 */
4520
	static function build_stats_url( $args ) {
4521
		$defaults = array(
4522
			'v'    => 'wpcom2',
4523
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4524
		);
4525
		$args     = wp_parse_args( $args, $defaults );
4526
		/**
4527
		 * Filter the URL used as the Stats tracking pixel.
4528
		 *
4529
		 * @since 2.3.2
4530
		 *
4531
		 * @param string $url Base URL used as the Stats tracking pixel.
4532
		 */
4533
		$base_url = apply_filters(
4534
			'jetpack_stats_base_url',
4535
			'https://pixel.wp.com/g.gif'
4536
		);
4537
		$url      = add_query_arg( $args, $base_url );
4538
		return $url;
4539
	}
4540
4541
	/**
4542
	 * Get the role of the current user.
4543
	 *
4544
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4545
	 *
4546
	 * @access public
4547
	 * @static
4548
	 *
4549
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4550
	 */
4551
	public static function translate_current_user_to_role() {
4552
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4553
4554
		$roles = new Roles();
4555
		return $roles->translate_current_user_to_role();
4556
	}
4557
4558
	/**
4559
	 * Get the role of a particular user.
4560
	 *
4561
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4562
	 *
4563
	 * @access public
4564
	 * @static
4565
	 *
4566
	 * @param \WP_User $user User object.
4567
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4568
	 */
4569
	public static function translate_user_to_role( $user ) {
4570
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4571
4572
		$roles = new Roles();
4573
		return $roles->translate_user_to_role( $user );
4574
	}
4575
4576
	/**
4577
	 * Get the minimum capability for a role.
4578
	 *
4579
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4580
	 *
4581
	 * @access public
4582
	 * @static
4583
	 *
4584
	 * @param string $role Role name.
4585
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4586
	 */
4587
	public static function translate_role_to_cap( $role ) {
4588
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4589
4590
		$roles = new Roles();
4591
		return $roles->translate_role_to_cap( $role );
4592
	}
4593
4594
	/**
4595
	 * Sign a user role with the master access token.
4596
	 * If not specified, will default to the current user.
4597
	 *
4598
	 * @deprecated since 7.7
4599
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4600
	 *
4601
	 * @access public
4602
	 * @static
4603
	 *
4604
	 * @param string $role    User role.
4605
	 * @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...
4606
	 * @return string Signed user role.
4607
	 */
4608
	public static function sign_role( $role, $user_id = null ) {
4609
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4610
		return self::connection()->sign_role( $role, $user_id );
4611
	}
4612
4613
	/**
4614
	 * Builds a URL to the Jetpack connection auth page
4615
	 *
4616
	 * @since 3.9.5
4617
	 *
4618
	 * @param bool        $raw If true, URL will not be escaped.
4619
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4620
	 *                              If string, will be a custom redirect.
4621
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4622
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4623
	 *
4624
	 * @return string Connect URL
4625
	 */
4626
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4627
		$site_id    = Jetpack_Options::get_option( 'id' );
4628
		$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...
4629
4630
		if ( $register || ! $blog_token || ! $site_id ) {
4631
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4632
4633
			if ( ! empty( $redirect ) ) {
4634
				$url = add_query_arg(
4635
					'redirect',
4636
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4637
					$url
4638
				);
4639
			}
4640
4641
			if ( is_network_admin() ) {
4642
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4643
			}
4644
4645
			$calypso_env = self::get_calypso_env();
4646
4647
			if ( ! empty( $calypso_env ) ) {
4648
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4649
			}
4650
		} else {
4651
4652
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4653
			// because otherwise this logic can get us in to a loop.
4654
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4655
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4656
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4657
4658
				$response = Client::wpcom_json_api_request_as_blog(
4659
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4660
					'1.1'
4661
				);
4662
4663
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4664
4665
					// Generating a register URL instead to refresh the existing token
4666
					return $this->build_connect_url( $raw, $redirect, $from, true );
4667
				}
4668
			}
4669
4670
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4626 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...
4671
		}
4672
4673
		if ( $from ) {
4674
			$url = add_query_arg( 'from', $from, $url );
4675
		}
4676
4677
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4678
		/**
4679
		 * Filter the URL used when connecting a user to a WordPress.com account.
4680
		 *
4681
		 * @since 8.1.0
4682
		 *
4683
		 * @param string $url Connection URL.
4684
		 * @param bool   $raw If true, URL will not be escaped.
4685
		 */
4686
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4687
	}
4688
4689
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4690
4691
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4692
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4693
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4694
4695
		if ( $iframe ) {
4696
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4697
		}
4698
4699
		$c8n = self::connection();
4700
		$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...
4701
4702
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4703
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4704
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4705
4706
		if ( $iframe ) {
4707
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4708
		}
4709
4710
		return $url;
4711
	}
4712
4713
	/**
4714
	 * Filters the connection URL parameter array.
4715
	 *
4716
	 * @param Array $args default URL parameters used by the package.
4717
	 * @return Array the modified URL arguments array.
4718
	 */
4719
	public static function filter_connect_request_body( $args ) {
4720
		if (
4721
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4722
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4723
		) {
4724
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4725
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4726
				? $gp_locale->slug
4727
				: '';
4728
		}
4729
4730
		$tracking        = new Tracking();
4731
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4732
4733
		$args = array_merge(
4734
			$args,
4735
			array(
4736
				'_ui' => $tracks_identity['_ui'],
4737
				'_ut' => $tracks_identity['_ut'],
4738
			)
4739
		);
4740
4741
		$calypso_env = self::get_calypso_env();
4742
4743
		if ( ! empty( $calypso_env ) ) {
4744
			$args['calypso_env'] = $calypso_env;
4745
		}
4746
4747
		return $args;
4748
	}
4749
4750
	/**
4751
	 * Filters the URL that will process the connection data. It can be different from the URL
4752
	 * that we send the user to after everything is done.
4753
	 *
4754
	 * @param String $processing_url the default redirect URL used by the package.
4755
	 * @return String the modified URL.
4756
	 */
4757
	public static function filter_connect_processing_url( $processing_url ) {
4758
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4759
		return $processing_url;
4760
	}
4761
4762
	/**
4763
	 * Filters the redirection URL that is used for connect requests. The redirect
4764
	 * URL should return the user back to the Jetpack console.
4765
	 *
4766
	 * @param String $redirect the default redirect URL used by the package.
4767
	 * @return String the modified URL.
4768
	 */
4769
	public static function filter_connect_redirect_url( $redirect ) {
4770
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4771
		$redirect           = $redirect
4772
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4773
			: $jetpack_admin_page;
4774
4775
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4776
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4777
		}
4778
4779
		return $redirect;
4780
	}
4781
4782
	/**
4783
	 * This action fires at the beginning of the Manager::authorize method.
4784
	 */
4785
	public static function authorize_starting() {
4786
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4787
		// Checking if site has been active/connected previously before recording unique connection.
4788
		if ( ! $jetpack_unique_connection ) {
4789
			// jetpack_unique_connection option has never been set.
4790
			$jetpack_unique_connection = array(
4791
				'connected'    => 0,
4792
				'disconnected' => 0,
4793
				'version'      => '3.6.1',
4794
			);
4795
4796
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4797
4798
			// Track unique connection.
4799
			$jetpack = self::init();
4800
4801
			$jetpack->stat( 'connections', 'unique-connection' );
4802
			$jetpack->do_stats( 'server_side' );
4803
		}
4804
4805
		// Increment number of times connected.
4806
		$jetpack_unique_connection['connected'] += 1;
4807
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4808
	}
4809
4810
	/**
4811
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4812
	 * linked.
4813
	 */
4814
	public static function authorize_ending_linked() {
4815
		// Don't activate anything since we are just connecting a user.
4816
		self::state( 'message', 'linked' );
4817
	}
4818
4819
	/**
4820
	 * This action fires at the end of the Manager::authorize method when the master user is
4821
	 * authorized.
4822
	 *
4823
	 * @param array $data The request data.
4824
	 */
4825
	public static function authorize_ending_authorized( $data ) {
4826
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4827
		self::invalidate_onboarding_token();
4828
4829
		// If redirect_uri is SSO, ensure SSO module is enabled.
4830
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4831
4832
		/** This filter is documented in class.jetpack-cli.php */
4833
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4834
4835
		$activate_sso = (
4836
			isset( $redirect_options['action'] ) &&
4837
			'jetpack-sso' === $redirect_options['action'] &&
4838
			$jetpack_start_enable_sso
4839
		);
4840
4841
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4842
4843
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4844
	}
4845
4846
	/**
4847
	 * Get our assumed site creation date.
4848
	 * Calculated based on the earlier date of either:
4849
	 * - Earliest admin user registration date.
4850
	 * - Earliest date of post of any post type.
4851
	 *
4852
	 * @since 7.2.0
4853
	 * @deprecated since 7.8.0
4854
	 *
4855
	 * @return string Assumed site creation date and time.
4856
	 */
4857
	public static function get_assumed_site_creation_date() {
4858
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4859
		return self::connection()->get_assumed_site_creation_date();
4860
	}
4861
4862 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4863
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4864
4865
		if ( $activation_source_name ) {
4866
			$args['_as'] = urlencode( $activation_source_name );
4867
		}
4868
4869
		if ( $activation_source_keyword ) {
4870
			$args['_ak'] = urlencode( $activation_source_keyword );
4871
		}
4872
	}
4873
4874
	function build_reconnect_url( $raw = false ) {
4875
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4876
		return $raw ? $url : esc_url( $url );
4877
	}
4878
4879
	public static function admin_url( $args = null ) {
4880
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4881
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4882
		return $url;
4883
	}
4884
4885
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4886
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4887
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4888
	}
4889
4890
	function dismiss_jetpack_notice() {
4891
4892
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4893
			return;
4894
		}
4895
4896
		switch ( $_GET['jetpack-notice'] ) {
4897
			case 'dismiss':
4898
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4899
4900
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4901
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4902
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4903
				}
4904
				break;
4905
		}
4906
	}
4907
4908
	public static function sort_modules( $a, $b ) {
4909
		if ( $a['sort'] == $b['sort'] ) {
4910
			return 0;
4911
		}
4912
4913
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4914
	}
4915
4916
	function ajax_recheck_ssl() {
4917
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4918
		$result = self::permit_ssl( true );
4919
		wp_send_json(
4920
			array(
4921
				'enabled' => $result,
4922
				'message' => get_transient( 'jetpack_https_test_message' ),
4923
			)
4924
		);
4925
	}
4926
4927
	/* Client API */
4928
4929
	/**
4930
	 * Returns the requested Jetpack API URL
4931
	 *
4932
	 * @deprecated since 7.7
4933
	 * @return string
4934
	 */
4935
	public static function api_url( $relative_url ) {
4936
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4937
		$connection = self::connection();
4938
		return $connection->api_url( $relative_url );
4939
	}
4940
4941
	/**
4942
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
4943
	 *
4944
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4945
	 */
4946
	public static function fix_url_for_bad_hosts( $url ) {
4947
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
4948
		return Connection_Utils::fix_url_for_bad_hosts( $url );
4949
	}
4950
4951
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4952
		// Default to a blog token.
4953
		$token_type = 'blog';
4954
4955
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4956
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4957
			if ( ! empty( $_GET['onboarding'] ) ) {
4958
				$jpo = $_GET;
4959
			} else {
4960
				$jpo = json_decode( $request_data, true );
4961
			}
4962
4963
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4964
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4965
4966
			if (
4967
				isset( $jpo_user )
4968
				&& isset( $jpo_token )
4969
				&& is_email( $jpo_user )
4970
				&& ctype_alnum( $jpo_token )
4971
				&& isset( $_GET['rest_route'] )
4972
				&& self::validate_onboarding_token_action(
4973
					$jpo_token,
4974
					$_GET['rest_route']
4975
				)
4976
			) {
4977
				$jp_user = get_user_by( 'email', $jpo_user );
4978
				if ( is_a( $jp_user, 'WP_User' ) ) {
4979
					wp_set_current_user( $jp_user->ID );
4980
					$user_can = is_multisite()
4981
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4982
						: current_user_can( 'manage_options' );
4983
					if ( $user_can ) {
4984
						$token_type              = 'user';
4985
						$token->external_user_id = $jp_user->ID;
4986
					}
4987
				}
4988
			}
4989
4990
			$token_data['type']    = $token_type;
4991
			$token_data['user_id'] = $token->external_user_id;
4992
		}
4993
4994
		return $token_data;
4995
	}
4996
4997
	/**
4998
	 * Create a random secret for validating onboarding payload
4999
	 *
5000
	 * @return string Secret token
5001
	 */
5002
	public static function create_onboarding_token() {
5003
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5004
			$token = wp_generate_password( 32, false );
5005
			Jetpack_Options::update_option( 'onboarding', $token );
5006
		}
5007
5008
		return $token;
5009
	}
5010
5011
	/**
5012
	 * Remove the onboarding token
5013
	 *
5014
	 * @return bool True on success, false on failure
5015
	 */
5016
	public static function invalidate_onboarding_token() {
5017
		return Jetpack_Options::delete_option( 'onboarding' );
5018
	}
5019
5020
	/**
5021
	 * Validate an onboarding token for a specific action
5022
	 *
5023
	 * @return boolean True if token/action pair is accepted, false if not
5024
	 */
5025
	public static function validate_onboarding_token_action( $token, $action ) {
5026
		// Compare tokens, bail if tokens do not match
5027
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5028
			return false;
5029
		}
5030
5031
		// List of valid actions we can take
5032
		$valid_actions = array(
5033
			'/jetpack/v4/settings',
5034
		);
5035
5036
		// Whitelist the action
5037
		if ( ! in_array( $action, $valid_actions ) ) {
5038
			return false;
5039
		}
5040
5041
		return true;
5042
	}
5043
5044
	/**
5045
	 * Checks to see if the URL is using SSL to connect with Jetpack
5046
	 *
5047
	 * @since 2.3.3
5048
	 * @return boolean
5049
	 */
5050
	public static function permit_ssl( $force_recheck = false ) {
5051
		// Do some fancy tests to see if ssl is being supported
5052
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5053
			$message = '';
5054
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5055
				$ssl = 0;
5056
			} else {
5057
				switch ( JETPACK_CLIENT__HTTPS ) {
5058
					case 'NEVER':
5059
						$ssl     = 0;
5060
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5061
						break;
5062
					case 'ALWAYS':
5063
					case 'AUTO':
5064
					default:
5065
						$ssl = 1;
5066
						break;
5067
				}
5068
5069
				// If it's not 'NEVER', test to see
5070
				if ( $ssl ) {
5071
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5072
						$ssl     = 0;
5073
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5074
					} else {
5075
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5076
						if ( is_wp_error( $response ) ) {
5077
							$ssl     = 0;
5078
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5079
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5080
							$ssl     = 0;
5081
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5082
						}
5083
					}
5084
				}
5085
			}
5086
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5087
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5088
		}
5089
5090
		return (bool) $ssl;
5091
	}
5092
5093
	/*
5094
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5095
	 */
5096
	public function alert_auto_ssl_fail() {
5097
		if ( ! current_user_can( 'manage_options' ) ) {
5098
			return;
5099
		}
5100
5101
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5102
		?>
5103
5104
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5105
			<div class="jp-banner__content">
5106
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5107
				<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>
5108
				<p>
5109
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5110
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5111
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5112
				</p>
5113
				<p>
5114
					<?php
5115
					printf(
5116
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5117
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5118
						esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' )
5119
					);
5120
					?>
5121
				</p>
5122
			</div>
5123
		</div>
5124
		<style>
5125
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5126
		</style>
5127
		<script type="text/javascript">
5128
			jQuery( document ).ready( function( $ ) {
5129
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5130
					var $this = $( this );
5131
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5132
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5133
					e.preventDefault();
5134
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5135
					$.post( ajaxurl, data )
5136
					  .done( function( response ) {
5137
						  if ( response.enabled ) {
5138
							  $( '#jetpack-ssl-warning' ).hide();
5139
						  } else {
5140
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5141
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5142
						  }
5143
					  }.bind( $this ) );
5144
				} );
5145
			} );
5146
		</script>
5147
5148
		<?php
5149
	}
5150
5151
	/**
5152
	 * Returns the Jetpack XML-RPC API
5153
	 *
5154
	 * @deprecated 8.0 Use Connection_Manager instead.
5155
	 * @return string
5156
	 */
5157
	public static function xmlrpc_api_url() {
5158
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5159
		return self::connection()->xmlrpc_api_url();
5160
	}
5161
5162
	/**
5163
	 * Returns the connection manager object.
5164
	 *
5165
	 * @return Automattic\Jetpack\Connection\Manager
5166
	 */
5167
	public static function connection() {
5168
		return self::init()->connection_manager;
5169
	}
5170
5171
	/**
5172
	 * Creates two secret tokens and the end of life timestamp for them.
5173
	 *
5174
	 * Note these tokens are unique per call, NOT static per site for connecting.
5175
	 *
5176
	 * @since 2.6
5177
	 * @param String  $action  The action name.
5178
	 * @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...
5179
	 * @param Integer $exp     Expiration time in seconds.
5180
	 * @return array
5181
	 */
5182
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5183
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5184
	}
5185
5186
	public static function get_secrets( $action, $user_id ) {
5187
		$secrets = self::connection()->get_secrets( $action, $user_id );
5188
5189
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5190
			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...
5191
		}
5192
5193
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5194
			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...
5195
		}
5196
5197
		return $secrets;
5198
	}
5199
5200
	/**
5201
	 * @deprecated 7.5 Use Connection_Manager instead.
5202
	 *
5203
	 * @param $action
5204
	 * @param $user_id
5205
	 */
5206
	public static function delete_secrets( $action, $user_id ) {
5207
		return self::connection()->delete_secrets( $action, $user_id );
5208
	}
5209
5210
	/**
5211
	 * Builds the timeout limit for queries talking with the wpcom servers.
5212
	 *
5213
	 * Based on local php max_execution_time in php.ini
5214
	 *
5215
	 * @since 2.6
5216
	 * @return int
5217
	 * @deprecated
5218
	 **/
5219
	public function get_remote_query_timeout_limit() {
5220
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5221
		return self::get_max_execution_time();
5222
	}
5223
5224
	/**
5225
	 * Builds the timeout limit for queries talking with the wpcom servers.
5226
	 *
5227
	 * Based on local php max_execution_time in php.ini
5228
	 *
5229
	 * @since 5.4
5230
	 * @return int
5231
	 **/
5232
	public static function get_max_execution_time() {
5233
		$timeout = (int) ini_get( 'max_execution_time' );
5234
5235
		// Ensure exec time set in php.ini
5236
		if ( ! $timeout ) {
5237
			$timeout = 30;
5238
		}
5239
		return $timeout;
5240
	}
5241
5242
	/**
5243
	 * Sets a minimum request timeout, and returns the current timeout
5244
	 *
5245
	 * @since 5.4
5246
	 **/
5247 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5248
		$timeout = self::get_max_execution_time();
5249
		if ( $timeout < $min_timeout ) {
5250
			$timeout = $min_timeout;
5251
			set_time_limit( $timeout );
5252
		}
5253
		return $timeout;
5254
	}
5255
5256
	/**
5257
	 * Takes the response from the Jetpack register new site endpoint and
5258
	 * verifies it worked properly.
5259
	 *
5260
	 * @since 2.6
5261
	 * @deprecated since 7.7.0
5262
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5263
	 **/
5264
	public function validate_remote_register_response() {
5265
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5266
	}
5267
5268
	/**
5269
	 * @return bool|WP_Error
5270
	 */
5271
	public static function register() {
5272
		$tracking = new Tracking();
5273
		$tracking->record_user_event( 'jpc_register_begin' );
5274
5275
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5276
5277
		$connection   = self::connection();
5278
		$registration = $connection->register();
5279
5280
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5281
5282
		if ( ! $registration || is_wp_error( $registration ) ) {
5283
			return $registration;
5284
		}
5285
5286
		return true;
5287
	}
5288
5289
	/**
5290
	 * Filters the registration request body to include tracking properties.
5291
	 *
5292
	 * @param Array $properties
5293
	 * @return Array amended properties.
5294
	 */
5295 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5296
		$tracking        = new Tracking();
5297
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5298
5299
		return array_merge(
5300
			$properties,
5301
			array(
5302
				'_ui' => $tracks_identity['_ui'],
5303
				'_ut' => $tracks_identity['_ut'],
5304
			)
5305
		);
5306
	}
5307
5308
	/**
5309
	 * Filters the token request body to include tracking properties.
5310
	 *
5311
	 * @param Array $properties
5312
	 * @return Array amended properties.
5313
	 */
5314 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5315
		$tracking        = new Tracking();
5316
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5317
5318
		return array_merge(
5319
			$properties,
5320
			array(
5321
				'_ui' => $tracks_identity['_ui'],
5322
				'_ut' => $tracks_identity['_ut'],
5323
			)
5324
		);
5325
	}
5326
5327
	/**
5328
	 * If the db version is showing something other that what we've got now, bump it to current.
5329
	 *
5330
	 * @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...
5331
	 */
5332
	public static function maybe_set_version_option() {
5333
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5334
		if ( JETPACK__VERSION != $version ) {
5335
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5336
5337
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5338
				/** This action is documented in class.jetpack.php */
5339
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5340
			}
5341
5342
			return true;
5343
		}
5344
		return false;
5345
	}
5346
5347
	/* Client Server API */
5348
5349
	/**
5350
	 * Loads the Jetpack XML-RPC client.
5351
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5352
	 *
5353
	 * @deprecated since 7.7.0
5354
	 */
5355
	public static function load_xml_rpc_client() {
5356
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5357
	}
5358
5359
	/**
5360
	 * Resets the saved authentication state in between testing requests.
5361
	 */
5362
	public function reset_saved_auth_state() {
5363
		$this->rest_authentication_status = null;
5364
		$this->connection_manager->reset_saved_auth_state();
5365
	}
5366
5367
	/**
5368
	 * Verifies the signature of the current request.
5369
	 *
5370
	 * @deprecated since 7.7.0
5371
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5372
	 *
5373
	 * @return false|array
5374
	 */
5375
	public function verify_xml_rpc_signature() {
5376
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5377
		return self::connection()->verify_xml_rpc_signature();
5378
	}
5379
5380
	/**
5381
	 * Verifies the signature of the current request.
5382
	 *
5383
	 * This function has side effects and should not be used. Instead,
5384
	 * use the memoized version `->verify_xml_rpc_signature()`.
5385
	 *
5386
	 * @deprecated since 7.7.0
5387
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5388
	 * @internal
5389
	 */
5390
	private function internal_verify_xml_rpc_signature() {
5391
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5392
	}
5393
5394
	/**
5395
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5396
	 *
5397
	 * @deprecated since 7.7.0
5398
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5399
	 *
5400
	 * @param \WP_User|mixed $user     User object if authenticated.
5401
	 * @param string         $username Username.
5402
	 * @param string         $password Password string.
5403
	 * @return \WP_User|mixed Authenticated user or error.
5404
	 */
5405
	public function authenticate_jetpack( $user, $username, $password ) {
5406
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5407
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5408
	}
5409
5410
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5411
	// Uses the existing XMLRPC request signing implementation.
5412
	function wp_rest_authenticate( $user ) {
5413
		if ( ! empty( $user ) ) {
5414
			// Another authentication method is in effect.
5415
			return $user;
5416
		}
5417
5418
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5419
			// Nothing to do for this authentication method.
5420
			return null;
5421
		}
5422
5423
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5424
			// Nothing to do for this authentication method.
5425
			return null;
5426
		}
5427
5428
		// Ensure that we always have the request body available.  At this
5429
		// point, the WP REST API code to determine the request body has not
5430
		// run yet.  That code may try to read from 'php://input' later, but
5431
		// this can only be done once per request in PHP versions prior to 5.6.
5432
		// So we will go ahead and perform this read now if needed, and save
5433
		// the request body where both the Jetpack signature verification code
5434
		// and the WP REST API code can see it.
5435
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5436
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5437
		}
5438
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5439
5440
		// Only support specific request parameters that have been tested and
5441
		// are known to work with signature verification.  A different method
5442
		// can be passed to the WP REST API via the '?_method=' parameter if
5443
		// needed.
5444
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5445
			$this->rest_authentication_status = new WP_Error(
5446
				'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...
5447
				__( 'This request method is not supported.', 'jetpack' ),
5448
				array( 'status' => 400 )
5449
			);
5450
			return null;
5451
		}
5452
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5453
			$this->rest_authentication_status = new WP_Error(
5454
				'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...
5455
				__( 'This request method does not support body parameters.', 'jetpack' ),
5456
				array( 'status' => 400 )
5457
			);
5458
			return null;
5459
		}
5460
5461
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5462
5463
		if (
5464
			$verified &&
5465
			isset( $verified['type'] ) &&
5466
			'user' === $verified['type'] &&
5467
			! empty( $verified['user_id'] )
5468
		) {
5469
			// Authentication successful.
5470
			$this->rest_authentication_status = true;
5471
			return $verified['user_id'];
5472
		}
5473
5474
		// Something else went wrong.  Probably a signature error.
5475
		$this->rest_authentication_status = new WP_Error(
5476
			'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...
5477
			__( 'The request is not signed correctly.', 'jetpack' ),
5478
			array( 'status' => 400 )
5479
		);
5480
		return null;
5481
	}
5482
5483
	/**
5484
	 * Report authentication status to the WP REST API.
5485
	 *
5486
	 * @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...
5487
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5488
	 */
5489
	public function wp_rest_authentication_errors( $value ) {
5490
		if ( $value !== null ) {
5491
			return $value;
5492
		}
5493
		return $this->rest_authentication_status;
5494
	}
5495
5496
	/**
5497
	 * Add our nonce to this request.
5498
	 *
5499
	 * @deprecated since 7.7.0
5500
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5501
	 *
5502
	 * @param int    $timestamp Timestamp of the request.
5503
	 * @param string $nonce     Nonce string.
5504
	 */
5505
	public function add_nonce( $timestamp, $nonce ) {
5506
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5507
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5508
	}
5509
5510
	/**
5511
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5512
	 * Capture it here so we can verify the signature later.
5513
	 *
5514
	 * @deprecated since 7.7.0
5515
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5516
	 *
5517
	 * @param array $methods XMLRPC methods.
5518
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5519
	 */
5520
	public function xmlrpc_methods( $methods ) {
5521
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5522
		return $this->connection_manager->xmlrpc_methods( $methods );
5523
	}
5524
5525
	/**
5526
	 * Register additional public XMLRPC methods.
5527
	 *
5528
	 * @deprecated since 7.7.0
5529
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5530
	 *
5531
	 * @param array $methods Public XMLRPC methods.
5532
	 * @return array Public XMLRPC methods, with the getOptions one.
5533
	 */
5534
	public function public_xmlrpc_methods( $methods ) {
5535
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5536
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5537
	}
5538
5539
	/**
5540
	 * Handles a getOptions XMLRPC method call.
5541
	 *
5542
	 * @deprecated since 7.7.0
5543
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5544
	 *
5545
	 * @param array $args method call arguments.
5546
	 * @return array an amended XMLRPC server options array.
5547
	 */
5548
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5549
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5550
		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...
5551
	}
5552
5553
	/**
5554
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5555
	 *
5556
	 * @deprecated since 7.7.0
5557
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5558
	 *
5559
	 * @param array $options Standard Core options.
5560
	 * @return array Amended options.
5561
	 */
5562
	public function xmlrpc_options( $options ) {
5563
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5564
		return $this->connection_manager->xmlrpc_options( $options );
5565
	}
5566
5567
	/**
5568
	 * Cleans nonces that were saved when calling ::add_nonce.
5569
	 *
5570
	 * @deprecated since 7.7.0
5571
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5572
	 *
5573
	 * @param bool $all whether to clean even non-expired nonces.
5574
	 */
5575
	public static function clean_nonces( $all = false ) {
5576
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5577
		return self::connection()->clean_nonces( $all );
5578
	}
5579
5580
	/**
5581
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5582
	 * SET: state( $key, $value );
5583
	 * GET: $value = state( $key );
5584
	 *
5585
	 * @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...
5586
	 * @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...
5587
	 * @param bool   $restate private
5588
	 */
5589
	public static function state( $key = null, $value = null, $restate = false ) {
5590
		static $state = array();
5591
		static $path, $domain;
5592
		if ( ! isset( $path ) ) {
5593
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5594
			$admin_url = self::admin_url();
5595
			$bits      = wp_parse_url( $admin_url );
5596
5597
			if ( is_array( $bits ) ) {
5598
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5599
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5600
			} else {
5601
				$path = $domain = null;
5602
			}
5603
		}
5604
5605
		// Extract state from cookies and delete cookies
5606
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5607
			$yum = $_COOKIE['jetpackState'];
5608
			unset( $_COOKIE['jetpackState'] );
5609
			foreach ( $yum as $k => $v ) {
5610
				if ( strlen( $v ) ) {
5611
					$state[ $k ] = $v;
5612
				}
5613
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5614
			}
5615
		}
5616
5617
		if ( $restate ) {
5618
			foreach ( $state as $k => $v ) {
5619
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5620
			}
5621
			return;
5622
		}
5623
5624
		// Get a state variable
5625
		if ( isset( $key ) && ! isset( $value ) ) {
5626
			if ( array_key_exists( $key, $state ) ) {
5627
				return $state[ $key ];
5628
			}
5629
			return null;
5630
		}
5631
5632
		// Set a state variable
5633
		if ( isset( $key ) && isset( $value ) ) {
5634
			if ( is_array( $value ) && isset( $value[0] ) ) {
5635
				$value = $value[0];
5636
			}
5637
			$state[ $key ] = $value;
5638
			if ( ! headers_sent() ) {
5639
				setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5640
			}
5641
		}
5642
	}
5643
5644
	public static function restate() {
5645
		self::state( null, null, true );
5646
	}
5647
5648
	public static function check_privacy( $file ) {
5649
		static $is_site_publicly_accessible = null;
5650
5651
		if ( is_null( $is_site_publicly_accessible ) ) {
5652
			$is_site_publicly_accessible = false;
5653
5654
			$rpc = new Jetpack_IXR_Client();
5655
5656
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5657
			if ( $success ) {
5658
				$response = $rpc->getResponse();
5659
				if ( $response ) {
5660
					$is_site_publicly_accessible = true;
5661
				}
5662
			}
5663
5664
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5665
		}
5666
5667
		if ( $is_site_publicly_accessible ) {
5668
			return;
5669
		}
5670
5671
		$module_slug = self::get_module_slug( $file );
5672
5673
		$privacy_checks = self::state( 'privacy_checks' );
5674
		if ( ! $privacy_checks ) {
5675
			$privacy_checks = $module_slug;
5676
		} else {
5677
			$privacy_checks .= ",$module_slug";
5678
		}
5679
5680
		self::state( 'privacy_checks', $privacy_checks );
5681
	}
5682
5683
	/**
5684
	 * Helper method for multicall XMLRPC.
5685
	 *
5686
	 * @param ...$args Args for the async_call.
5687
	 */
5688
	public static function xmlrpc_async_call( ...$args ) {
5689
		global $blog_id;
5690
		static $clients = array();
5691
5692
		$client_blog_id = is_multisite() ? $blog_id : 0;
5693
5694
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5695
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5696
			if ( function_exists( 'ignore_user_abort' ) ) {
5697
				ignore_user_abort( true );
5698
			}
5699
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5700
		}
5701
5702
		if ( ! empty( $args[0] ) ) {
5703
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5704
		} elseif ( is_multisite() ) {
5705
			foreach ( $clients as $client_blog_id => $client ) {
5706
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5707
					continue;
5708
				}
5709
5710
				$switch_success = switch_to_blog( $client_blog_id, true );
5711
				if ( ! $switch_success ) {
5712
					continue;
5713
				}
5714
5715
				flush();
5716
				$client->query();
5717
5718
				restore_current_blog();
5719
			}
5720
		} else {
5721
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5722
				flush();
5723
				$clients[0]->query();
5724
			}
5725
		}
5726
	}
5727
5728
	public static function staticize_subdomain( $url ) {
5729
5730
		// Extract hostname from URL
5731
		$host = wp_parse_url( $url, PHP_URL_HOST );
5732
5733
		// Explode hostname on '.'
5734
		$exploded_host = explode( '.', $host );
5735
5736
		// Retrieve the name and TLD
5737
		if ( count( $exploded_host ) > 1 ) {
5738
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5739
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5740
			// Rebuild domain excluding subdomains
5741
			$domain = $name . '.' . $tld;
5742
		} else {
5743
			$domain = $host;
5744
		}
5745
		// Array of Automattic domains
5746
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5747
5748
		// Return $url if not an Automattic domain
5749
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5750
			return $url;
5751
		}
5752
5753
		if ( is_ssl() ) {
5754
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5755
		}
5756
5757
		srand( crc32( basename( $url ) ) );
5758
		$static_counter = rand( 0, 2 );
5759
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5760
5761
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5762
	}
5763
5764
	/* JSON API Authorization */
5765
5766
	/**
5767
	 * Handles the login action for Authorizing the JSON API
5768
	 */
5769
	function login_form_json_api_authorization() {
5770
		$this->verify_json_api_authorization_request();
5771
5772
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5773
5774
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5775
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5776
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5777
	}
5778
5779
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5780
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5781
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5782
			return $url;
5783
		}
5784
5785
		$parsed_url = wp_parse_url( $url );
5786
		$url        = strtok( $url, '?' );
5787
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5788
		if ( ! empty( $parsed_url['query'] ) ) {
5789
			$url .= "&{$parsed_url['query']}";
5790
		}
5791
5792
		return $url;
5793
	}
5794
5795
	// Make sure the POSTed request is handled by the same action
5796
	function preserve_action_in_login_form_for_json_api_authorization() {
5797
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5798
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5799
	}
5800
5801
	// If someone logs in to approve API access, store the Access Code in usermeta
5802
	function store_json_api_authorization_token( $user_login, $user ) {
5803
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5804
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5805
		$token = wp_generate_password( 32, false );
5806
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5807
	}
5808
5809
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5810
	function allow_wpcom_public_api_domain( $domains ) {
5811
		$domains[] = 'public-api.wordpress.com';
5812
		return $domains;
5813
	}
5814
5815
	static function is_redirect_encoded( $redirect_url ) {
5816
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5817
	}
5818
5819
	// Add all wordpress.com environments to the safe redirect whitelist
5820
	function allow_wpcom_environments( $domains ) {
5821
		$domains[] = 'wordpress.com';
5822
		$domains[] = 'wpcalypso.wordpress.com';
5823
		$domains[] = 'horizon.wordpress.com';
5824
		$domains[] = 'calypso.localhost';
5825
		return $domains;
5826
	}
5827
5828
	// Add the Access Code details to the public-api.wordpress.com redirect
5829
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5830
		return add_query_arg(
5831
			urlencode_deep(
5832
				array(
5833
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5834
					'jetpack-user-id' => (int) $user->ID,
5835
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5836
				)
5837
			),
5838
			$redirect_to
5839
		);
5840
	}
5841
5842
5843
	/**
5844
	 * Verifies the request by checking the signature
5845
	 *
5846
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5847
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5848
	 *
5849
	 * @param null|array $environment
5850
	 */
5851
	function verify_json_api_authorization_request( $environment = null ) {
5852
		$environment = is_null( $environment )
5853
			? $_REQUEST
5854
			: $environment;
5855
5856
		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...
5857
		$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...
5858
		if ( ! $token || empty( $token->secret ) ) {
5859
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5860
		}
5861
5862
		$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' );
5863
5864
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5865
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5866
			/**
5867
			 * Jetpack authorisation request Error.
5868
			 *
5869
			 * @since 7.5.0
5870
			 */
5871
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5872
			$die_error = sprintf(
5873
				/* translators: %s is a URL */
5874
				__( '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' ),
5875
				'https://jetpack.com/support/double-encoding/'
5876
			);
5877
		}
5878
5879
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5880
5881
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5882
			$signature = $jetpack_signature->sign_request(
5883
				$environment['token'],
5884
				$environment['timestamp'],
5885
				$environment['nonce'],
5886
				'',
5887
				'GET',
5888
				$environment['jetpack_json_api_original_query'],
5889
				null,
5890
				true
5891
			);
5892
		} else {
5893
			$signature = $jetpack_signature->sign_current_request(
5894
				array(
5895
					'body'   => null,
5896
					'method' => 'GET',
5897
				)
5898
			);
5899
		}
5900
5901
		if ( ! $signature ) {
5902
			wp_die( $die_error );
5903
		} elseif ( is_wp_error( $signature ) ) {
5904
			wp_die( $die_error );
5905
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5906
			if ( is_ssl() ) {
5907
				// 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
5908
				$signature = $jetpack_signature->sign_current_request(
5909
					array(
5910
						'scheme' => 'http',
5911
						'body'   => null,
5912
						'method' => 'GET',
5913
					)
5914
				);
5915
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5916
					wp_die( $die_error );
5917
				}
5918
			} else {
5919
				wp_die( $die_error );
5920
			}
5921
		}
5922
5923
		$timestamp = (int) $environment['timestamp'];
5924
		$nonce     = stripslashes( (string) $environment['nonce'] );
5925
5926
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5927
			// De-nonce the nonce, at least for 5 minutes.
5928
			// 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)
5929
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5930
			if ( $old_nonce_time < time() - 300 ) {
5931
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5932
			}
5933
		}
5934
5935
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5936
		$data_filters = array(
5937
			'state'        => 'opaque',
5938
			'client_id'    => 'int',
5939
			'client_title' => 'string',
5940
			'client_image' => 'url',
5941
		);
5942
5943
		foreach ( $data_filters as $key => $sanitation ) {
5944
			if ( ! isset( $data->$key ) ) {
5945
				wp_die( $die_error );
5946
			}
5947
5948
			switch ( $sanitation ) {
5949
				case 'int':
5950
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
5951
					break;
5952
				case 'opaque':
5953
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
5954
					break;
5955
				case 'string':
5956
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
5957
					break;
5958
				case 'url':
5959
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
5960
					break;
5961
			}
5962
		}
5963
5964
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5965
			wp_die( $die_error );
5966
		}
5967
	}
5968
5969
	function login_message_json_api_authorization( $message ) {
5970
		return '<p class="message">' . sprintf(
5971
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
5972
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5973
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5974
	}
5975
5976
	/**
5977
	 * Get $content_width, but with a <s>twist</s> filter.
5978
	 */
5979
	public static function get_content_width() {
5980
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5981
			? $GLOBALS['content_width']
5982
			: false;
5983
		/**
5984
		 * Filter the Content Width value.
5985
		 *
5986
		 * @since 2.2.3
5987
		 *
5988
		 * @param string $content_width Content Width value.
5989
		 */
5990
		return apply_filters( 'jetpack_content_width', $content_width );
5991
	}
5992
5993
	/**
5994
	 * Pings the WordPress.com Mirror Site for the specified options.
5995
	 *
5996
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5997
	 *
5998
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5999
	 */
6000
	public function get_cloud_site_options( $option_names ) {
6001
		$option_names = array_filter( (array) $option_names, 'is_string' );
6002
6003
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6004
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6005
		if ( $xml->isError() ) {
6006
			return array(
6007
				'error_code' => $xml->getErrorCode(),
6008
				'error_msg'  => $xml->getErrorMessage(),
6009
			);
6010
		}
6011
		$cloud_site_options = $xml->getResponse();
6012
6013
		return $cloud_site_options;
6014
	}
6015
6016
	/**
6017
	 * Checks if the site is currently in an identity crisis.
6018
	 *
6019
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6020
	 */
6021
	public static function check_identity_crisis() {
6022
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6023
			return false;
6024
		}
6025
6026
		return Jetpack_Options::get_option( 'sync_error_idc' );
6027
	}
6028
6029
	/**
6030
	 * Checks whether the home and siteurl specifically are whitelisted
6031
	 * Written so that we don't have re-check $key and $value params every time
6032
	 * we want to check if this site is whitelisted, for example in footer.php
6033
	 *
6034
	 * @since  3.8.0
6035
	 * @return bool True = already whitelisted False = not whitelisted
6036
	 */
6037
	public static function is_staging_site() {
6038
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6039
		return ( new Status() )->is_staging_site();
6040
	}
6041
6042
	/**
6043
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6044
	 *
6045
	 * @since 4.4.0
6046
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6047
	 *
6048
	 * @return bool
6049
	 */
6050
	public static function validate_sync_error_idc_option() {
6051
		$is_valid = false;
6052
6053
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6054
		if ( false === $idc_allowed ) {
6055
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6056
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6057
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6058
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6059
				$transient_duration = HOUR_IN_SECONDS;
6060
			} else {
6061
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6062
				$idc_allowed        = '1';
6063
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6064
			}
6065
6066
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6067
		}
6068
6069
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6070
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6071
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6072
			$local_options = self::get_sync_error_idc_option();
6073
			// Ensure all values are set.
6074
			if ( isset( $sync_error['home'] ) && isset ( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6075
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6076
					$is_valid = true;
6077
				}
6078
			}
6079
6080
		}
6081
6082
		/**
6083
		 * Filters whether the sync_error_idc option is valid.
6084
		 *
6085
		 * @since 4.4.0
6086
		 *
6087
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6088
		 */
6089
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6090
6091
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6092
			// Since the option exists, and did not validate, delete it
6093
			Jetpack_Options::delete_option( 'sync_error_idc' );
6094
		}
6095
6096
		return $is_valid;
6097
	}
6098
6099
	/**
6100
	 * Normalizes a url by doing three things:
6101
	 *  - Strips protocol
6102
	 *  - Strips www
6103
	 *  - Adds a trailing slash
6104
	 *
6105
	 * @since 4.4.0
6106
	 * @param string $url
6107
	 * @return WP_Error|string
6108
	 */
6109
	public static function normalize_url_protocol_agnostic( $url ) {
6110
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6111
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6112
			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...
6113
		}
6114
6115
		// Strip www and protocols
6116
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6117
		return $url;
6118
	}
6119
6120
	/**
6121
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6122
	 *
6123
	 * @since 4.4.0
6124
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6125
	 *
6126
	 * @param array $response
6127
	 * @return array Array of the local urls, wpcom urls, and error code
6128
	 */
6129
	public static function get_sync_error_idc_option( $response = array() ) {
6130
		// Since the local options will hit the database directly, store the values
6131
		// in a transient to allow for autoloading and caching on subsequent views.
6132
		$local_options = get_transient( 'jetpack_idc_local' );
6133
		if ( false === $local_options ) {
6134
			$local_options = array(
6135
				'home'    => Functions::home_url(),
6136
				'siteurl' => Functions::site_url(),
6137
			);
6138
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6139
		}
6140
6141
		$options = array_merge( $local_options, $response );
6142
6143
		$returned_values = array();
6144
		foreach ( $options as $key => $option ) {
6145
			if ( 'error_code' === $key ) {
6146
				$returned_values[ $key ] = $option;
6147
				continue;
6148
			}
6149
6150
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6151
				continue;
6152
			}
6153
6154
			$returned_values[ $key ] = $normalized_url;
6155
		}
6156
6157
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6158
6159
		return $returned_values;
6160
	}
6161
6162
	/**
6163
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6164
	 * If set to true, the site will be put into staging mode.
6165
	 *
6166
	 * @since 4.3.2
6167
	 * @return bool
6168
	 */
6169
	public static function sync_idc_optin() {
6170
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6171
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6172
		} else {
6173
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6174
		}
6175
6176
		/**
6177
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6178
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6179
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6180
		 *
6181
		 * @since 4.3.2
6182
		 *
6183
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6184
		 */
6185
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6186
	}
6187
6188
	/**
6189
	 * Maybe Use a .min.css stylesheet, maybe not.
6190
	 *
6191
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6192
	 */
6193
	public static function maybe_min_asset( $url, $path, $plugin ) {
6194
		// Short out on things trying to find actual paths.
6195
		if ( ! $path || empty( $plugin ) ) {
6196
			return $url;
6197
		}
6198
6199
		$path = ltrim( $path, '/' );
6200
6201
		// Strip out the abspath.
6202
		$base = dirname( plugin_basename( $plugin ) );
6203
6204
		// Short out on non-Jetpack assets.
6205
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6206
			return $url;
6207
		}
6208
6209
		// File name parsing.
6210
		$file              = "{$base}/{$path}";
6211
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6212
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6213
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6214
		$extension         = array_shift( $file_name_parts_r );
6215
6216
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6217
			// Already pointing at the minified version.
6218
			if ( 'min' === $file_name_parts_r[0] ) {
6219
				return $url;
6220
			}
6221
6222
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6223
			if ( file_exists( $min_full_path ) ) {
6224
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6225
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6226
				if ( 'css' === $extension ) {
6227
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6228
					self::$min_assets[ $key ] = $path;
6229
				}
6230
			}
6231
		}
6232
6233
		return $url;
6234
	}
6235
6236
	/**
6237
	 * If the asset is minified, let's flag .min as the suffix.
6238
	 *
6239
	 * Attached to `style_loader_src` filter.
6240
	 *
6241
	 * @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...
6242
	 * @param string $handle The registered handle of the script in question.
6243
	 * @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...
6244
	 */
6245
	public static function set_suffix_on_min( $src, $handle ) {
6246
		if ( false === strpos( $src, '.min.css' ) ) {
6247
			return $src;
6248
		}
6249
6250
		if ( ! empty( self::$min_assets ) ) {
6251
			foreach ( self::$min_assets as $file => $path ) {
6252
				if ( false !== strpos( $src, $file ) ) {
6253
					wp_style_add_data( $handle, 'suffix', '.min' );
6254
					return $src;
6255
				}
6256
			}
6257
		}
6258
6259
		return $src;
6260
	}
6261
6262
	/**
6263
	 * Maybe inlines a stylesheet.
6264
	 *
6265
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6266
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6267
	 *
6268
	 * Attached to `style_loader_tag` filter.
6269
	 *
6270
	 * @param string $tag The tag that would link to the external asset.
6271
	 * @param string $handle The registered handle of the script in question.
6272
	 *
6273
	 * @return string
6274
	 */
6275
	public static function maybe_inline_style( $tag, $handle ) {
6276
		global $wp_styles;
6277
		$item = $wp_styles->registered[ $handle ];
6278
6279
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6280
			return $tag;
6281
		}
6282
6283
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6284
			$href = $matches[1];
6285
			// Strip off query string
6286
			if ( $pos = strpos( $href, '?' ) ) {
6287
				$href = substr( $href, 0, $pos );
6288
			}
6289
			// Strip off fragment
6290
			if ( $pos = strpos( $href, '#' ) ) {
6291
				$href = substr( $href, 0, $pos );
6292
			}
6293
		} else {
6294
			return $tag;
6295
		}
6296
6297
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6298
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6299
			return $tag;
6300
		}
6301
6302
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6303
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6304
			// And this isn't the pass that actually deals with the RTL version...
6305
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6306
				// Short out, as the RTL version will deal with it in a moment.
6307
				return $tag;
6308
			}
6309
		}
6310
6311
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6312
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6313
		if ( $css ) {
6314
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6315
			if ( empty( $item->extra['after'] ) ) {
6316
				wp_add_inline_style( $handle, $css );
6317
			} else {
6318
				array_unshift( $item->extra['after'], $css );
6319
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6320
			}
6321
		}
6322
6323
		return $tag;
6324
	}
6325
6326
	/**
6327
	 * Loads a view file from the views
6328
	 *
6329
	 * Data passed in with the $data parameter will be available in the
6330
	 * template file as $data['value']
6331
	 *
6332
	 * @param string $template - Template file to load
6333
	 * @param array  $data - Any data to pass along to the template
6334
	 * @return boolean - If template file was found
6335
	 **/
6336
	public function load_view( $template, $data = array() ) {
6337
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6338
6339
		if ( file_exists( $views_dir . $template ) ) {
6340
			require_once $views_dir . $template;
6341
			return true;
6342
		}
6343
6344
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6345
		return false;
6346
	}
6347
6348
	/**
6349
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6350
	 */
6351
	public function deprecated_hooks() {
6352
		global $wp_filter;
6353
6354
		/*
6355
		 * Format:
6356
		 * deprecated_filter_name => replacement_name
6357
		 *
6358
		 * If there is no replacement, use null for replacement_name
6359
		 */
6360
		$deprecated_list = array(
6361
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6362
			'wpl_sharing_2014_1'                           => null,
6363
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6364
			'jetpack_identity_crisis_options_to_check'     => null,
6365
			'update_option_jetpack_single_user_site'       => null,
6366
			'audio_player_default_colors'                  => null,
6367
			'add_option_jetpack_featured_images_enabled'   => null,
6368
			'add_option_jetpack_update_details'            => null,
6369
			'add_option_jetpack_updates'                   => null,
6370
			'add_option_jetpack_network_name'              => null,
6371
			'add_option_jetpack_network_allow_new_registrations' => null,
6372
			'add_option_jetpack_network_add_new_users'     => null,
6373
			'add_option_jetpack_network_site_upload_space' => null,
6374
			'add_option_jetpack_network_upload_file_types' => null,
6375
			'add_option_jetpack_network_enable_administration_menus' => null,
6376
			'add_option_jetpack_is_multi_site'             => null,
6377
			'add_option_jetpack_is_main_network'           => null,
6378
			'add_option_jetpack_main_network_site'         => null,
6379
			'jetpack_sync_all_registered_options'          => null,
6380
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6381
			'jetpack_is_post_mailable'                     => null,
6382
			'jetpack_seo_site_host'                        => null,
6383
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6384
			'jetpack_holiday_snow_option_name'             => null,
6385
			'jetpack_holiday_chance_of_snow'               => null,
6386
			'jetpack_holiday_snow_js_url'                  => null,
6387
			'jetpack_is_holiday_snow_season'               => null,
6388
			'jetpack_holiday_snow_option_updated'          => null,
6389
			'jetpack_holiday_snowing'                      => null,
6390
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6391
			'jetpack_cache_plans'                          => null,
6392
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6393
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6394
			'jetpack_enable_site_verification'             => null,
6395
			'can_display_jetpack_manage_notice'            => null,
6396
			// Removed in Jetpack 7.3.0
6397
			'atd_load_scripts'                             => null,
6398
			'atd_http_post_timeout'                        => null,
6399
			'atd_http_post_error'                          => null,
6400
			'atd_service_domain'                           => null,
6401
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6402
			// Removed in Jetpack 7.9.0
6403
			'jetpack_pwa_manifest'                         => null,
6404
			'jetpack_pwa_background_color'                 => null,
6405
			// Removed in Jetpack 8.3.0.
6406
			'jetpack_check_mobile'                         => null,
6407
			'jetpack_mobile_stylesheet'                    => null,
6408
			'jetpack_mobile_template'                      => null,
6409
			'mobile_reject_mobile'                         => null,
6410
			'mobile_force_mobile'                          => null,
6411
			'mobile_app_promo_download'                    => null,
6412
			'mobile_setup'                                 => null,
6413
			'jetpack_mobile_footer_before'                 => null,
6414
			'wp_mobile_theme_footer'                       => null,
6415
			'minileven_credits'                            => null,
6416
			'jetpack_mobile_header_before'                 => null,
6417
			'jetpack_mobile_header_after'                  => null,
6418
			'jetpack_mobile_theme_menu'                    => null,
6419
			'minileven_show_featured_images'               => null,
6420
			'minileven_attachment_size'                    => null,
6421
		);
6422
6423
		// This is a silly loop depth. Better way?
6424
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6425
			if ( has_action( $hook ) ) {
6426
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6427
					foreach ( $values as $hooked ) {
6428
						if ( is_callable( $hooked['function'] ) ) {
6429
							$function_name = 'an anonymous function';
6430
						} else {
6431
							$function_name = $hooked['function'];
6432
						}
6433
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6434
					}
6435
				}
6436
			}
6437
		}
6438
	}
6439
6440
	/**
6441
	 * Converts any url in a stylesheet, to the correct absolute url.
6442
	 *
6443
	 * Considerations:
6444
	 *  - Normal, relative URLs     `feh.png`
6445
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6446
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6447
	 *  - Absolute URLs             `http://domain.com/feh.png`
6448
	 *  - Domain root relative URLs `/feh.png`
6449
	 *
6450
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6451
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6452
	 *
6453
	 * @return mixed|string
6454
	 */
6455
	public static function absolutize_css_urls( $css, $css_file_url ) {
6456
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6457
		$css_dir = dirname( $css_file_url );
6458
		$p       = wp_parse_url( $css_dir );
6459
		$domain  = sprintf(
6460
			'%1$s//%2$s%3$s%4$s',
6461
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6462
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6463
			$p['host'],
6464
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6465
		);
6466
6467
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6468
			$find = $replace = array();
6469
			foreach ( $matches as $match ) {
6470
				$url = trim( $match['path'], "'\" \t" );
6471
6472
				// If this is a data url, we don't want to mess with it.
6473
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6474
					continue;
6475
				}
6476
6477
				// If this is an absolute or protocol-agnostic url,
6478
				// we don't want to mess with it.
6479
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6480
					continue;
6481
				}
6482
6483
				switch ( substr( $url, 0, 1 ) ) {
6484
					case '/':
6485
						$absolute = $domain . $url;
6486
						break;
6487
					default:
6488
						$absolute = $css_dir . '/' . $url;
6489
				}
6490
6491
				$find[]    = $match[0];
6492
				$replace[] = sprintf( 'url("%s")', $absolute );
6493
			}
6494
			$css = str_replace( $find, $replace, $css );
6495
		}
6496
6497
		return $css;
6498
	}
6499
6500
	/**
6501
	 * This methods removes all of the registered css files on the front end
6502
	 * from Jetpack in favor of using a single file. In effect "imploding"
6503
	 * all the files into one file.
6504
	 *
6505
	 * Pros:
6506
	 * - Uses only ONE css asset connection instead of 15
6507
	 * - Saves a minimum of 56k
6508
	 * - Reduces server load
6509
	 * - Reduces time to first painted byte
6510
	 *
6511
	 * Cons:
6512
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6513
	 *      should not cause any issues with themes.
6514
	 * - Plugins/themes dequeuing styles no longer do anything. See
6515
	 *      jetpack_implode_frontend_css filter for a workaround
6516
	 *
6517
	 * For some situations developers may wish to disable css imploding and
6518
	 * instead operate in legacy mode where each file loads seperately and
6519
	 * can be edited individually or dequeued. This can be accomplished with
6520
	 * the following line:
6521
	 *
6522
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6523
	 *
6524
	 * @since 3.2
6525
	 **/
6526
	public function implode_frontend_css( $travis_test = false ) {
6527
		$do_implode = true;
6528
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6529
			$do_implode = false;
6530
		}
6531
6532
		// Do not implode CSS when the page loads via the AMP plugin.
6533
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6534
			$do_implode = false;
6535
		}
6536
6537
		/**
6538
		 * Allow CSS to be concatenated into a single jetpack.css file.
6539
		 *
6540
		 * @since 3.2.0
6541
		 *
6542
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6543
		 */
6544
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6545
6546
		// Do not use the imploded file when default behavior was altered through the filter
6547
		if ( ! $do_implode ) {
6548
			return;
6549
		}
6550
6551
		// We do not want to use the imploded file in dev mode, or if not connected
6552
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6553
			if ( ! $travis_test ) {
6554
				return;
6555
			}
6556
		}
6557
6558
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6559
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6560
			return;
6561
		}
6562
6563
		/*
6564
		 * Now we assume Jetpack is connected and able to serve the single
6565
		 * file.
6566
		 *
6567
		 * In the future there will be a check here to serve the file locally
6568
		 * or potentially from the Jetpack CDN
6569
		 *
6570
		 * For now:
6571
		 * - Enqueue a single imploded css file
6572
		 * - Zero out the style_loader_tag for the bundled ones
6573
		 * - Be happy, drink scotch
6574
		 */
6575
6576
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6577
6578
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6579
6580
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6581
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6582
	}
6583
6584
	function concat_remove_style_loader_tag( $tag, $handle ) {
6585
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6586
			$tag = '';
6587
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6588
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6589
			}
6590
		}
6591
6592
		return $tag;
6593
	}
6594
6595
	/**
6596
	 * Add an async attribute to scripts that can be loaded asynchronously.
6597
	 * https://www.w3schools.com/tags/att_script_async.asp
6598
	 *
6599
	 * @since 7.7.0
6600
	 *
6601
	 * @param string $tag    The <script> tag for the enqueued script.
6602
	 * @param string $handle The script's registered handle.
6603
	 * @param string $src    The script's source URL.
6604
	 */
6605
	public function script_add_async( $tag, $handle, $src ) {
6606
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6607
			return preg_replace( '/^<script /i', '<script async ', $tag );
6608
		}
6609
6610
		return $tag;
6611
	}
6612
6613
	/*
6614
	 * Check the heartbeat data
6615
	 *
6616
	 * Organizes the heartbeat data by severity.  For example, if the site
6617
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6618
	 *
6619
	 * Data will be added to "caution" array, if it either:
6620
	 *  - Out of date Jetpack version
6621
	 *  - Out of date WP version
6622
	 *  - Out of date PHP version
6623
	 *
6624
	 * $return array $filtered_data
6625
	 */
6626
	public static function jetpack_check_heartbeat_data() {
6627
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6628
6629
		$good    = array();
6630
		$caution = array();
6631
		$bad     = array();
6632
6633
		foreach ( $raw_data as $stat => $value ) {
6634
6635
			// Check jetpack version
6636
			if ( 'version' == $stat ) {
6637
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6638
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6639
					continue;
6640
				}
6641
			}
6642
6643
			// Check WP version
6644
			if ( 'wp-version' == $stat ) {
6645
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6646
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6647
					continue;
6648
				}
6649
			}
6650
6651
			// Check PHP version
6652
			if ( 'php-version' == $stat ) {
6653
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6654
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_PHP_VERSION;
6655
					continue;
6656
				}
6657
			}
6658
6659
			// Check ID crisis
6660
			if ( 'identitycrisis' == $stat ) {
6661
				if ( 'yes' == $value ) {
6662
					$bad[ $stat ] = $value;
6663
					continue;
6664
				}
6665
			}
6666
6667
			// The rest are good :)
6668
			$good[ $stat ] = $value;
6669
		}
6670
6671
		$filtered_data = array(
6672
			'good'    => $good,
6673
			'caution' => $caution,
6674
			'bad'     => $bad,
6675
		);
6676
6677
		return $filtered_data;
6678
	}
6679
6680
6681
	/*
6682
	 * This method is used to organize all options that can be reset
6683
	 * without disconnecting Jetpack.
6684
	 *
6685
	 * It is used in class.jetpack-cli.php to reset options
6686
	 *
6687
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6688
	 *
6689
	 * @return array of options to delete.
6690
	 */
6691
	public static function get_jetpack_options_for_reset() {
6692
		return Jetpack_Options::get_options_for_reset();
6693
	}
6694
6695
	/*
6696
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6697
	 * so we can bring them directly to their site in calypso.
6698
	 *
6699
	 * @param string | url
6700
	 * @return string | url without the guff
6701
	 */
6702
	public static function build_raw_urls( $url ) {
6703
		$strip_http = '/.*?:\/\//i';
6704
		$url        = preg_replace( $strip_http, '', $url );
6705
		$url        = str_replace( '/', '::', $url );
6706
		return $url;
6707
	}
6708
6709
	/**
6710
	 * Stores and prints out domains to prefetch for page speed optimization.
6711
	 *
6712
	 * @param mixed $new_urls
6713
	 */
6714
	public static function dns_prefetch( $new_urls = null ) {
6715
		static $prefetch_urls = array();
6716
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6717
			echo "\r\n";
6718
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6719
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6720
			}
6721
		} elseif ( ! empty( $new_urls ) ) {
6722
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6723
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6724
			}
6725
			foreach ( (array) $new_urls as $this_new_url ) {
6726
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6727
			}
6728
			$prefetch_urls = array_unique( $prefetch_urls );
6729
		}
6730
	}
6731
6732
	public function wp_dashboard_setup() {
6733
		if ( self::is_active() ) {
6734
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6735
		}
6736
6737
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6738
			$jetpack_logo = new Jetpack_Logo();
6739
			$widget_title = sprintf(
6740
				wp_kses(
6741
					/* translators: Placeholder is a Jetpack logo. */
6742
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6743
					array( 'span' => array() )
6744
				),
6745
				$jetpack_logo->get_jp_emblem( true )
6746
			);
6747
6748
			wp_add_dashboard_widget(
6749
				'jetpack_summary_widget',
6750
				$widget_title,
6751
				array( __CLASS__, 'dashboard_widget' )
6752
			);
6753
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6754
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6755
6756
			// If we're inactive and not in development mode, sort our box to the top.
6757
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6758
				global $wp_meta_boxes;
6759
6760
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6761
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6762
6763
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6764
			}
6765
		}
6766
	}
6767
6768
	/**
6769
	 * @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...
6770
	 * @return mixed
6771
	 */
6772
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6773
		if ( ! is_array( $sorted ) ) {
6774
			return $sorted;
6775
		}
6776
6777
		foreach ( $sorted as $box_context => $ids ) {
6778
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6779
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6780
				continue;
6781
			}
6782
6783
			$ids_array = explode( ',', $ids );
6784
			$key       = array_search( 'dashboard_stats', $ids_array );
6785
6786
			if ( false !== $key ) {
6787
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6788
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6789
				$sorted[ $box_context ] = implode( ',', $ids_array );
6790
				// We've found it, stop searching, and just return.
6791
				break;
6792
			}
6793
		}
6794
6795
		return $sorted;
6796
	}
6797
6798
	public static function dashboard_widget() {
6799
		/**
6800
		 * Fires when the dashboard is loaded.
6801
		 *
6802
		 * @since 3.4.0
6803
		 */
6804
		do_action( 'jetpack_dashboard_widget' );
6805
	}
6806
6807
	public static function dashboard_widget_footer() {
6808
		?>
6809
		<footer>
6810
6811
		<div class="protect">
6812
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6813
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6814
				<p class="blocked-count">
6815
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6816
				</p>
6817
				<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>
6818
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6819
				<a href="
6820
				<?php
6821
				echo esc_url(
6822
					wp_nonce_url(
6823
						self::admin_url(
6824
							array(
6825
								'action' => 'activate',
6826
								'module' => 'protect',
6827
							)
6828
						),
6829
						'jetpack_activate-protect'
6830
					)
6831
				);
6832
				?>
6833
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6834
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6835
				</a>
6836
			<?php else : ?>
6837
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6838
			<?php endif; ?>
6839
		</div>
6840
6841
		<div class="akismet">
6842
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6843
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6844
				<p class="blocked-count">
6845
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6846
				</p>
6847
				<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>
6848
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6849
				<a href="
6850
				<?php
6851
				echo esc_url(
6852
					wp_nonce_url(
6853
						add_query_arg(
6854
							array(
6855
								'action' => 'activate',
6856
								'plugin' => 'akismet/akismet.php',
6857
							),
6858
							admin_url( 'plugins.php' )
6859
						),
6860
						'activate-plugin_akismet/akismet.php'
6861
					)
6862
				);
6863
				?>
6864
							" class="button button-jetpack">
6865
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
6866
				</a>
6867
			<?php else : ?>
6868
				<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>
6869
			<?php endif; ?>
6870
		</div>
6871
6872
		</footer>
6873
		<?php
6874
	}
6875
6876
	/*
6877
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6878
	 */
6879
	function jetpack_icon_user_connected( $columns ) {
6880
		$columns['user_jetpack'] = '';
6881
		return $columns;
6882
	}
6883
6884
	/*
6885
	 * Show Jetpack icon if the user is linked.
6886
	 */
6887
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6888
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6889
			$jetpack_logo = new Jetpack_Logo();
6890
			$emblem_html  = sprintf(
6891
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6892
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6893
				$jetpack_logo->get_jp_emblem()
6894
			);
6895
			return $emblem_html;
6896
		}
6897
6898
		return $val;
6899
	}
6900
6901
	/*
6902
	 * Style the Jetpack user column
6903
	 */
6904
	function jetpack_user_col_style() {
6905
		global $current_screen;
6906
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6907
			?>
6908
			<style>
6909
				.fixed .column-user_jetpack {
6910
					width: 21px;
6911
				}
6912
				.jp-emblem-user-admin svg {
6913
					width: 20px;
6914
					height: 20px;
6915
				}
6916
				.jp-emblem-user-admin path {
6917
					fill: #00BE28;
6918
				}
6919
			</style>
6920
			<?php
6921
		}
6922
	}
6923
6924
	/**
6925
	 * Checks if Akismet is active and working.
6926
	 *
6927
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6928
	 * that implied usage of methods present since more recent version.
6929
	 * See https://github.com/Automattic/jetpack/pull/9585
6930
	 *
6931
	 * @since  5.1.0
6932
	 *
6933
	 * @return bool True = Akismet available. False = Aksimet not available.
6934
	 */
6935
	public static function is_akismet_active() {
6936
		static $status = null;
6937
6938
		if ( ! is_null( $status ) ) {
6939
			return $status;
6940
		}
6941
6942
		// Check if a modern version of Akismet is active.
6943
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6944
			$status = false;
6945
			return $status;
6946
		}
6947
6948
		// Make sure there is a key known to Akismet at all before verifying key.
6949
		$akismet_key = Akismet::get_api_key();
6950
		if ( ! $akismet_key ) {
6951
			$status = false;
6952
			return $status;
6953
		}
6954
6955
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6956
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6957
6958
		// 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.
6959
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6960
		// We cache the result of the Akismet key verification for ten minutes.
6961
		if ( ! $akismet_key_state || $recheck ) {
6962
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6963
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6964
		}
6965
6966
		$status = 'valid' === $akismet_key_state;
6967
6968
		return $status;
6969
	}
6970
6971
	/**
6972
	 * @deprecated
6973
	 *
6974
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6975
	 */
6976
	public static function is_function_in_backtrace() {
6977
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6978
	}
6979
6980
	/**
6981
	 * Given a minified path, and a non-minified path, will return
6982
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6983
	 *
6984
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6985
	 * root Jetpack directory.
6986
	 *
6987
	 * @since 5.6.0
6988
	 *
6989
	 * @param string $min_path
6990
	 * @param string $non_min_path
6991
	 * @return string The URL to the file
6992
	 */
6993
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6994
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6995
	}
6996
6997
	/**
6998
	 * Checks for whether Jetpack Backup & Scan is enabled.
6999
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7000
	 *
7001
	 * @return bool|int|mixed
7002
	 */
7003
	public static function is_rewind_enabled() {
7004
		if ( ! self::is_active() ) {
7005
			return false;
7006
		}
7007
7008
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7009
		if ( false === $rewind_enabled ) {
7010
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7011
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7012
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7013
				&& ! empty( $rewind_data['state'] )
7014
				&& 'active' === $rewind_data['state'] )
7015
				? 1
7016
				: 0;
7017
7018
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7019
		}
7020
		return $rewind_enabled;
7021
	}
7022
7023
	/**
7024
	 * Return Calypso environment value; used for developing Jetpack and pairing
7025
	 * it with different Calypso enrionments, such as localhost.
7026
	 *
7027
	 * @since 7.4.0
7028
	 *
7029
	 * @return string Calypso environment
7030
	 */
7031
	public static function get_calypso_env() {
7032
		if ( isset( $_GET['calypso_env'] ) ) {
7033
			return sanitize_key( $_GET['calypso_env'] );
7034
		}
7035
7036
		if ( getenv( 'CALYPSO_ENV' ) ) {
7037
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7038
		}
7039
7040
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7041
			return sanitize_key( CALYPSO_ENV );
7042
		}
7043
7044
		return '';
7045
	}
7046
7047
	/**
7048
	 * Checks whether or not TOS has been agreed upon.
7049
	 * Will return true if a user has clicked to register, or is already connected.
7050
	 */
7051
	public static function jetpack_tos_agreed() {
7052
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7053
7054
		$terms_of_service = new Terms_Of_Service();
7055
		return $terms_of_service->has_agreed();
7056
7057
	}
7058
7059
	/**
7060
	 * Handles activating default modules as well general cleanup for the new connection.
7061
	 *
7062
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7063
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7064
	 * @param boolean $send_state_messages          Whether to send state messages.
7065
	 * @return void
7066
	 */
7067
	public static function handle_post_authorization_actions(
7068
		$activate_sso = false,
7069
		$redirect_on_activation_error = false,
7070
		$send_state_messages = true
7071
	) {
7072
		$other_modules = $activate_sso
7073
			? array( 'sso' )
7074
			: array();
7075
7076
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7077
			self::delete_active_modules();
7078
7079
			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...
7080
		} else {
7081
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7082
		}
7083
7084
		// Since this is a fresh connection, be sure to clear out IDC options
7085
		Jetpack_IDC::clear_all_idc_options();
7086
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7087
7088
		// Start nonce cleaner
7089
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7090
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7091
7092
		if ( $send_state_messages ) {
7093
			self::state( 'message', 'authorized' );
7094
		}
7095
	}
7096
7097
	/**
7098
	 * Returns a boolean for whether backups UI should be displayed or not.
7099
	 *
7100
	 * @return bool Should backups UI be displayed?
7101
	 */
7102
	public static function show_backups_ui() {
7103
		/**
7104
		 * Whether UI for backups should be displayed.
7105
		 *
7106
		 * @since 6.5.0
7107
		 *
7108
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7109
		 */
7110
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7111
	}
7112
7113
	/*
7114
	 * Deprecated manage functions
7115
	 */
7116
	function prepare_manage_jetpack_notice() {
7117
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7118
	}
7119
	function manage_activate_screen() {
7120
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7121
	}
7122
	function admin_jetpack_manage_notice() {
7123
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7124
	}
7125
	function opt_out_jetpack_manage_url() {
7126
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7127
	}
7128
	function opt_in_jetpack_manage_url() {
7129
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7130
	}
7131
	function opt_in_jetpack_manage_notice() {
7132
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7133
	}
7134
	function can_display_jetpack_manage_notice() {
7135
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7136
	}
7137
7138
	/**
7139
	 * Clean leftoveruser meta.
7140
	 *
7141
	 * Delete Jetpack-related user meta when it is no longer needed.
7142
	 *
7143
	 * @since 7.3.0
7144
	 *
7145
	 * @param int $user_id User ID being updated.
7146
	 */
7147
	public static function user_meta_cleanup( $user_id ) {
7148
		$meta_keys = array(
7149
			// AtD removed from Jetpack 7.3
7150
			'AtD_options',
7151
			'AtD_check_when',
7152
			'AtD_guess_lang',
7153
			'AtD_ignored_phrases',
7154
		);
7155
7156
		foreach ( $meta_keys as $meta_key ) {
7157
			if ( get_user_meta( $user_id, $meta_key ) ) {
7158
				delete_user_meta( $user_id, $meta_key );
7159
			}
7160
		}
7161
	}
7162
7163
	/**
7164
	 * Checks if a Jetpack site is both active and not in development.
7165
	 *
7166
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7167
	 *
7168
	 * @return bool True if Jetpack is active and not in development.
7169
	 */
7170
	public static function is_active_and_not_development_mode() {
7171
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7172
			return false;
7173
		}
7174
		return true;
7175
	}
7176
}
7177