Completed
Push — fix/admin-menu-rtl-styles ( 20fd4e...fb884e )
by
unknown
11:25
created

Jetpack   F

Complexity

Total Complexity 1020

Size/Duplication

Total Lines 7573
Duplicated Lines 4.42 %

Coupling/Cohesion

Components 3
Dependencies 46

Importance

Changes 0
Metric Value
dl 335
loc 7573
rs 0.8
c 0
b 0
f 0
wmc 1020
lcom 3
cbo 46

263 Methods

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

How to fix   Duplicated Code    Complexity   

Duplicated Code

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

Common duplication problems, and corresponding solutions are:

Complex Class

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
895
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
896
		} else {
897
			/**
898
			 * Initialize tracking right after the user agrees to the terms of service.
899
			 */
900
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
901
		}
902
	}
903
904
	/**
905
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
906
	 * initialization code.
907
	 *
908
	 * @action plugins_loaded
909
	 */
910
	public function late_initialization() {
911
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
912
913
		Partner::init();
914
915
		/**
916
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
917
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
918
		 *
919
		 * @since 8.1.0
920
		 *
921
		 * @param Jetpack $jetpack the main plugin class object.
922
		 */
923
		do_action( 'jetpack_loaded', $this );
924
925
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
926
	}
927
928
	/**
929
	 * Sets up the XMLRPC request handlers.
930
	 *
931
	 * @deprecated since 7.7.0
932
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
933
	 *
934
	 * @param array                 $request_params Incoming request parameters.
935
	 * @param Boolean               $is_active      Whether the connection is currently active.
936
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
937
	 * @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...
938
	 */
939 View Code Duplication
	public function setup_xmlrpc_handlers(
940
		$request_params,
941
		$is_active,
942
		$is_signed,
943
		Jetpack_XMLRPC_Server $xmlrpc_server = null
944
	) {
945
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
946
947
		if ( ! $this->connection_manager ) {
948
			$this->connection_manager = new Connection_Manager();
949
		}
950
951
		return $this->connection_manager->setup_xmlrpc_handlers(
952
			$request_params,
953
			$is_active,
954
			$is_signed,
955
			$xmlrpc_server
956
		);
957
	}
958
959
	/**
960
	 * Initialize REST API registration connector.
961
	 *
962
	 * @deprecated since 7.7.0
963
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
964
	 */
965 View Code Duplication
	public function initialize_rest_api_registration_connector() {
966
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
967
968
		if ( ! $this->connection_manager ) {
969
			$this->connection_manager = new Connection_Manager();
970
		}
971
972
		$this->connection_manager->initialize_rest_api_registration_connector();
973
	}
974
975
	/**
976
	 * This is ported over from the manage module, which has been deprecated and baked in here.
977
	 *
978
	 * @param $domains
979
	 */
980
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
981
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
982
	}
983
984
	/**
985
	 * Return $domains, with 'wordpress.com' appended.
986
	 * This is ported over from the manage module, which has been deprecated and baked in here.
987
	 *
988
	 * @param $domains
989
	 * @return array
990
	 */
991
	function allow_wpcom_domain( $domains ) {
992
		if ( empty( $domains ) ) {
993
			$domains = array();
994
		}
995
		$domains[] = 'wordpress.com';
996
		return array_unique( $domains );
997
	}
998
999
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
1000
		$post = get_post( $post_id );
1001
1002
		if ( empty( $post ) ) {
1003
			return $default_url;
1004
		}
1005
1006
		$post_type = $post->post_type;
1007
1008
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1009
		// https://en.support.wordpress.com/custom-post-types/
1010
		$allowed_post_types = array(
1011
			'post',
1012
			'page',
1013
			'jetpack-portfolio',
1014
			'jetpack-testimonial',
1015
		);
1016
1017
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1018
			return $default_url;
1019
		}
1020
1021
		return Redirect::get_url(
1022
			'calypso-edit-' . $post_type,
1023
			array(
1024
				'path' => $post_id,
1025
			)
1026
		);
1027
	}
1028
1029
	function point_edit_comment_links_to_calypso( $url ) {
1030
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1031
		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...
1032
1033
		return Redirect::get_url(
1034
			'calypso-edit-comment',
1035
			array(
1036
				'path' => $query_args['amp;c'],
1037
			)
1038
		);
1039
1040
	}
1041
1042
	/**
1043
	 * Extend Sync callables with Jetpack Plugin functions.
1044
	 *
1045
	 * @param array $callables list of callables.
1046
	 *
1047
	 * @return array list of callables.
1048
	 */
1049
	public function filter_sync_callable_whitelist( $callables ) {
1050
1051
		// Jetpack Functions.
1052
		$jetpack_callables = array(
1053
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1054
			'updates'                  => array( 'Jetpack', 'get_updates' ),
1055
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1056
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1057
		);
1058
		$callables         = array_merge( $callables, $jetpack_callables );
1059
1060
		// Jetpack_SSO_Helpers.
1061
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1062
			$sso_helpers = array(
1063
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1064
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1065
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1066
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1067
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1068
			);
1069
			$callables   = array_merge( $callables, $sso_helpers );
1070
		}
1071
1072
		return $callables;
1073
	}
1074
1075
	/**
1076
	 * Extend Sync multisite callables with Jetpack Plugin functions.
1077
	 *
1078
	 * @param array $callables list of callables.
1079
	 *
1080
	 * @return array list of callables.
1081
	 */
1082
	public function filter_sync_multisite_callable_whitelist( $callables ) {
1083
1084
		// Jetpack Funtions.
1085
		$jetpack_multisite_callables = array(
1086
			'network_name'                        => array( 'Jetpack', 'network_name' ),
1087
			'network_allow_new_registrations'     => array( 'Jetpack', 'network_allow_new_registrations' ),
1088
			'network_add_new_users'               => array( 'Jetpack', 'network_add_new_users' ),
1089
			'network_site_upload_space'           => array( 'Jetpack', 'network_site_upload_space' ),
1090
			'network_upload_file_types'           => array( 'Jetpack', 'network_upload_file_types' ),
1091
			'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1092
		);
1093
		$callables                   = array_merge( $callables, $jetpack_multisite_callables );
1094
1095
		return $callables;
1096
	}
1097
1098
	function jetpack_track_last_sync_callback( $params ) {
1099
		/**
1100
		 * Filter to turn off jitm caching
1101
		 *
1102
		 * @since 5.4.0
1103
		 *
1104
		 * @param bool false Whether to cache just in time messages
1105
		 */
1106
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1107
			return $params;
1108
		}
1109
1110
		if ( is_array( $params ) && isset( $params[0] ) ) {
1111
			$option = $params[0];
1112
			if ( 'active_plugins' === $option ) {
1113
				// use the cache if we can, but not terribly important if it gets evicted
1114
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1115
			}
1116
		}
1117
1118
		return $params;
1119
	}
1120
1121
	function jetpack_connection_banner_callback() {
1122
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1123
1124
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1125
		if (
1126
			isset( $_REQUEST['dismissBanner'] ) &&
1127
			! Jetpack_Connection_Banner::force_display()
1128
		) {
1129
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1130
			wp_send_json_success();
1131
		}
1132
1133
		wp_die();
1134
	}
1135
1136
	/**
1137
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1138
	 * Only used in our alternate XML-RPC endpoint, where we want to
1139
	 * ensure that Core and other plugins' methods are not exposed.
1140
	 *
1141
	 * @deprecated since 7.7.0
1142
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1143
	 *
1144
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1145
	 * @return array Filtered $methods
1146
	 */
1147 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1148
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1149
1150
		if ( ! $this->connection_manager ) {
1151
			$this->connection_manager = new Connection_Manager();
1152
		}
1153
1154
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1155
	}
1156
1157
	/**
1158
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1159
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1160
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1161
	 * which is accessible via a different URI. Most of the below is copied directly
1162
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1163
	 *
1164
	 * @deprecated since 7.7.0
1165
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1166
	 */
1167 View Code Duplication
	public function alternate_xmlrpc() {
1168
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1169
1170
		if ( ! $this->connection_manager ) {
1171
			$this->connection_manager = new Connection_Manager();
1172
		}
1173
1174
		$this->connection_manager->alternate_xmlrpc();
1175
	}
1176
1177
	/**
1178
	 * The callback for the JITM ajax requests.
1179
	 *
1180
	 * @deprecated since 7.9.0
1181
	 */
1182
	function jetpack_jitm_ajax_callback() {
1183
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1184
	}
1185
1186
	/**
1187
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1188
	 */
1189
	function push_stats() {
1190
		if ( ! empty( $this->stats ) ) {
1191
			$this->do_stats( 'server_side' );
1192
		}
1193
	}
1194
1195
	/**
1196
	 * Sets the Jetpack custom capabilities.
1197
	 *
1198
	 * @param string[] $caps    Array of the user's capabilities.
1199
	 * @param string   $cap     Capability name.
1200
	 * @param int      $user_id The user ID.
1201
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1202
	 */
1203
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1204
		switch ( $cap ) {
1205
			case 'jetpack_manage_modules':
1206
			case 'jetpack_activate_modules':
1207
			case 'jetpack_deactivate_modules':
1208
				$caps = array( 'manage_options' );
1209
				break;
1210
			case 'jetpack_configure_modules':
1211
				$caps = array( 'manage_options' );
1212
				break;
1213
			case 'jetpack_manage_autoupdates':
1214
				$caps = array(
1215
					'manage_options',
1216
					'update_plugins',
1217
				);
1218
				break;
1219
			case 'jetpack_network_admin_page':
1220
			case 'jetpack_network_settings_page':
1221
				$caps = array( 'manage_network_plugins' );
1222
				break;
1223
			case 'jetpack_network_sites_page':
1224
				$caps = array( 'manage_sites' );
1225
				break;
1226 View Code Duplication
			case 'jetpack_admin_page':
1227
				$is_offline_mode = ( new Status() )->is_offline_mode();
1228
				if ( $is_offline_mode ) {
1229
					$caps = array( 'manage_options' );
1230
					break;
1231
				} else {
1232
					$caps = array( 'read' );
1233
				}
1234
				break;
1235
		}
1236
		return $caps;
1237
	}
1238
1239
	/**
1240
	 * Require a Jetpack authentication.
1241
	 *
1242
	 * @deprecated since 7.7.0
1243
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1244
	 */
1245 View Code Duplication
	public function require_jetpack_authentication() {
1246
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1247
1248
		if ( ! $this->connection_manager ) {
1249
			$this->connection_manager = new Connection_Manager();
1250
		}
1251
1252
		$this->connection_manager->require_jetpack_authentication();
1253
	}
1254
1255
	/**
1256
	 * Register assets for use in various modules and the Jetpack admin page.
1257
	 *
1258
	 * @uses wp_script_is, wp_register_script, plugins_url
1259
	 * @action wp_loaded
1260
	 * @return null
1261
	 */
1262
	public function register_assets() {
1263 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1264
			wp_register_script(
1265
				'jetpack-gallery-settings',
1266
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1267
				array( 'media-views' ),
1268
				'20121225'
1269
			);
1270
		}
1271
1272
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1273
			wp_register_script(
1274
				'jetpack-twitter-timeline',
1275
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1276
				array( 'jquery' ),
1277
				'4.0.0',
1278
				true
1279
			);
1280
		}
1281
1282
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1283
			wp_register_script(
1284
				'jetpack-facebook-embed',
1285
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1286
				array(),
1287
				null,
1288
				true
1289
			);
1290
1291
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1292
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1293
			if ( ! is_numeric( $fb_app_id ) ) {
1294
				$fb_app_id = '';
1295
			}
1296
			wp_localize_script(
1297
				'jetpack-facebook-embed',
1298
				'jpfbembed',
1299
				array(
1300
					'appid'  => $fb_app_id,
1301
					'locale' => $this->get_locale(),
1302
				)
1303
			);
1304
		}
1305
1306
		/**
1307
		 * As jetpack_register_genericons is by default fired off a hook,
1308
		 * the hook may have already fired by this point.
1309
		 * So, let's just trigger it manually.
1310
		 */
1311
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1312
		jetpack_register_genericons();
1313
1314
		/**
1315
		 * Register the social logos
1316
		 */
1317
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1318
		jetpack_register_social_logos();
1319
1320
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1321
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1322
		}
1323
	}
1324
1325
	/**
1326
	 * Guess locale from language code.
1327
	 *
1328
	 * @param string $lang Language code.
1329
	 * @return string|bool
1330
	 */
1331 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1332
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1333
			return 'en_US';
1334
		}
1335
1336
		if ( ! class_exists( 'GP_Locales' ) ) {
1337
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1338
				return false;
1339
			}
1340
1341
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1342
		}
1343
1344
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1345
			// WP.com: get_locale() returns 'it'
1346
			$locale = GP_Locales::by_slug( $lang );
1347
		} else {
1348
			// Jetpack: get_locale() returns 'it_IT';
1349
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1350
		}
1351
1352
		if ( ! $locale ) {
1353
			return false;
1354
		}
1355
1356
		if ( empty( $locale->facebook_locale ) ) {
1357
			if ( empty( $locale->wp_locale ) ) {
1358
				return false;
1359
			} else {
1360
				// Facebook SDK is smart enough to fall back to en_US if a
1361
				// locale isn't supported. Since supported Facebook locales
1362
				// can fall out of sync, we'll attempt to use the known
1363
				// wp_locale value and rely on said fallback.
1364
				return $locale->wp_locale;
1365
			}
1366
		}
1367
1368
		return $locale->facebook_locale;
1369
	}
1370
1371
	/**
1372
	 * Get the locale.
1373
	 *
1374
	 * @return string|bool
1375
	 */
1376
	function get_locale() {
1377
		$locale = $this->guess_locale_from_lang( get_locale() );
1378
1379
		if ( ! $locale ) {
1380
			$locale = 'en_US';
1381
		}
1382
1383
		return $locale;
1384
	}
1385
1386
	/**
1387
	 * Return the network_site_url so that .com knows what network this site is a part of.
1388
	 *
1389
	 * @param  bool $option
1390
	 * @return string
1391
	 */
1392
	public function jetpack_main_network_site_option( $option ) {
1393
		return network_site_url();
1394
	}
1395
	/**
1396
	 * Network Name.
1397
	 */
1398
	static function network_name( $option = null ) {
1399
		global $current_site;
1400
		return $current_site->site_name;
1401
	}
1402
	/**
1403
	 * Does the network allow new user and site registrations.
1404
	 *
1405
	 * @return string
1406
	 */
1407
	static function network_allow_new_registrations( $option = null ) {
1408
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1409
	}
1410
	/**
1411
	 * Does the network allow admins to add new users.
1412
	 *
1413
	 * @return boolian
1414
	 */
1415
	static function network_add_new_users( $option = null ) {
1416
		return (bool) get_site_option( 'add_new_users' );
1417
	}
1418
	/**
1419
	 * File upload psace left per site in MB.
1420
	 *  -1 means NO LIMIT.
1421
	 *
1422
	 * @return number
1423
	 */
1424
	static function network_site_upload_space( $option = null ) {
1425
		// value in MB
1426
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1427
	}
1428
1429
	/**
1430
	 * Network allowed file types.
1431
	 *
1432
	 * @return string
1433
	 */
1434
	static function network_upload_file_types( $option = null ) {
1435
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1436
	}
1437
1438
	/**
1439
	 * Maximum file upload size set by the network.
1440
	 *
1441
	 * @return number
1442
	 */
1443
	static function network_max_upload_file_size( $option = null ) {
1444
		// value in KB
1445
		return get_site_option( 'fileupload_maxk', 300 );
1446
	}
1447
1448
	/**
1449
	 * Lets us know if a site allows admins to manage the network.
1450
	 *
1451
	 * @return array
1452
	 */
1453
	static function network_enable_administration_menus( $option = null ) {
1454
		return get_site_option( 'menu_items' );
1455
	}
1456
1457
	/**
1458
	 * If a user has been promoted to or demoted from admin, we need to clear the
1459
	 * jetpack_other_linked_admins transient.
1460
	 *
1461
	 * @since 4.3.2
1462
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1463
	 *
1464
	 * @param int    $user_id   The user ID whose role changed.
1465
	 * @param string $role      The new role.
1466
	 * @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...
1467
	 */
1468
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1469
		if ( 'administrator' == $role
1470
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1471
			|| is_null( $old_roles )
1472
		) {
1473
			delete_transient( 'jetpack_other_linked_admins' );
1474
		}
1475
	}
1476
1477
	/**
1478
	 * Checks to see if there are any other users available to become primary
1479
	 * Users must both:
1480
	 * - Be linked to wpcom
1481
	 * - Be an admin
1482
	 *
1483
	 * @return mixed False if no other users are linked, Int if there are.
1484
	 */
1485
	static function get_other_linked_admins() {
1486
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1487
1488
		if ( false === $other_linked_users ) {
1489
			$admins = get_users( array( 'role' => 'administrator' ) );
1490
			if ( count( $admins ) > 1 ) {
1491
				$available = array();
1492
				foreach ( $admins as $admin ) {
1493
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1494
						$available[] = $admin->ID;
1495
					}
1496
				}
1497
1498
				$count_connected_admins = count( $available );
1499
				if ( count( $available ) > 1 ) {
1500
					$other_linked_users = $count_connected_admins;
1501
				} else {
1502
					$other_linked_users = 0;
1503
				}
1504
			} else {
1505
				$other_linked_users = 0;
1506
			}
1507
1508
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1509
		}
1510
1511
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1512
	}
1513
1514
	/**
1515
	 * Return whether we are dealing with a multi network setup or not.
1516
	 * The reason we are type casting this is because we want to avoid the situation where
1517
	 * the result is false since when is_main_network_option return false it cases
1518
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1519
	 * database which could be set to anything as opposed to what this function returns.
1520
	 *
1521
	 * @param  bool $option
1522
	 *
1523
	 * @return boolean
1524
	 */
1525
	public function is_main_network_option( $option ) {
1526
		// return '1' or ''
1527
		return (string) (bool) self::is_multi_network();
1528
	}
1529
1530
	/**
1531
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1532
	 *
1533
	 * @param  string $option
1534
	 * @return boolean
1535
	 */
1536
	public function is_multisite( $option ) {
1537
		return (string) (bool) is_multisite();
1538
	}
1539
1540
	/**
1541
	 * Implemented since there is no core is multi network function
1542
	 * Right now there is no way to tell if we which network is the dominant network on the system
1543
	 *
1544
	 * @since  3.3
1545
	 * @return boolean
1546
	 */
1547 View Code Duplication
	public static function is_multi_network() {
1548
		global  $wpdb;
1549
1550
		// if we don't have a multi site setup no need to do any more
1551
		if ( ! is_multisite() ) {
1552
			return false;
1553
		}
1554
1555
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1556
		if ( $num_sites > 1 ) {
1557
			return true;
1558
		} else {
1559
			return false;
1560
		}
1561
	}
1562
1563
	/**
1564
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1565
	 *
1566
	 * @return null
1567
	 */
1568
	function update_jetpack_main_network_site_option() {
1569
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1570
	}
1571
	/**
1572
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1573
	 */
1574
	function update_jetpack_network_settings() {
1575
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1576
		// Only sync this info for the main network site.
1577
	}
1578
1579
	/**
1580
	 * Get back if the current site is single user site.
1581
	 *
1582
	 * @return bool
1583
	 */
1584 View Code Duplication
	public static function is_single_user_site() {
1585
		global $wpdb;
1586
1587
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1588
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1589
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1590
		}
1591
		return 1 === (int) $some_users;
1592
	}
1593
1594
	/**
1595
	 * Returns true if the site has file write access false otherwise.
1596
	 *
1597
	 * @return string ( '1' | '0' )
1598
	 **/
1599
	public static function file_system_write_access() {
1600
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1601
			require_once ABSPATH . 'wp-admin/includes/file.php';
1602
		}
1603
1604
		require_once ABSPATH . 'wp-admin/includes/template.php';
1605
1606
		$filesystem_method = get_filesystem_method();
1607
		if ( $filesystem_method === 'direct' ) {
1608
			return 1;
1609
		}
1610
1611
		ob_start();
1612
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1613
		ob_end_clean();
1614
		if ( $filesystem_credentials_are_stored ) {
1615
			return 1;
1616
		}
1617
		return 0;
1618
	}
1619
1620
	/**
1621
	 * Finds out if a site is using a version control system.
1622
	 *
1623
	 * @return string ( '1' | '0' )
1624
	 **/
1625
	public static function is_version_controlled() {
1626
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1627
		return (string) (int) Functions::is_version_controlled();
1628
	}
1629
1630
	/**
1631
	 * Determines whether the current theme supports featured images or not.
1632
	 *
1633
	 * @return string ( '1' | '0' )
1634
	 */
1635
	public static function featured_images_enabled() {
1636
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1637
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1638
	}
1639
1640
	/**
1641
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1642
	 *
1643
	 * @deprecated 4.7 use get_avatar_url instead.
1644
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1645
	 * @param int               $size Size of the avatar image
1646
	 * @param string            $default URL to a default image to use if no avatar is available
1647
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1648
	 *
1649
	 * @return array
1650
	 */
1651
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1652
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1653
		return get_avatar_url(
1654
			$id_or_email,
1655
			array(
1656
				'size'          => $size,
1657
				'default'       => $default,
1658
				'force_default' => $force_display,
1659
			)
1660
		);
1661
	}
1662
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1663
	/**
1664
	 * jetpack_updates is saved in the following schema:
1665
	 *
1666
	 * array (
1667
	 *      'plugins'                       => (int) Number of plugin updates available.
1668
	 *      'themes'                        => (int) Number of theme updates available.
1669
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1670
	 *      'translations'                  => (int) Number of translation updates available.
1671
	 *      'total'                         => (int) Total of all available updates.
1672
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1673
	 * )
1674
	 *
1675
	 * @return array
1676
	 */
1677
	public static function get_updates() {
1678
		$update_data = wp_get_update_data();
1679
1680
		// Stores the individual update counts as well as the total count.
1681
		if ( isset( $update_data['counts'] ) ) {
1682
			$updates = $update_data['counts'];
1683
		}
1684
1685
		// If we need to update WordPress core, let's find the latest version number.
1686 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1687
			$cur = get_preferred_from_update_core();
1688
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1689
				$updates['wp_update_version'] = $cur->current;
1690
			}
1691
		}
1692
		return isset( $updates ) ? $updates : array();
1693
	}
1694
	// phpcs:enable
1695
1696
	public static function get_update_details() {
1697
		$update_details = array(
1698
			'update_core'    => get_site_transient( 'update_core' ),
1699
			'update_plugins' => get_site_transient( 'update_plugins' ),
1700
			'update_themes'  => get_site_transient( 'update_themes' ),
1701
		);
1702
		return $update_details;
1703
	}
1704
1705
	public static function refresh_update_data() {
1706
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1707
1708
	}
1709
1710
	public static function refresh_theme_data() {
1711
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1712
	}
1713
1714
	/**
1715
	 * Is Jetpack active?
1716
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1717
	 *
1718
	 * This method is deprecated since 9.6.0. Please use one of the methods provided by the Manager class in the Connection package,
1719
	 * or Jetpack::is_connection_ready if you want to know when the Jetpack plugin starts considering the connection ready to be used.
1720
	 *
1721
	 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
1722
	 *
1723
	 * @deprecated 9.6.0
1724
	 *
1725
	 * @return bool
1726
	 */
1727
	public static function is_active() {
1728
		return self::connection()->is_active();
0 ignored issues
show
Deprecated Code introduced by
The method Automattic\Jetpack\Connection\Manager::is_active() has been deprecated with message: 9.6.0

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...
1729
	}
1730
1731
	/**
1732
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1733
	 *
1734
	 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1735
	 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1736
	 * users and this option will be available by default for everybody.
1737
	 *
1738
	 * @since 9.6.0
1739
	 *
1740
	 * @return bool is the site connection ready to be used?
1741
	 */
1742
	public static function is_connection_ready() {
1743
		if ( ( new Status() )->is_no_user_testing_mode() ) {
1744
			return self::connection()->is_connected();
1745
		}
1746
		return (bool) self::connection()->has_connected_owner();
1747
	}
1748
1749
	/**
1750
	 * Make an API call to WordPress.com for plan status
1751
	 *
1752
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1753
	 *
1754
	 * @return bool True if plan is updated, false if no update
1755
	 */
1756
	public static function refresh_active_plan_from_wpcom() {
1757
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1758
		return Jetpack_Plan::refresh_from_wpcom();
1759
	}
1760
1761
	/**
1762
	 * Get the plan that this Jetpack site is currently using
1763
	 *
1764
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1765
	 * @return array Active Jetpack plan details.
1766
	 */
1767
	public static function get_active_plan() {
1768
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1769
		return Jetpack_Plan::get();
1770
	}
1771
1772
	/**
1773
	 * Determine whether the active plan supports a particular feature
1774
	 *
1775
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1776
	 * @return bool True if plan supports feature, false if not.
1777
	 */
1778
	public static function active_plan_supports( $feature ) {
1779
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1780
		return Jetpack_Plan::supports( $feature );
1781
	}
1782
1783
	/**
1784
	 * Deprecated: Is Jetpack in development (offline) mode?
1785
	 *
1786
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1787
	 * and themes still use it, and we do not want to flood them with notices.
1788
	 *
1789
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1790
	 *
1791
	 * @deprecated since 8.0.
1792
	 */
1793
	public static function is_development_mode() {
1794
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1795
		return ( new Status() )->is_offline_mode();
1796
	}
1797
1798
	/**
1799
	 * Whether the site is currently onboarding or not.
1800
	 * A site is considered as being onboarded if it currently has an onboarding token.
1801
	 *
1802
	 * @since 5.8
1803
	 *
1804
	 * @access public
1805
	 * @static
1806
	 *
1807
	 * @return bool True if the site is currently onboarding, false otherwise
1808
	 */
1809
	public static function is_onboarding() {
1810
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1811
	}
1812
1813
	/**
1814
	 * Determines reason for Jetpack offline mode.
1815
	 */
1816
	public static function development_mode_trigger_text() {
1817
		$status = new Status();
1818
1819
		if ( ! $status->is_offline_mode() ) {
1820
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1821
		}
1822
1823
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1824
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1825
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1826
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1827
		} elseif ( $status->is_local_site() ) {
1828
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1829
			/** This filter is documented in packages/status/src/class-status.php */
1830
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1831
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1832
		} else {
1833
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1834
		}
1835
1836
		return $notice;
1837
1838
	}
1839
	/**
1840
	 * Get Jetpack offline mode notice text and notice class.
1841
	 *
1842
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1843
	 */
1844
	public static function show_development_mode_notice() {
1845 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1846
			$notice = sprintf(
1847
				/* translators: %s is a URL */
1848
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1849
				Redirect::get_url( 'jetpack-support-development-mode' )
1850
			);
1851
1852
			$notice .= ' ' . self::development_mode_trigger_text();
1853
1854
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1855
		}
1856
1857
		// Throw up a notice if using a development version and as for feedback.
1858
		if ( self::is_development_version() ) {
1859
			/* translators: %s is a URL */
1860
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), Redirect::get_url( 'jetpack-contact-support-beta-group' ) );
1861
1862
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1863
		}
1864
		// Throw up a notice if using staging mode
1865 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1866
			/* translators: %s is a URL */
1867
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1868
1869
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1870
		}
1871
	}
1872
1873
	/**
1874
	 * Whether Jetpack's version maps to a public release, or a development version.
1875
	 */
1876
	public static function is_development_version() {
1877
		/**
1878
		 * Allows filtering whether this is a development version of Jetpack.
1879
		 *
1880
		 * This filter is especially useful for tests.
1881
		 *
1882
		 * @since 4.3.0
1883
		 *
1884
		 * @param bool $development_version Is this a develoment version of Jetpack?
1885
		 */
1886
		return (bool) apply_filters(
1887
			'jetpack_development_version',
1888
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1889
		);
1890
	}
1891
1892
	/**
1893
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1894
	 */
1895
	public static function is_user_connected( $user_id = false ) {
1896
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1897
		return self::connection()->is_user_connected( $user_id );
0 ignored issues
show
Documentation introduced by
$user_id is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1898
	}
1899
1900
	/**
1901
	 * Get the wpcom user data of the current|specified connected user.
1902
	 */
1903
	public static function get_connected_user_data( $user_id = null ) {
1904
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1905
		return self::connection()->get_connected_user_data( $user_id );
1906
	}
1907
1908
	/**
1909
	 * Get the wpcom email of the current|specified connected user.
1910
	 */
1911
	public static function get_connected_user_email( $user_id = null ) {
1912
		if ( ! $user_id ) {
1913
			$user_id = get_current_user_id();
1914
		}
1915
1916
		$xml = new Jetpack_IXR_Client(
1917
			array(
1918
				'user_id' => $user_id,
1919
			)
1920
		);
1921
		$xml->query( 'wpcom.getUserEmail' );
1922
		if ( ! $xml->isError() ) {
1923
			return $xml->getResponse();
1924
		}
1925
		return false;
1926
	}
1927
1928
	/**
1929
	 * Get the wpcom email of the master user.
1930
	 */
1931
	public static function get_master_user_email() {
1932
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1933
		if ( $master_user_id ) {
1934
			return self::get_connected_user_email( $master_user_id );
1935
		}
1936
		return '';
1937
	}
1938
1939
	/**
1940
	 * Whether the current user is the connection owner.
1941
	 *
1942
	 * @deprecated since 7.7
1943
	 *
1944
	 * @return bool Whether the current user is the connection owner.
1945
	 */
1946
	public function current_user_is_connection_owner() {
1947
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1948
		return self::connection()->is_connection_owner();
1949
	}
1950
1951
	/**
1952
	 * Gets current user IP address.
1953
	 *
1954
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1955
	 *
1956
	 * @return string                  Current user IP address.
1957
	 */
1958
	public static function current_user_ip( $check_all_headers = false ) {
1959
		if ( $check_all_headers ) {
1960
			foreach ( array(
1961
				'HTTP_CF_CONNECTING_IP',
1962
				'HTTP_CLIENT_IP',
1963
				'HTTP_X_FORWARDED_FOR',
1964
				'HTTP_X_FORWARDED',
1965
				'HTTP_X_CLUSTER_CLIENT_IP',
1966
				'HTTP_FORWARDED_FOR',
1967
				'HTTP_FORWARDED',
1968
				'HTTP_VIA',
1969
			) as $key ) {
1970
				if ( ! empty( $_SERVER[ $key ] ) ) {
1971
					return $_SERVER[ $key ];
1972
				}
1973
			}
1974
		}
1975
1976
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1977
	}
1978
1979
	/**
1980
	 * Synchronize connected user role changes
1981
	 */
1982
	function user_role_change( $user_id ) {
1983
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1984
		Users::user_role_change( $user_id );
1985
	}
1986
1987
	/**
1988
	 * Loads the currently active modules.
1989
	 */
1990
	public static function load_modules() {
1991
		$is_offline_mode = ( new Status() )->is_offline_mode();
1992
		if (
1993
			! self::is_connection_ready()
1994
			&& ! $is_offline_mode
1995
			&& ! self::is_onboarding()
1996
			&& (
1997
				! is_multisite()
1998
				|| ! get_site_option( 'jetpack_protect_active' )
1999
			)
2000
		) {
2001
			return;
2002
		}
2003
2004
		$version = Jetpack_Options::get_option( 'version' );
2005 View Code Duplication
		if ( ! $version ) {
2006
			$version = $old_version = JETPACK__VERSION . ':' . time();
2007
			/** This action is documented in class.jetpack.php */
2008
			do_action( 'updating_jetpack_version', $version, false );
2009
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2010
		}
2011
		list( $version ) = explode( ':', $version );
2012
2013
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2014
2015
		$modules_data = array();
2016
2017
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2018
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2019
			$updated_modules = array();
2020
			foreach ( $modules as $module ) {
2021
				$modules_data[ $module ] = self::get_module( $module );
2022
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2023
					continue;
2024
				}
2025
2026
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2027
					continue;
2028
				}
2029
2030
				$updated_modules[] = $module;
2031
			}
2032
2033
			$modules = array_diff( $modules, $updated_modules );
2034
		}
2035
2036
		foreach ( $modules as $index => $module ) {
2037
			// If we're in offline mode, disable modules requiring a connection.
2038
			if ( $is_offline_mode ) {
2039
				// Prime the pump if we need to
2040
				if ( empty( $modules_data[ $module ] ) ) {
2041
					$modules_data[ $module ] = self::get_module( $module );
2042
				}
2043
				// If the module requires a connection, but we're in local mode, don't include it.
2044
				if ( $modules_data[ $module ]['requires_connection'] ) {
2045
					continue;
2046
				}
2047
			}
2048
2049
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2050
				continue;
2051
			}
2052
2053
			if ( ! include_once self::get_module_path( $module ) ) {
2054
				unset( $modules[ $index ] );
2055
				self::update_active_modules( array_values( $modules ) );
2056
				continue;
2057
			}
2058
2059
			/**
2060
			 * Fires when a specific module is loaded.
2061
			 * The dynamic part of the hook, $module, is the module slug.
2062
			 *
2063
			 * @since 1.1.0
2064
			 */
2065
			do_action( 'jetpack_module_loaded_' . $module );
2066
		}
2067
2068
		/**
2069
		 * Fires when all the modules are loaded.
2070
		 *
2071
		 * @since 1.1.0
2072
		 */
2073
		do_action( 'jetpack_modules_loaded' );
2074
2075
		// 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.
2076
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2077
	}
2078
2079
	/**
2080
	 * Check if Jetpack's REST API compat file should be included
2081
	 *
2082
	 * @action plugins_loaded
2083
	 * @return null
2084
	 */
2085
	public function check_rest_api_compat() {
2086
		/**
2087
		 * Filters the list of REST API compat files to be included.
2088
		 *
2089
		 * @since 2.2.5
2090
		 *
2091
		 * @param array $args Array of REST API compat files to include.
2092
		 */
2093
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2094
2095
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2096
			require_once $_jetpack_rest_api_compat_include;
2097
		}
2098
	}
2099
2100
	/**
2101
	 * Gets all plugins currently active in values, regardless of whether they're
2102
	 * traditionally activated or network activated.
2103
	 *
2104
	 * @todo Store the result in core's object cache maybe?
2105
	 */
2106
	public static function get_active_plugins() {
2107
		$active_plugins = (array) get_option( 'active_plugins', array() );
2108
2109
		if ( is_multisite() ) {
2110
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2111
			// whereas active_plugins stores them in the values.
2112
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2113
			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...
2114
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2115
			}
2116
		}
2117
2118
		sort( $active_plugins );
2119
2120
		return array_unique( $active_plugins );
2121
	}
2122
2123
	/**
2124
	 * Gets and parses additional plugin data to send with the heartbeat data
2125
	 *
2126
	 * @since 3.8.1
2127
	 *
2128
	 * @return array Array of plugin data
2129
	 */
2130
	public static function get_parsed_plugin_data() {
2131
		if ( ! function_exists( 'get_plugins' ) ) {
2132
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2133
		}
2134
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2135
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2136
		$active_plugins = self::get_active_plugins();
2137
2138
		$plugins = array();
2139
		foreach ( $all_plugins as $path => $plugin_data ) {
2140
			$plugins[ $path ] = array(
2141
				'is_active' => in_array( $path, $active_plugins ),
2142
				'file'      => $path,
2143
				'name'      => $plugin_data['Name'],
2144
				'version'   => $plugin_data['Version'],
2145
				'author'    => $plugin_data['Author'],
2146
			);
2147
		}
2148
2149
		return $plugins;
2150
	}
2151
2152
	/**
2153
	 * Gets and parses theme data to send with the heartbeat data
2154
	 *
2155
	 * @since 3.8.1
2156
	 *
2157
	 * @return array Array of theme data
2158
	 */
2159
	public static function get_parsed_theme_data() {
2160
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2161
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2162
2163
		$themes = array();
2164
		foreach ( $all_themes as $slug => $theme_data ) {
2165
			$theme_headers = array();
2166
			foreach ( $header_keys as $header_key ) {
2167
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2168
			}
2169
2170
			$themes[ $slug ] = array(
2171
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2172
				'slug'            => $slug,
2173
				'theme_root'      => $theme_data->get_theme_root_uri(),
2174
				'parent'          => $theme_data->parent(),
2175
				'headers'         => $theme_headers,
2176
			);
2177
		}
2178
2179
		return $themes;
2180
	}
2181
2182
	/**
2183
	 * Checks whether a specific plugin is active.
2184
	 *
2185
	 * We don't want to store these in a static variable, in case
2186
	 * there are switch_to_blog() calls involved.
2187
	 */
2188
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2189
		return in_array( $plugin, self::get_active_plugins() );
2190
	}
2191
2192
	/**
2193
	 * Check if Jetpack's Open Graph tags should be used.
2194
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2195
	 *
2196
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2197
	 * @action plugins_loaded
2198
	 * @return null
2199
	 */
2200
	public function check_open_graph() {
2201
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2202
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2203
		}
2204
2205
		$active_plugins = self::get_active_plugins();
2206
2207
		if ( ! empty( $active_plugins ) ) {
2208
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2209
				if ( in_array( $plugin, $active_plugins ) ) {
2210
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2211
					break;
2212
				}
2213
			}
2214
		}
2215
2216
		/**
2217
		 * Allow the addition of Open Graph Meta Tags to all pages.
2218
		 *
2219
		 * @since 2.0.3
2220
		 *
2221
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2222
		 */
2223
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2224
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2225
		}
2226
	}
2227
2228
	/**
2229
	 * Check if Jetpack's Twitter tags should be used.
2230
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2231
	 *
2232
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2233
	 * @action plugins_loaded
2234
	 * @return null
2235
	 */
2236
	public function check_twitter_tags() {
2237
2238
		$active_plugins = self::get_active_plugins();
2239
2240
		if ( ! empty( $active_plugins ) ) {
2241
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2242
				if ( in_array( $plugin, $active_plugins ) ) {
2243
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2244
					break;
2245
				}
2246
			}
2247
		}
2248
2249
		/**
2250
		 * Allow Twitter Card Meta tags to be disabled.
2251
		 *
2252
		 * @since 2.6.0
2253
		 *
2254
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2255
		 */
2256
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2257
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2258
		}
2259
	}
2260
2261
	/**
2262
	 * Allows plugins to submit security reports.
2263
	 *
2264
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2265
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2266
	 * @param array  $args         See definitions above
2267
	 */
2268
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2269
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2270
	}
2271
2272
	/* Jetpack Options API */
2273
2274
	public static function get_option_names( $type = 'compact' ) {
2275
		return Jetpack_Options::get_option_names( $type );
2276
	}
2277
2278
	/**
2279
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2280
	 *
2281
	 * @param string $name    Option name
2282
	 * @param mixed  $default (optional)
2283
	 */
2284
	public static function get_option( $name, $default = false ) {
2285
		return Jetpack_Options::get_option( $name, $default );
2286
	}
2287
2288
	/**
2289
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2290
	 *
2291
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2292
	 * @param string $name  Option name
2293
	 * @param mixed  $value Option value
2294
	 */
2295
	public static function update_option( $name, $value ) {
2296
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2297
		return Jetpack_Options::update_option( $name, $value );
2298
	}
2299
2300
	/**
2301
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2302
	 *
2303
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2304
	 * @param array $array array( option name => option value, ... )
2305
	 */
2306
	public static function update_options( $array ) {
2307
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2308
		return Jetpack_Options::update_options( $array );
2309
	}
2310
2311
	/**
2312
	 * Deletes the given option.  May be passed multiple option names as an array.
2313
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2314
	 *
2315
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2316
	 * @param string|array $names
2317
	 */
2318
	public static function delete_option( $names ) {
2319
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2320
		return Jetpack_Options::delete_option( $names );
2321
	}
2322
2323
	/**
2324
	 * Enters a user token into the user_tokens option
2325
	 *
2326
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2327
	 *
2328
	 * @param int    $user_id The user id.
2329
	 * @param string $token The user token.
2330
	 * @param bool   $is_master_user Whether the user is the master user.
2331
	 * @return bool
2332
	 */
2333
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2334
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2335
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2336
	}
2337
2338
	/**
2339
	 * Returns an array of all PHP files in the specified absolute path.
2340
	 * Equivalent to glob( "$absolute_path/*.php" ).
2341
	 *
2342
	 * @param string $absolute_path The absolute path of the directory to search.
2343
	 * @return array Array of absolute paths to the PHP files.
2344
	 */
2345
	public static function glob_php( $absolute_path ) {
2346
		if ( function_exists( 'glob' ) ) {
2347
			return glob( "$absolute_path/*.php" );
2348
		}
2349
2350
		$absolute_path = untrailingslashit( $absolute_path );
2351
		$files         = array();
2352
		if ( ! $dir = @opendir( $absolute_path ) ) {
2353
			return $files;
2354
		}
2355
2356
		while ( false !== $file = readdir( $dir ) ) {
2357
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2358
				continue;
2359
			}
2360
2361
			$file = "$absolute_path/$file";
2362
2363
			if ( ! is_file( $file ) ) {
2364
				continue;
2365
			}
2366
2367
			$files[] = $file;
2368
		}
2369
2370
		closedir( $dir );
2371
2372
		return $files;
2373
	}
2374
2375
	public static function activate_new_modules( $redirect = false ) {
2376
		if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2377
			return;
2378
		}
2379
2380
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2381 View Code Duplication
		if ( ! $jetpack_old_version ) {
2382
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2383
			/** This action is documented in class.jetpack.php */
2384
			do_action( 'updating_jetpack_version', $version, false );
2385
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2386
		}
2387
2388
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2389
2390
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2391
			return;
2392
		}
2393
2394
		$active_modules     = self::get_active_modules();
2395
		$reactivate_modules = array();
2396
		foreach ( $active_modules as $active_module ) {
2397
			$module = self::get_module( $active_module );
2398
			if ( ! isset( $module['changed'] ) ) {
2399
				continue;
2400
			}
2401
2402
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2403
				continue;
2404
			}
2405
2406
			$reactivate_modules[] = $active_module;
2407
			self::deactivate_module( $active_module );
2408
		}
2409
2410
		$new_version = JETPACK__VERSION . ':' . time();
2411
		/** This action is documented in class.jetpack.php */
2412
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2413
		Jetpack_Options::update_options(
2414
			array(
2415
				'version'     => $new_version,
2416
				'old_version' => $jetpack_old_version,
2417
			)
2418
		);
2419
2420
		self::state( 'message', 'modules_activated' );
2421
2422
		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...
2423
2424
		if ( $redirect ) {
2425
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2426
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2427
				$page = $_GET['page'];
2428
			}
2429
2430
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2431
			exit;
2432
		}
2433
	}
2434
2435
	/**
2436
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2437
	 * Make sure to tuck away module "library" files in a sub-directory.
2438
	 *
2439
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2440
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2441
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2442
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2443
	 *
2444
	 * @return array $modules Array of module slugs
2445
	 */
2446
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2447
		static $modules = null;
2448
2449
		if ( ! isset( $modules ) ) {
2450
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2451
			// Use the cache if we're on the front-end and it's available...
2452
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2453
				$modules = $available_modules_option[ JETPACK__VERSION ];
2454
			} else {
2455
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2456
2457
				$modules = array();
2458
2459
				foreach ( $files as $file ) {
2460
					if ( ! $headers = self::get_module( $file ) ) {
2461
						continue;
2462
					}
2463
2464
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2465
				}
2466
2467
				Jetpack_Options::update_option(
2468
					'available_modules',
2469
					array(
2470
						JETPACK__VERSION => $modules,
2471
					)
2472
				);
2473
			}
2474
		}
2475
2476
		/**
2477
		 * Filters the array of modules available to be activated.
2478
		 *
2479
		 * @since 2.4.0
2480
		 *
2481
		 * @param array $modules Array of available modules.
2482
		 * @param string $min_version Minimum version number required to use modules.
2483
		 * @param string $max_version Maximum version number required to use modules.
2484
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2485
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2486
		 */
2487
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version, $requires_connection, $requires_user_connection );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2488
2489
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2490
			return array_keys( $mods );
2491
		}
2492
2493
		$r = array();
2494
		foreach ( $mods as $slug => $introduced ) {
2495
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2496
				continue;
2497
			}
2498
2499
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2500
				continue;
2501
			}
2502
2503
			$mod_details = self::get_module( $slug );
2504
2505
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2506
				continue;
2507
			}
2508
2509
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2510
				continue;
2511
			}
2512
2513
			$r[] = $slug;
2514
		}
2515
2516
		return $r;
2517
	}
2518
2519
	/**
2520
	 * Get default modules loaded on activation.
2521
	 *
2522
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2523
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2524
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2525
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2526
	 *
2527
	 * @return array $modules Array of module slugs
2528
	 */
2529
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2530
		$return = array();
2531
2532
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2533
			$module_data = self::get_module( $module );
2534
2535
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2536
				case 'yes':
2537
					$return[] = $module;
2538
					break;
2539
				case 'public':
2540
					if ( Jetpack_Options::get_option( 'public' ) ) {
2541
						$return[] = $module;
2542
					}
2543
					break;
2544
				case 'no':
2545
				default:
2546
					break;
2547
			}
2548
		}
2549
		/**
2550
		 * Filters the array of default modules.
2551
		 *
2552
		 * @since 2.5.0
2553
		 *
2554
		 * @param array $return Array of default modules.
2555
		 * @param string $min_version Minimum version number required to use modules.
2556
		 * @param string $max_version Maximum version number required to use modules.
2557
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2558
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2559
		 */
2560
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version, $requires_connection, $requires_user_connection );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2561
	}
2562
2563
	/**
2564
	 * Checks activated modules during auto-activation to determine
2565
	 * if any of those modules are being deprecated.  If so, close
2566
	 * them out, and add any replacement modules.
2567
	 *
2568
	 * Runs at priority 99 by default.
2569
	 *
2570
	 * This is run late, so that it can still activate a module if
2571
	 * the new module is a replacement for another that the user
2572
	 * currently has active, even if something at the normal priority
2573
	 * would kibosh everything.
2574
	 *
2575
	 * @since 2.6
2576
	 * @uses jetpack_get_default_modules filter
2577
	 * @param array $modules
2578
	 * @return array
2579
	 */
2580
	function handle_deprecated_modules( $modules ) {
2581
		$deprecated_modules = array(
2582
			'debug'            => null,  // Closed out and moved to the debugger library.
2583
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2584
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2585
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2586
		);
2587
2588
		// Don't activate SSO if they never completed activating WPCC.
2589
		if ( self::is_module_active( 'wpcc' ) ) {
2590
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2591
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2592
				$deprecated_modules['wpcc'] = null;
2593
			}
2594
		}
2595
2596
		foreach ( $deprecated_modules as $module => $replacement ) {
2597
			if ( self::is_module_active( $module ) ) {
2598
				self::deactivate_module( $module );
2599
				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...
2600
					$modules[] = $replacement;
2601
				}
2602
			}
2603
		}
2604
2605
		return array_unique( $modules );
2606
	}
2607
2608
	/**
2609
	 * Checks activated plugins during auto-activation to determine
2610
	 * if any of those plugins are in the list with a corresponding module
2611
	 * that is not compatible with the plugin. The module will not be allowed
2612
	 * to auto-activate.
2613
	 *
2614
	 * @since 2.6
2615
	 * @uses jetpack_get_default_modules filter
2616
	 * @param array $modules
2617
	 * @return array
2618
	 */
2619
	function filter_default_modules( $modules ) {
2620
2621
		$active_plugins = self::get_active_plugins();
2622
2623
		if ( ! empty( $active_plugins ) ) {
2624
2625
			// For each module we'd like to auto-activate...
2626
			foreach ( $modules as $key => $module ) {
2627
				// If there are potential conflicts for it...
2628
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2629
					// For each potential conflict...
2630
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2631
						// If that conflicting plugin is active...
2632
						if ( in_array( $plugin, $active_plugins ) ) {
2633
							// Remove that item from being auto-activated.
2634
							unset( $modules[ $key ] );
2635
						}
2636
					}
2637
				}
2638
			}
2639
		}
2640
2641
		return $modules;
2642
	}
2643
2644
	/**
2645
	 * Extract a module's slug from its full path.
2646
	 */
2647
	public static function get_module_slug( $file ) {
2648
		return str_replace( '.php', '', basename( $file ) );
2649
	}
2650
2651
	/**
2652
	 * Generate a module's path from its slug.
2653
	 */
2654
	public static function get_module_path( $slug ) {
2655
		/**
2656
		 * Filters the path of a modules.
2657
		 *
2658
		 * @since 7.4.0
2659
		 *
2660
		 * @param array $return The absolute path to a module's root php file
2661
		 * @param string $slug The module slug
2662
		 */
2663
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $slug.

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

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

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

Loading history...
2664
	}
2665
2666
	/**
2667
	 * Load module data from module file. Headers differ from WordPress
2668
	 * plugin headers to avoid them being identified as standalone
2669
	 * plugins on the WordPress plugins page.
2670
	 */
2671
	public static function get_module( $module ) {
2672
		$headers = array(
2673
			'name'                      => 'Module Name',
2674
			'description'               => 'Module Description',
2675
			'sort'                      => 'Sort Order',
2676
			'recommendation_order'      => 'Recommendation Order',
2677
			'introduced'                => 'First Introduced',
2678
			'changed'                   => 'Major Changes In',
2679
			'deactivate'                => 'Deactivate',
2680
			'free'                      => 'Free',
2681
			'requires_connection'       => 'Requires Connection',
2682
			'requires_user_connection'  => 'Requires User Connection',
2683
			'auto_activate'             => 'Auto Activate',
2684
			'module_tags'               => 'Module Tags',
2685
			'feature'                   => 'Feature',
2686
			'additional_search_queries' => 'Additional Search Queries',
2687
			'plan_classes'              => 'Plans',
2688
		);
2689
2690
		static $modules_details;
2691
		$file = self::get_module_path( self::get_module_slug( $module ) );
2692
2693
		if ( isset( $modules_details[ $module ] ) ) {
2694
			$mod = $modules_details[ $module ];
2695
		} else {
2696
2697
			$mod = self::get_file_data( $file, $headers );
2698
			if ( empty( $mod['name'] ) ) {
2699
				return false;
2700
			}
2701
2702
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2703
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2704
			$mod['deactivate']               = empty( $mod['deactivate'] );
2705
			$mod['free']                     = empty( $mod['free'] );
2706
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2707
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2708
2709
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2710
				$mod['auto_activate'] = 'No';
2711
			} else {
2712
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2713
			}
2714
2715
			if ( $mod['module_tags'] ) {
2716
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2717
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2718
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2719
			} else {
2720
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2721
			}
2722
2723 View Code Duplication
			if ( $mod['plan_classes'] ) {
2724
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2725
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2726
			} else {
2727
				$mod['plan_classes'] = array( 'free' );
2728
			}
2729
2730 View Code Duplication
			if ( $mod['feature'] ) {
2731
				$mod['feature'] = explode( ',', $mod['feature'] );
2732
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2733
			} else {
2734
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2735
			}
2736
2737
			$modules_details[ $module ] = $mod;
2738
2739
		}
2740
2741
		/**
2742
		 * Filters the feature array on a module.
2743
		 *
2744
		 * This filter allows you to control where each module is filtered: Recommended,
2745
		 * and the default "Other" listing.
2746
		 *
2747
		 * @since 3.5.0
2748
		 *
2749
		 * @param array   $mod['feature'] The areas to feature this module:
2750
		 *     'Recommended' shows on the main Jetpack admin screen.
2751
		 *     'Other' should be the default if no other value is in the array.
2752
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2753
		 * @param array   $mod All the currently assembled module data.
2754
		 */
2755
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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

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

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

Loading history...
2756
2757
		/**
2758
		 * Filter the returned data about a module.
2759
		 *
2760
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2761
		 * so please be careful.
2762
		 *
2763
		 * @since 3.6.0
2764
		 *
2765
		 * @param array   $mod    The details of the requested module.
2766
		 * @param string  $module The slug of the module, e.g. sharedaddy
2767
		 * @param string  $file   The path to the module source file.
2768
		 */
2769
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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

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

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

Loading history...
2770
	}
2771
2772
	/**
2773
	 * Like core's get_file_data implementation, but caches the result.
2774
	 */
2775
	public static function get_file_data( $file, $headers ) {
2776
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2777
		$file_name = basename( $file );
2778
2779
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2780
2781
		$file_data_option = get_transient( $cache_key );
2782
2783
		if ( ! is_array( $file_data_option ) ) {
2784
			delete_transient( $cache_key );
2785
			$file_data_option = false;
2786
		}
2787
2788
		if ( false === $file_data_option ) {
2789
			$file_data_option = array();
2790
		}
2791
2792
		$key           = md5( $file_name . serialize( $headers ) );
2793
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2794
2795
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2796
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2797
			return $file_data_option[ $key ];
2798
		}
2799
2800
		$data = get_file_data( $file, $headers );
2801
2802
		$file_data_option[ $key ] = $data;
2803
2804
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2805
2806
		return $data;
2807
	}
2808
2809
	/**
2810
	 * Return translated module tag.
2811
	 *
2812
	 * @param string $tag Tag as it appears in each module heading.
2813
	 *
2814
	 * @return mixed
2815
	 */
2816
	public static function translate_module_tag( $tag ) {
2817
		return jetpack_get_module_i18n_tag( $tag );
2818
	}
2819
2820
	/**
2821
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2822
	 *
2823
	 * @since 3.9.2
2824
	 *
2825
	 * @param array $modules
2826
	 *
2827
	 * @return string|void
2828
	 */
2829
	public static function get_translated_modules( $modules ) {
2830
		foreach ( $modules as $index => $module ) {
2831
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2832
			if ( isset( $module['name'] ) ) {
2833
				$modules[ $index ]['name'] = $i18n_module['name'];
2834
			}
2835
			if ( isset( $module['description'] ) ) {
2836
				$modules[ $index ]['description']       = $i18n_module['description'];
2837
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2838
			}
2839
		}
2840
		return $modules;
2841
	}
2842
2843
	/**
2844
	 * Get a list of activated modules as an array of module slugs.
2845
	 */
2846
	public static function get_active_modules() {
2847
		$active = Jetpack_Options::get_option( 'active_modules' );
2848
2849
		if ( ! is_array( $active ) ) {
2850
			$active = array();
2851
		}
2852
2853
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2854
			$active[] = 'vaultpress';
2855
		} else {
2856
			$active = array_diff( $active, array( 'vaultpress' ) );
2857
		}
2858
2859
		// If protect is active on the main site of a multisite, it should be active on all sites.
2860
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2861
			$active[] = 'protect';
2862
		}
2863
2864
		/**
2865
		 * Allow filtering of the active modules.
2866
		 *
2867
		 * Gives theme and plugin developers the power to alter the modules that
2868
		 * are activated on the fly.
2869
		 *
2870
		 * @since 5.8.0
2871
		 *
2872
		 * @param array $active Array of active module slugs.
2873
		 */
2874
		$active = apply_filters( 'jetpack_active_modules', $active );
2875
2876
		return array_unique( $active );
2877
	}
2878
2879
	/**
2880
	 * Check whether or not a Jetpack module is active.
2881
	 *
2882
	 * @param string $module The slug of a Jetpack module.
2883
	 * @return bool
2884
	 *
2885
	 * @static
2886
	 */
2887
	public static function is_module_active( $module ) {
2888
		return in_array( $module, self::get_active_modules() );
2889
	}
2890
2891
	public static function is_module( $module ) {
2892
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2893
	}
2894
2895
	/**
2896
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2897
	 *
2898
	 * @param bool $catch True to start catching, False to stop.
2899
	 *
2900
	 * @static
2901
	 */
2902
	public static function catch_errors( $catch ) {
2903
		static $display_errors, $error_reporting;
2904
2905
		if ( $catch ) {
2906
			$display_errors  = @ini_set( 'display_errors', 1 );
2907
			$error_reporting = @error_reporting( E_ALL );
2908
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2909
		} else {
2910
			@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...
2911
			@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...
2912
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2913
		}
2914
	}
2915
2916
	/**
2917
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2918
	 */
2919
	public static function catch_errors_on_shutdown() {
2920
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2921
	}
2922
2923
	/**
2924
	 * Rewrite any string to make paths easier to read.
2925
	 *
2926
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2927
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2928
	 *
2929
	 * @param $string
2930
	 * @return mixed
2931
	 */
2932
	public static function alias_directories( $string ) {
2933
		// ABSPATH has a trailing slash.
2934
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2935
		// WP_CONTENT_DIR does not have a trailing slash.
2936
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2937
2938
		return $string;
2939
	}
2940
2941
	public static function activate_default_modules(
2942
		$min_version = false,
2943
		$max_version = false,
2944
		$other_modules = array(),
2945
		$redirect = null,
2946
		$send_state_messages = null,
2947
		$requires_connection = null,
2948
		$requires_user_connection = null
2949
	) {
2950
		$jetpack = self::init();
2951
2952
		if ( is_null( $redirect ) ) {
2953
			if (
2954
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2955
			||
2956
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2957
			||
2958
				( defined( 'WP_CLI' ) && WP_CLI )
2959
			||
2960
				( defined( 'DOING_CRON' ) && DOING_CRON )
2961
			||
2962
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2963
			) {
2964
				$redirect = false;
2965
			} elseif ( is_admin() ) {
2966
				$redirect = true;
2967
			} else {
2968
				$redirect = false;
2969
			}
2970
		}
2971
2972
		if ( is_null( $send_state_messages ) ) {
2973
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2974
		}
2975
2976
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2977
		$modules = array_merge( $other_modules, $modules );
2978
2979
		// Look for standalone plugins and disable if active.
2980
2981
		$to_deactivate = array();
2982
		foreach ( $modules as $module ) {
2983
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2984
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2985
			}
2986
		}
2987
2988
		$deactivated = array();
2989
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2990
			list( $probable_file, $probable_title ) = $deactivate_me;
2991
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2992
				$deactivated[] = $module;
2993
			}
2994
		}
2995
2996
		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...
2997
			if ( $send_state_messages ) {
2998
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2999
			}
3000
3001
			if ( $redirect ) {
3002
				$url = add_query_arg(
3003
					array(
3004
						'action'   => 'activate_default_modules',
3005
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3006
					),
3007
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3008
				);
3009
				wp_safe_redirect( $url );
3010
				exit;
3011
			}
3012
		}
3013
3014
		/**
3015
		 * Fires before default modules are activated.
3016
		 *
3017
		 * @since 1.9.0
3018
		 *
3019
		 * @param string    $min_version Minimum version number required to use modules.
3020
		 * @param string    $max_version Maximum version number required to use modules.
3021
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3022
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3023
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3024
		 */
3025
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3026
3027
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3028
		if ( $send_state_messages ) {
3029
			self::restate();
3030
			self::catch_errors( true );
3031
		}
3032
3033
		$active = self::get_active_modules();
3034
3035
		foreach ( $modules as $module ) {
3036
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3037
				$active[] = $module;
3038
				self::update_active_modules( $active );
3039
				continue;
3040
			}
3041
3042
			if ( $send_state_messages && in_array( $module, $active ) ) {
3043
				$module_info = self::get_module( $module );
3044 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3045
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3046
					if ( $active_state = self::state( $state ) ) {
3047
						$active_state = explode( ',', $active_state );
3048
					} else {
3049
						$active_state = array();
3050
					}
3051
					$active_state[] = $module;
3052
					self::state( $state, implode( ',', $active_state ) );
3053
				}
3054
				continue;
3055
			}
3056
3057
			$file = self::get_module_path( $module );
3058
			if ( ! file_exists( $file ) ) {
3059
				continue;
3060
			}
3061
3062
			// we'll override this later if the plugin can be included without fatal error
3063
			if ( $redirect ) {
3064
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3065
			}
3066
3067
			if ( $send_state_messages ) {
3068
				self::state( 'error', 'module_activation_failed' );
3069
				self::state( 'module', $module );
3070
			}
3071
3072
			ob_start();
3073
			require_once $file;
3074
3075
			$active[] = $module;
3076
3077 View Code Duplication
			if ( $send_state_messages ) {
3078
3079
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3080
				if ( $active_state = self::state( $state ) ) {
3081
					$active_state = explode( ',', $active_state );
3082
				} else {
3083
					$active_state = array();
3084
				}
3085
				$active_state[] = $module;
3086
				self::state( $state, implode( ',', $active_state ) );
3087
			}
3088
3089
			self::update_active_modules( $active );
3090
3091
			ob_end_clean();
3092
		}
3093
3094
		if ( $send_state_messages ) {
3095
			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...
3096
			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...
3097
		}
3098
3099
		self::catch_errors( false );
3100
		/**
3101
		 * Fires when default modules are activated.
3102
		 *
3103
		 * @since 1.9.0
3104
		 *
3105
		 * @param string    $min_version Minimum version number required to use modules.
3106
		 * @param string    $max_version Maximum version number required to use modules.
3107
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3108
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3109
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3110
		 */
3111
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3112
	}
3113
3114
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3115
		/**
3116
		 * Fires before a module is activated.
3117
		 *
3118
		 * @since 2.6.0
3119
		 *
3120
		 * @param string $module Module slug.
3121
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3122
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3123
		 */
3124
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3125
3126
		$jetpack = self::init();
3127
3128
		if ( ! strlen( $module ) ) {
3129
			return false;
3130
		}
3131
3132
		if ( ! self::is_module( $module ) ) {
3133
			return false;
3134
		}
3135
3136
		// If it's already active, then don't do it again
3137
		$active = self::get_active_modules();
3138
		foreach ( $active as $act ) {
3139
			if ( $act == $module ) {
3140
				return true;
3141
			}
3142
		}
3143
3144
		$module_data = self::get_module( $module );
3145
3146
		$is_offline_mode = ( new Status() )->is_offline_mode();
3147
		if ( ! self::is_connection_ready() ) {
3148
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3149
				return false;
3150
			}
3151
3152
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3153
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3154
				return false;
3155
			}
3156
		}
3157
3158
		// Check and see if the old plugin is active
3159
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3160
			// Deactivate the old plugin
3161
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3162
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3163
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3164
				self::state( 'deactivated_plugins', $module );
3165
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3166
				exit;
3167
			}
3168
		}
3169
3170
		// Protect won't work with mis-configured IPs
3171
		if ( 'protect' === $module ) {
3172
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3173
			if ( ! jetpack_protect_get_ip() ) {
3174
				self::state( 'message', 'protect_misconfigured_ip' );
3175
				return false;
3176
			}
3177
		}
3178
3179
		if ( ! Jetpack_Plan::supports( $module ) ) {
3180
			return false;
3181
		}
3182
3183
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3184
		self::state( 'module', $module );
3185
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3186
3187
		self::catch_errors( true );
3188
		ob_start();
3189
		require self::get_module_path( $module );
3190
		/** This action is documented in class.jetpack.php */
3191
		do_action( 'jetpack_activate_module', $module );
3192
		$active[] = $module;
3193
		self::update_active_modules( $active );
3194
3195
		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...
3196
		ob_end_clean();
3197
		self::catch_errors( false );
3198
3199
		if ( $redirect ) {
3200
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3201
		}
3202
		if ( $exit ) {
3203
			exit;
3204
		}
3205
		return true;
3206
	}
3207
3208
	function activate_module_actions( $module ) {
3209
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3210
	}
3211
3212
	public static function deactivate_module( $module ) {
3213
		/**
3214
		 * Fires when a module is deactivated.
3215
		 *
3216
		 * @since 1.9.0
3217
		 *
3218
		 * @param string $module Module slug.
3219
		 */
3220
		do_action( 'jetpack_pre_deactivate_module', $module );
3221
3222
		$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...
3223
3224
		$active = self::get_active_modules();
3225
		$new    = array_filter( array_diff( $active, (array) $module ) );
3226
3227
		return self::update_active_modules( $new );
3228
	}
3229
3230
	public static function enable_module_configurable( $module ) {
3231
		$module = self::get_module_slug( $module );
3232
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3233
	}
3234
3235
	/**
3236
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3237
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3238
	 *
3239
	 * @param string $module Module slug
3240
	 * @return string $url module configuration URL
3241
	 */
3242
	public static function module_configuration_url( $module ) {
3243
		$module      = self::get_module_slug( $module );
3244
		$default_url = self::admin_url() . "#/settings?term=$module";
3245
		/**
3246
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3247
		 *
3248
		 * @since 6.9.0
3249
		 *
3250
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3251
		 */
3252
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3253
3254
		return $url;
3255
	}
3256
3257
	/* Installation */
3258
	public static function bail_on_activation( $message, $deactivate = true ) {
3259
		?>
3260
<!doctype html>
3261
<html>
3262
<head>
3263
<meta charset="<?php bloginfo( 'charset' ); ?>">
3264
<style>
3265
* {
3266
	text-align: center;
3267
	margin: 0;
3268
	padding: 0;
3269
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3270
}
3271
p {
3272
	margin-top: 1em;
3273
	font-size: 18px;
3274
}
3275
</style>
3276
<body>
3277
<p><?php echo esc_html( $message ); ?></p>
3278
</body>
3279
</html>
3280
		<?php
3281
		if ( $deactivate ) {
3282
			$plugins = get_option( 'active_plugins' );
3283
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3284
			$update  = false;
3285
			foreach ( $plugins as $i => $plugin ) {
3286
				if ( $plugin === $jetpack ) {
3287
					$plugins[ $i ] = false;
3288
					$update        = true;
3289
				}
3290
			}
3291
3292
			if ( $update ) {
3293
				update_option( 'active_plugins', array_filter( $plugins ) );
3294
			}
3295
		}
3296
		exit;
3297
	}
3298
3299
	/**
3300
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3301
	 *
3302
	 * @static
3303
	 */
3304
	public static function plugin_activation( $network_wide ) {
3305
		Jetpack_Options::update_option( 'activated', 1 );
3306
3307
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3308
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3309
		}
3310
3311
		if ( $network_wide ) {
3312
			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...
3313
		}
3314
3315
		// For firing one-off events (notices) immediately after activation
3316
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3317
3318
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3319
3320
		Health::on_jetpack_activated();
3321
3322
		self::plugin_initialize();
3323
	}
3324
3325
	public static function get_activation_source( $referer_url ) {
3326
3327
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3328
			return array( 'wp-cli', null );
3329
		}
3330
3331
		$referer = wp_parse_url( $referer_url );
3332
3333
		$source_type  = 'unknown';
3334
		$source_query = null;
3335
3336
		if ( ! is_array( $referer ) ) {
3337
			return array( $source_type, $source_query );
3338
		}
3339
3340
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3341
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3342
3343
		if ( isset( $referer['query'] ) ) {
3344
			parse_str( $referer['query'], $query_parts );
3345
		} else {
3346
			$query_parts = array();
3347
		}
3348
3349
		if ( $plugins_path === $referer['path'] ) {
3350
			$source_type = 'list';
3351
		} elseif ( $plugins_install_path === $referer['path'] ) {
3352
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3353
			switch ( $tab ) {
3354
				case 'popular':
3355
					$source_type = 'popular';
3356
					break;
3357
				case 'recommended':
3358
					$source_type = 'recommended';
3359
					break;
3360
				case 'favorites':
3361
					$source_type = 'favorites';
3362
					break;
3363
				case 'search':
3364
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3365
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3366
					break;
3367
				default:
3368
					$source_type = 'featured';
3369
			}
3370
		}
3371
3372
		return array( $source_type, $source_query );
3373
	}
3374
3375
	/**
3376
	 * Runs before bumping version numbers up to a new version
3377
	 *
3378
	 * @param string $version    Version:timestamp.
3379
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3380
	 */
3381
	public static function do_version_bump( $version, $old_version ) {
3382
		if ( $old_version ) { // For existing Jetpack installations.
3383
3384
			// If a front end page is visited after the update, the 'wp' action will fire.
3385
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3386
3387
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3388
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3389
		}
3390
	}
3391
3392
	/**
3393
	 * Sets the display_update_modal state.
3394
	 */
3395
	public static function set_update_modal_display() {
3396
		self::state( 'display_update_modal', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3397
	}
3398
3399
	/**
3400
	 * Sets the internal version number and activation state.
3401
	 *
3402
	 * @static
3403
	 */
3404
	public static function plugin_initialize() {
3405
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3406
			Jetpack_Options::update_option( 'activated', 2 );
3407
		}
3408
3409 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3410
			$version = $old_version = JETPACK__VERSION . ':' . time();
3411
			/** This action is documented in class.jetpack.php */
3412
			do_action( 'updating_jetpack_version', $version, false );
3413
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3414
		}
3415
3416
		self::load_modules();
3417
3418
		Jetpack_Options::delete_option( 'do_activate' );
3419
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3420
	}
3421
3422
	/**
3423
	 * Removes all connection options
3424
	 *
3425
	 * @static
3426
	 */
3427
	public static function plugin_deactivation() {
3428
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3429
		$tracking = new Tracking();
3430
		$tracking->record_user_event( 'deactivate_plugin', array() );
3431
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3432
			Jetpack_Network::init()->deactivate();
3433
		} else {
3434
			self::disconnect( false );
3435
			// Jetpack_Heartbeat::init()->deactivate();
3436
		}
3437
	}
3438
3439
	/**
3440
	 * Disconnects from the Jetpack servers.
3441
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3442
	 *
3443
	 * @static
3444
	 */
3445
	public static function disconnect( $update_activated_state = true ) {
3446
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3447
3448
		$connection = self::connection();
3449
3450
		( new Nonce_Handler() )->clean_all();
3451
3452
		// If the site is in an IDC because sync is not allowed,
3453
		// let's make sure to not disconnect the production site.
3454
		if ( ! self::validate_sync_error_idc_option() ) {
3455
			$tracking = new Tracking();
3456
			$tracking->record_user_event( 'disconnect_site', array() );
3457
3458
			$connection->disconnect_site_wpcom( true );
3459
		}
3460
3461
		$connection->delete_all_connection_tokens( true );
3462
		Jetpack_IDC::clear_all_idc_options();
3463
3464
		if ( $update_activated_state ) {
3465
			Jetpack_Options::update_option( 'activated', 4 );
3466
		}
3467
3468
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3469
			// Check then record unique disconnection if site has never been disconnected previously
3470
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3471
				$jetpack_unique_connection['disconnected'] = 1;
3472
			} else {
3473
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3474
					// track unique disconnect
3475
					$jetpack = self::init();
3476
3477
					$jetpack->stat( 'connections', 'unique-disconnect' );
3478
					$jetpack->do_stats( 'server_side' );
3479
				}
3480
				// increment number of times disconnected
3481
				$jetpack_unique_connection['disconnected'] += 1;
3482
			}
3483
3484
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3485
		}
3486
3487
		// Delete all the sync related data. Since it could be taking up space.
3488
		Sender::get_instance()->uninstall();
3489
3490
	}
3491
3492
	/**
3493
	 * Disconnects the user
3494
	 *
3495
	 * @param int $user_id The user ID to disconnect.
3496
	 */
3497
	public function disconnect_user( $user_id ) {
3498
		$this->connection_manager->disconnect_user( $user_id );
3499
	}
3500
3501
	/**
3502
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3503
	 */
3504
	public static function try_registration() {
3505
		$terms_of_service = new Terms_Of_Service();
3506
		// The user has agreed to the TOS at some point by now.
3507
		$terms_of_service->agree();
3508
3509
		// Let's get some testing in beta versions and such.
3510
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3511
			// Before attempting to connect, let's make sure that the domains are viable.
3512
			$domains_to_check = array_unique(
3513
				array(
3514
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3515
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3516
				)
3517
			);
3518
			foreach ( $domains_to_check as $domain ) {
3519
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3518 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

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

Consider the follow example

<?php

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

    return false;
}

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

Loading history...
3520
				if ( is_wp_error( $result ) ) {
3521
					return $result;
3522
				}
3523
			}
3524
		}
3525
3526
		$result = self::register();
3527
3528
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3529
		if ( ! $result || is_wp_error( $result ) ) {
3530
			return $result;
3531
		} else {
3532
			return true;
3533
		}
3534
	}
3535
3536
	/**
3537
	 * Tracking an internal event log. Try not to put too much chaff in here.
3538
	 *
3539
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3540
	 */
3541
	public static function log( $code, $data = null ) {
3542
		// only grab the latest 200 entries
3543
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3544
3545
		// Append our event to the log
3546
		$log_entry = array(
3547
			'time'    => time(),
3548
			'user_id' => get_current_user_id(),
3549
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3550
			'code'    => $code,
3551
		);
3552
		// Don't bother storing it unless we've got some.
3553
		if ( ! is_null( $data ) ) {
3554
			$log_entry['data'] = $data;
3555
		}
3556
		$log[] = $log_entry;
3557
3558
		// Try add_option first, to make sure it's not autoloaded.
3559
		// @todo: Add an add_option method to Jetpack_Options
3560
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3561
			Jetpack_Options::update_option( 'log', $log );
3562
		}
3563
3564
		/**
3565
		 * Fires when Jetpack logs an internal event.
3566
		 *
3567
		 * @since 3.0.0
3568
		 *
3569
		 * @param array $log_entry {
3570
		 *  Array of details about the log entry.
3571
		 *
3572
		 *  @param string time Time of the event.
3573
		 *  @param int user_id ID of the user who trigerred the event.
3574
		 *  @param int blog_id Jetpack Blog ID.
3575
		 *  @param string code Unique name for the event.
3576
		 *  @param string data Data about the event.
3577
		 * }
3578
		 */
3579
		do_action( 'jetpack_log_entry', $log_entry );
3580
	}
3581
3582
	/**
3583
	 * Get the internal event log.
3584
	 *
3585
	 * @param $event (string) - only return the specific log events
3586
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3587
	 *
3588
	 * @return array of log events || WP_Error for invalid params
3589
	 */
3590
	public static function get_log( $event = false, $num = false ) {
3591
		if ( $event && ! is_string( $event ) ) {
3592
			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...
3593
		}
3594
3595
		if ( $num && ! is_numeric( $num ) ) {
3596
			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...
3597
		}
3598
3599
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3600
3601
		// If nothing set - act as it did before, otherwise let's start customizing the output
3602
		if ( ! $num && ! $event ) {
3603
			return $entire_log;
3604
		} else {
3605
			$entire_log = array_reverse( $entire_log );
3606
		}
3607
3608
		$custom_log_output = array();
3609
3610
		if ( $event ) {
3611
			foreach ( $entire_log as $log_event ) {
3612
				if ( $event == $log_event['code'] ) {
3613
					$custom_log_output[] = $log_event;
3614
				}
3615
			}
3616
		} else {
3617
			$custom_log_output = $entire_log;
3618
		}
3619
3620
		if ( $num ) {
3621
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3622
		}
3623
3624
		return $custom_log_output;
3625
	}
3626
3627
	/**
3628
	 * Log modification of important settings.
3629
	 */
3630
	public static function log_settings_change( $option, $old_value, $value ) {
3631
		switch ( $option ) {
3632
			case 'jetpack_sync_non_public_post_stati':
3633
				self::log( $option, $value );
3634
				break;
3635
		}
3636
	}
3637
3638
	/**
3639
	 * Return stat data for WPCOM sync
3640
	 */
3641
	public static function get_stat_data( $encode = true, $extended = true ) {
3642
		$data = Jetpack_Heartbeat::generate_stats_array();
3643
3644
		if ( $extended ) {
3645
			$additional_data = self::get_additional_stat_data();
3646
			$data            = array_merge( $data, $additional_data );
3647
		}
3648
3649
		if ( $encode ) {
3650
			return json_encode( $data );
3651
		}
3652
3653
		return $data;
3654
	}
3655
3656
	/**
3657
	 * Get additional stat data to sync to WPCOM
3658
	 */
3659
	public static function get_additional_stat_data( $prefix = '' ) {
3660
		$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...
3661
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3662
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3663
		$return[ "{$prefix}site-count" ]    = 0;
3664
3665
		if ( function_exists( 'get_blog_count' ) ) {
3666
			$return[ "{$prefix}site-count" ] = get_blog_count();
3667
		}
3668
		return $return;
3669
	}
3670
3671
	private static function get_site_user_count() {
3672
		global $wpdb;
3673
3674
		if ( function_exists( 'wp_is_large_network' ) ) {
3675
			if ( wp_is_large_network( 'users' ) ) {
3676
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3677
			}
3678
		}
3679
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3680
			// It wasn't there, so regenerate the data and save the transient
3681
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3682
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3683
		}
3684
		return $user_count;
3685
	}
3686
3687
	/* Admin Pages */
3688
3689
	function admin_init() {
3690
		// If the plugin is not connected, display a connect message.
3691
		if (
3692
			// the plugin was auto-activated and needs its candy
3693
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3694
		||
3695
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3696
			! Jetpack_Options::get_option( 'activated' )
3697
		) {
3698
			self::plugin_initialize();
3699
		}
3700
3701
		$is_offline_mode = ( new Status() )->is_offline_mode();
3702
		if ( ! self::is_connection_ready() && ! $is_offline_mode ) {
3703
			Jetpack_Connection_Banner::init();
3704
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3705
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3706
			// Upgrade: 1.1 -> 1.1.1
3707
			// Check and see if host can verify the Jetpack servers' SSL certificate
3708
			$args = array();
3709
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3710
		}
3711
3712
		Jetpack_Recommendations_Banner::init();
3713
3714
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3715
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3716
		}
3717
3718
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3719
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3720
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3721
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3722
3723
		if ( self::is_connection_ready() || $is_offline_mode ) {
3724
			// Artificially throw errors in certain specific cases during plugin activation.
3725
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3726
		}
3727
3728
		// Add custom column in wp-admin/users.php to show whether user is linked.
3729
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3730
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3731
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3732
	}
3733
3734
	function admin_body_class( $admin_body_class = '' ) {
3735
		$classes = explode( ' ', trim( $admin_body_class ) );
3736
3737
		$classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3738
3739
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3740
		return " $admin_body_class ";
3741
	}
3742
3743
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3744
		return $admin_body_class . ' jetpack-pagestyles ';
3745
	}
3746
3747
	/**
3748
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3749
	 * This function artificially throws errors for such cases (per a specific list).
3750
	 *
3751
	 * @param string $plugin The activated plugin.
3752
	 */
3753
	function throw_error_on_activate_plugin( $plugin ) {
3754
		$active_modules = self::get_active_modules();
3755
3756
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3757
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3758
			$throw = false;
3759
3760
			// Try and make sure it really was the stats plugin
3761
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3762
				if ( 'stats.php' == basename( $plugin ) ) {
3763
					$throw = true;
3764
				}
3765
			} else {
3766
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3767
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3768
					$throw = true;
3769
				}
3770
			}
3771
3772
			if ( $throw ) {
3773
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3774
			}
3775
		}
3776
	}
3777
3778
	function intercept_plugin_error_scrape_init() {
3779
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3780
	}
3781
3782
	function intercept_plugin_error_scrape( $action, $result ) {
3783
		if ( ! $result ) {
3784
			return;
3785
		}
3786
3787
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3788
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3789
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3790
			}
3791
		}
3792
	}
3793
3794
	/**
3795
	 * Register the remote file upload request handlers, if needed.
3796
	 *
3797
	 * @access public
3798
	 */
3799
	public function add_remote_request_handlers() {
3800
		// Remote file uploads are allowed only via AJAX requests.
3801
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3802
			return;
3803
		}
3804
3805
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3806
		$remote_request_actions = array(
3807
			'jetpack_upload_file',
3808
			'jetpack_update_file',
3809
		);
3810
3811
		// phpcs:ignore WordPress.Security.NonceVerification
3812
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3813
			return;
3814
		}
3815
3816
		// Require Jetpack authentication for the remote file upload AJAX requests.
3817
		if ( ! $this->connection_manager ) {
3818
			$this->connection_manager = new Connection_Manager();
3819
		}
3820
3821
		$this->connection_manager->require_jetpack_authentication();
3822
3823
		// Register the remote file upload AJAX handlers.
3824
		foreach ( $remote_request_actions as $action ) {
3825
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3826
		}
3827
	}
3828
3829
	/**
3830
	 * Handler for Jetpack remote file uploads.
3831
	 *
3832
	 * @access public
3833
	 */
3834
	public function remote_request_handlers() {
3835
		$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...
3836
3837
		switch ( current_filter() ) {
3838
			case 'wp_ajax_nopriv_jetpack_upload_file':
3839
				$response = $this->upload_handler();
3840
				break;
3841
3842
			case 'wp_ajax_nopriv_jetpack_update_file':
3843
				$response = $this->upload_handler( true );
3844
				break;
3845
			default:
3846
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_handler'.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
3858
3859
			if ( ! is_int( $status_code ) ) {
3860
				$status_code = 400;
3861
			}
3862
3863
			status_header( $status_code );
3864
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3865
		}
3866
3867
		status_header( 200 );
3868
		if ( true === $response ) {
3869
			exit;
3870
		}
3871
3872
		die( json_encode( (object) $response ) );
3873
	}
3874
3875
	/**
3876
	 * Uploads a file gotten from the global $_FILES.
3877
	 * If `$update_media_item` is true and `post_id` is defined
3878
	 * the attachment file of the media item (gotten through of the post_id)
3879
	 * will be updated instead of add a new one.
3880
	 *
3881
	 * @param  boolean $update_media_item - update media attachment
3882
	 * @return array - An array describing the uploadind files process
3883
	 */
3884
	function upload_handler( $update_media_item = false ) {
3885
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3886
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 405.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
3907
			}
3908
		}
3909
3910
		$media_keys = array_keys( $_FILES['media'] );
3911
3912
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3913
		if ( ! $token || is_wp_error( $token ) ) {
3914
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
3915
		}
3916
3917
		$uploaded_files = array();
3918
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3919
		unset( $GLOBALS['post'] );
3920
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3921
			$file = array();
3922
			foreach ( $media_keys as $media_key ) {
3923
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3924
			}
3925
3926
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3927
3928
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3929
			if ( $hmac_provided !== $hmac_file ) {
3930
				$uploaded_files[ $index ] = (object) array(
3931
					'error'             => 'invalid_hmac',
3932
					'error_description' => 'The corresponding HMAC for this file does not match',
3933
				);
3934
				continue;
3935
			}
3936
3937
			$_FILES['.jetpack.upload.'] = $file;
3938
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3939
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3940
				$post_id = 0;
3941
			}
3942
3943
			if ( $update_media_item ) {
3944
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3945
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_input'.

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

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

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

Loading history...
3946
				}
3947
3948
				$media_array = $_FILES['media'];
3949
3950
				$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...
3951
				$file_array['type']     = $media_array['type'][0];
3952
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3953
				$file_array['error']    = $media_array['error'][0];
3954
				$file_array['size']     = $media_array['size'][0];
3955
3956
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3957
3958
				if ( is_wp_error( $edited_media_item ) ) {
3959
					return $edited_media_item;
3960
				}
3961
3962
				$response = (object) array(
3963
					'id'   => (string) $post_id,
3964
					'file' => (string) $edited_media_item->post_title,
3965
					'url'  => (string) wp_get_attachment_url( $post_id ),
3966
					'type' => (string) $edited_media_item->post_mime_type,
3967
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3968
				);
3969
3970
				return (array) array( $response );
3971
			}
3972
3973
			$attachment_id = media_handle_upload(
3974
				'.jetpack.upload.',
3975
				$post_id,
3976
				array(),
3977
				array(
3978
					'action' => 'jetpack_upload_file',
3979
				)
3980
			);
3981
3982
			if ( ! $attachment_id ) {
3983
				$uploaded_files[ $index ] = (object) array(
3984
					'error'             => 'unknown',
3985
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3986
				);
3987
			} elseif ( is_wp_error( $attachment_id ) ) {
3988
				$uploaded_files[ $index ] = (object) array(
3989
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3990
					'error_description' => $attachment_id->get_error_message(),
3991
				);
3992
			} else {
3993
				$attachment               = get_post( $attachment_id );
3994
				$uploaded_files[ $index ] = (object) array(
3995
					'id'   => (string) $attachment_id,
3996
					'file' => $attachment->post_title,
3997
					'url'  => wp_get_attachment_url( $attachment_id ),
3998
					'type' => $attachment->post_mime_type,
3999
					'meta' => wp_get_attachment_metadata( $attachment_id ),
4000
				);
4001
				// Zip files uploads are not supported unless they are done for installation purposed
4002
				// lets delete them in case something goes wrong in this whole process
4003
				if ( 'application/zip' === $attachment->post_mime_type ) {
4004
					// Schedule a cleanup for 2 hours from now in case of failed install.
4005
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
4006
				}
4007
			}
4008
		}
4009
		if ( ! is_null( $global_post ) ) {
4010
			$GLOBALS['post'] = $global_post;
4011
		}
4012
4013
		return $uploaded_files;
4014
	}
4015
4016
	/**
4017
	 * Add help to the Jetpack page
4018
	 *
4019
	 * @since Jetpack (1.2.3)
4020
	 * @return false if not the Jetpack page
4021
	 */
4022
	function admin_help() {
4023
		$current_screen = get_current_screen();
4024
4025
		// Overview
4026
		$current_screen->add_help_tab(
4027
			array(
4028
				'id'      => 'home',
4029
				'title'   => __( 'Home', 'jetpack' ),
4030
				'content' =>
4031
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4032
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4033
					'<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>',
4034
			)
4035
		);
4036
4037
		// Screen Content
4038
		if ( current_user_can( 'manage_options' ) ) {
4039
			$current_screen->add_help_tab(
4040
				array(
4041
					'id'      => 'settings',
4042
					'title'   => __( 'Settings', 'jetpack' ),
4043
					'content' =>
4044
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4045
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4046
						'<ol>' .
4047
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4048
							'<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>' .
4049
						'</ol>' .
4050
						'<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>',
4051
				)
4052
			);
4053
		}
4054
4055
		// Help Sidebar
4056
		$support_url = Redirect::get_url( 'jetpack-support' );
4057
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4058
		$current_screen->set_help_sidebar(
4059
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4060
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4061
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4062
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4063
		);
4064
	}
4065
4066
	function admin_menu_css() {
4067
		wp_enqueue_style( 'jetpack-icons' );
4068
	}
4069
4070
	function admin_menu_order() {
4071
		return true;
4072
	}
4073
4074
	function jetpack_menu_order( $menu_order ) {
4075
		$jp_menu_order = array();
4076
4077
		foreach ( $menu_order as $index => $item ) {
4078
			if ( $item != 'jetpack' ) {
4079
				$jp_menu_order[] = $item;
4080
			}
4081
4082
			if ( $index == 0 ) {
4083
				$jp_menu_order[] = 'jetpack';
4084
			}
4085
		}
4086
4087
		return $jp_menu_order;
4088
	}
4089
4090
	function admin_banner_styles() {
4091
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4092
4093
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4094
			wp_register_style(
4095
				'jetpack-dops-style',
4096
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4097
				array(),
4098
				JETPACK__VERSION
4099
			);
4100
		}
4101
4102
		wp_enqueue_style(
4103
			'jetpack',
4104
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4105
			array( 'jetpack-dops-style' ),
4106
			JETPACK__VERSION . '-20121016'
4107
		);
4108
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4109
		wp_style_add_data( 'jetpack', 'suffix', $min );
4110
	}
4111
4112
	function plugin_action_links( $actions ) {
4113
4114
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4115
4116
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
4117
			return array_merge(
4118
				$jetpack_home,
4119
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4120
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4121
				$actions
4122
			);
4123
		}
4124
4125
		return array_merge( $jetpack_home, $actions );
4126
	}
4127
4128
	/**
4129
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4130
	 *
4131
	 * @param string $hook The current admin page.
4132
	 *
4133
	 * @return void
4134
	 */
4135
	public function deactivate_dialog( $hook ) {
4136
		if (
4137
			'plugins.php' === $hook
4138
			&& self::is_connection_ready()
4139
		) {
4140
4141
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4142
4143
			if ( count( $active_plugins_using_connection ) > 1 ) {
4144
4145
				add_thickbox();
4146
4147
				wp_register_script(
4148
					'jp-tracks',
4149
					'//stats.wp.com/w.js',
4150
					array(),
4151
					gmdate( 'YW' ),
4152
					true
4153
				);
4154
4155
				wp_register_script(
4156
					'jp-tracks-functions',
4157
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4158
					array( 'jp-tracks' ),
4159
					JETPACK__VERSION,
4160
					false
4161
				);
4162
4163
				wp_enqueue_script(
4164
					'jetpack-deactivate-dialog-js',
4165
					Assets::get_file_url_for_environment(
4166
						'_inc/build/jetpack-deactivate-dialog.min.js',
4167
						'_inc/jetpack-deactivate-dialog.js'
4168
					),
4169
					array( 'jquery', 'jp-tracks-functions' ),
4170
					JETPACK__VERSION,
4171
					true
4172
				);
4173
4174
				wp_localize_script(
4175
					'jetpack-deactivate-dialog-js',
4176
					'deactivate_dialog',
4177
					array(
4178
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4179
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4180
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4181
					)
4182
				);
4183
4184
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4185
4186
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4187
			}
4188
		}
4189
	}
4190
4191
	/**
4192
	 * Outputs the content of the deactivation modal
4193
	 *
4194
	 * @return void
4195
	 */
4196
	public function deactivate_dialog_content() {
4197
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4198
		unset( $active_plugins_using_connection['jetpack'] );
4199
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
Bug introduced by
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4197 can also be of type object<WP_Error>; however, Jetpack::load_view() does only seem to accept array, maybe add an additional type check?

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

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

    return array();
}

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

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

Loading history...
4200
	}
4201
4202
	/**
4203
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4204
	 *
4205
	 * @param string $login_url The wp-login URL.
4206
	 * @param string $redirect  URL to redirect users after logging in.
4207
	 * @since Jetpack 8.4
4208
	 * @return string
4209
	 */
4210
	public function login_url( $login_url, $redirect ) {
4211
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4212
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4213
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4214
		}
4215
		return $login_url;
4216
	}
4217
4218
	/**
4219
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4220
	 *
4221
	 * @since Jetpack 8.4
4222
	 */
4223
	public function login_init() {
4224
		// phpcs:ignore WordPress.Security.NonceVerification
4225
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4226
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4227
			wp_safe_redirect(
4228
				add_query_arg(
4229
					array(
4230
						'forceInstall' => 1,
4231
						'url'          => rawurlencode( get_site_url() ),
4232
					),
4233
					// @todo provide way to go to specific calypso env.
4234
					self::get_calypso_host() . 'jetpack/connect'
4235
				)
4236
			);
4237
			exit;
4238
		}
4239
	}
4240
4241
	/*
4242
	 * Registration flow:
4243
	 * 1 - ::admin_page_load() action=register
4244
	 * 2 - ::try_registration()
4245
	 * 3 - ::register()
4246
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4247
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4248
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4249
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4250
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4251
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4252
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4253
	 *       jetpack_id, jetpack_secret, jetpack_public
4254
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4255
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4256
	 * 5 - user logs in with WP.com account
4257
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4258
	 *		- Manager::authorize()
4259
	 *		- Manager::get_token()
4260
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4261
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4262
	 *			- which responds with access_token, token_type, scope
4263
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4264
	 *		- Jetpack::activate_default_modules()
4265
	 *     		- Deactivates deprecated plugins
4266
	 *     		- Activates all default modules
4267
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4268
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4269
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4270
	 *     Done!
4271
	 */
4272
4273
	/**
4274
	 * Handles the page load events for the Jetpack admin page
4275
	 */
4276
	function admin_page_load() {
4277
		$error = false;
4278
4279
		// Make sure we have the right body class to hook stylings for subpages off of.
4280
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4281
4282
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4283
			// Should only be used in intermediate redirects to preserve state across redirects
4284
			self::restate();
4285
		}
4286
4287
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4288
			// @todo: Add validation against a known allowed list.
4289
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4290
			// User clicked in the iframe to link their accounts
4291
			if ( ! self::connection()->is_user_connected() ) {
4292
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4293
4294
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4295
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4296
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4297
4298
				if ( isset( $_GET['notes_iframe'] ) ) {
4299
					$connect_url .= '&notes_iframe';
4300
				}
4301
				wp_redirect( $connect_url );
4302
				exit;
4303
			} else {
4304
				if ( ! isset( $_GET['calypso_env'] ) ) {
4305
					self::state( 'message', 'already_authorized' );
4306
					wp_safe_redirect( self::admin_url() );
4307
					exit;
4308
				} else {
4309
					$connect_url  = $this->build_connect_url( true, false, $from );
4310
					$connect_url .= '&already_authorized=true';
4311
					wp_redirect( $connect_url );
4312
					exit;
4313
				}
4314
			}
4315
		}
4316
4317
		if ( isset( $_GET['action'] ) ) {
4318
			switch ( $_GET['action'] ) {
4319
				case 'authorize_redirect':
4320
					self::log( 'authorize_redirect' );
4321
4322
					add_filter(
4323
						'allowed_redirect_hosts',
4324
						function ( $domains ) {
4325
							$domains[] = 'jetpack.com';
4326
							$domains[] = 'jetpack.wordpress.com';
4327
							$domains[] = 'wordpress.com';
4328
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4329
							return array_unique( $domains );
4330
						}
4331
					);
4332
4333
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4334
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4335
4336
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4337
						// The destination URL is missing or invalid, nothing to do here.
4338
						exit;
4339
					}
4340
4341
					if ( static::connection()->is_connected() && static::connection()->is_user_connected() ) {
4342
						// The user is either already connected, or finished the connection process.
4343
						wp_safe_redirect( $dest_url );
4344
						exit;
4345
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4346
						// The user decided not to proceed with setting up the connection.
4347
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4348
						exit;
4349
					}
4350
4351
					$redirect_url = self::admin_url(
4352
						array(
4353
							'page'     => 'jetpack',
4354
							'action'   => 'authorize_redirect',
4355
							'dest_url' => rawurlencode( $dest_url ),
4356
							'done'     => '1',
4357
						)
4358
					);
4359
4360
					wp_safe_redirect( static::build_authorize_url( $redirect_url ) );
0 ignored issues
show
Documentation introduced by
$redirect_url 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...
4361
					exit;
4362
				case 'authorize':
4363
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4364
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4365
					exit;
4366
				case 'register':
4367
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4368
						$error = 'cheatin';
4369
						break;
4370
					}
4371
					check_admin_referer( 'jetpack-register' );
4372
					self::log( 'register' );
4373
					self::maybe_set_version_option();
4374
					$registered = self::try_registration();
4375
					if ( is_wp_error( $registered ) ) {
4376
						$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...
4377
						self::state( 'error', $error );
4378
						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...
4379
4380
						/**
4381
						 * Jetpack registration Error.
4382
						 *
4383
						 * @since 7.5.0
4384
						 *
4385
						 * @param string|int $error The error code.
4386
						 * @param \WP_Error $registered The error object.
4387
						 */
4388
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4389
						break;
4390
					}
4391
4392
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4393
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4394
4395
					/**
4396
					 * Jetpack registration Success.
4397
					 *
4398
					 * @since 7.5.0
4399
					 *
4400
					 * @param string $from 'from' GET parameter;
4401
					 */
4402
					do_action( 'jetpack_connection_register_success', $from );
4403
4404
					$url = $this->build_connect_url( true, $redirect, $from );
4405
4406
					if ( ! empty( $_GET['onboarding'] ) ) {
4407
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4408
					}
4409
4410
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4411
						$url = add_query_arg( 'auth_approved', 'true', $url );
4412
					}
4413
4414
					wp_redirect( $url );
4415
					exit;
4416
				case 'activate':
4417
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4418
						$error = 'cheatin';
4419
						break;
4420
					}
4421
4422
					$module = stripslashes( $_GET['module'] );
4423
					check_admin_referer( "jetpack_activate-$module" );
4424
					self::log( 'activate', $module );
4425
					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...
4426
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4427
					}
4428
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4429
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4430
					exit;
4431
				case 'activate_default_modules':
4432
					check_admin_referer( 'activate_default_modules' );
4433
					self::log( 'activate_default_modules' );
4434
					self::restate();
4435
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4436
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4437
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4438
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4439
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4440
					exit;
4441 View Code Duplication
				case 'disconnect':
4442
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4443
						$error = 'cheatin';
4444
						break;
4445
					}
4446
4447
					check_admin_referer( 'jetpack-disconnect' );
4448
					self::log( 'disconnect' );
4449
					self::disconnect();
4450
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4451
					exit;
4452 View Code Duplication
				case 'reconnect':
4453
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4454
						$error = 'cheatin';
4455
						break;
4456
					}
4457
4458
					check_admin_referer( 'jetpack-reconnect' );
4459
					self::log( 'reconnect' );
4460
					self::disconnect();
4461
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4462
					exit;
4463 View Code Duplication
				case 'deactivate':
4464
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4465
						$error = 'cheatin';
4466
						break;
4467
					}
4468
4469
					$modules = stripslashes( $_GET['module'] );
4470
					check_admin_referer( "jetpack_deactivate-$modules" );
4471
					foreach ( explode( ',', $modules ) as $module ) {
4472
						self::log( 'deactivate', $module );
4473
						self::deactivate_module( $module );
4474
						self::state( 'message', 'module_deactivated' );
4475
					}
4476
					self::state( 'module', $modules );
4477
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4478
					exit;
4479
				case 'unlink':
4480
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4481
					check_admin_referer( 'jetpack-unlink' );
4482
					self::log( 'unlink' );
4483
					$this->connection_manager->disconnect_user();
4484
					self::state( 'message', 'unlinked' );
4485
					if ( 'sub-unlink' == $redirect ) {
4486
						wp_safe_redirect( admin_url() );
4487
					} else {
4488
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4489
					}
4490
					exit;
4491
				case 'onboard':
4492
					if ( ! current_user_can( 'manage_options' ) ) {
4493
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4494
					} else {
4495
						self::create_onboarding_token();
4496
						$url = $this->build_connect_url( true );
4497
4498
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4499
							$url = add_query_arg( 'onboarding', $token, $url );
4500
						}
4501
4502
						$calypso_env = $this->get_calypso_env();
4503
						if ( ! empty( $calypso_env ) ) {
4504
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4505
						}
4506
4507
						wp_redirect( $url );
4508
						exit;
4509
					}
4510
					exit;
4511
				default:
4512
					/**
4513
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4514
					 *
4515
					 * @since 2.6.0
4516
					 *
4517
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4518
					 */
4519
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4520
			}
4521
		}
4522
4523
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4524
			self::activate_new_modules( true );
4525
		}
4526
4527
		$message_code = self::state( 'message' );
4528
		if ( self::state( 'optin-manage' ) ) {
4529
			$activated_manage = $message_code;
4530
			$message_code     = 'jetpack-manage';
4531
		}
4532
4533
		switch ( $message_code ) {
4534
			case 'jetpack-manage':
4535
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4536
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4537
				$this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), $sites_url ) . '</strong>';
4538
				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...
4539
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4540
				}
4541
				break;
4542
4543
		}
4544
4545
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4546
4547
		if ( ! empty( $deactivated_plugins ) ) {
4548
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4549
			$deactivated_titles  = array();
4550
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4551
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4552
					continue;
4553
				}
4554
4555
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4556
			}
4557
4558
			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...
4559
				if ( $this->message ) {
4560
					$this->message .= "<br /><br />\n";
4561
				}
4562
4563
				$this->message .= wp_sprintf(
4564
					_n(
4565
						'Jetpack contains the most recent version of the old %l plugin.',
4566
						'Jetpack contains the most recent versions of the old %l plugins.',
4567
						count( $deactivated_titles ),
4568
						'jetpack'
4569
					),
4570
					$deactivated_titles
4571
				);
4572
4573
				$this->message .= "<br />\n";
4574
4575
				$this->message .= _n(
4576
					'The old version has been deactivated and can be removed from your site.',
4577
					'The old versions have been deactivated and can be removed from your site.',
4578
					count( $deactivated_titles ),
4579
					'jetpack'
4580
				);
4581
			}
4582
		}
4583
4584
		$this->privacy_checks = self::state( 'privacy_checks' );
4585
4586
		if ( $this->message || $this->error || $this->privacy_checks ) {
4587
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4588
		}
4589
4590
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4591
	}
4592
4593
	function admin_notices() {
4594
4595
		if ( $this->error ) {
4596
			?>
4597
<div id="message" class="jetpack-message jetpack-err">
4598
	<div class="squeezer">
4599
		<h2>
4600
			<?php
4601
			echo wp_kses(
4602
				$this->error,
4603
				array(
4604
					'a'      => array( 'href' => array() ),
4605
					'small'  => true,
4606
					'code'   => true,
4607
					'strong' => true,
4608
					'br'     => true,
4609
					'b'      => true,
4610
				)
4611
			);
4612
			?>
4613
			</h2>
4614
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4615
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4616
<?php	endif; ?>
4617
	</div>
4618
</div>
4619
			<?php
4620
		}
4621
4622
		if ( $this->message ) {
4623
			?>
4624
<div id="message" class="jetpack-message">
4625
	<div class="squeezer">
4626
		<h2>
4627
			<?php
4628
			echo wp_kses(
4629
				$this->message,
4630
				array(
4631
					'strong' => array(),
4632
					'a'      => array( 'href' => true ),
4633
					'br'     => true,
4634
				)
4635
			);
4636
			?>
4637
			</h2>
4638
	</div>
4639
</div>
4640
			<?php
4641
		}
4642
4643
		if ( $this->privacy_checks ) :
4644
			$module_names = $module_slugs = array();
4645
4646
			$privacy_checks = explode( ',', $this->privacy_checks );
4647
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4648
			foreach ( $privacy_checks as $module_slug ) {
4649
				$module = self::get_module( $module_slug );
4650
				if ( ! $module ) {
4651
					continue;
4652
				}
4653
4654
				$module_slugs[] = $module_slug;
4655
				$module_names[] = "<strong>{$module['name']}</strong>";
4656
			}
4657
4658
			$module_slugs = join( ',', $module_slugs );
4659
			?>
4660
<div id="message" class="jetpack-message jetpack-err">
4661
	<div class="squeezer">
4662
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4663
		<p>
4664
			<?php
4665
			echo wp_kses(
4666
				wptexturize(
4667
					wp_sprintf(
4668
						_nx(
4669
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4670
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4671
							count( $privacy_checks ),
4672
							'%l = list of Jetpack module/feature names',
4673
							'jetpack'
4674
						),
4675
						$module_names
4676
					)
4677
				),
4678
				array( 'strong' => true )
4679
			);
4680
4681
			echo "\n<br />\n";
4682
4683
			echo wp_kses(
4684
				sprintf(
4685
					_nx(
4686
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4687
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4688
						count( $privacy_checks ),
4689
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4690
						'jetpack'
4691
					),
4692
					wp_nonce_url(
4693
						self::admin_url(
4694
							array(
4695
								'page'   => 'jetpack',
4696
								'action' => 'deactivate',
4697
								'module' => urlencode( $module_slugs ),
4698
							)
4699
						),
4700
						"jetpack_deactivate-$module_slugs"
4701
					),
4702
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4703
				),
4704
				array(
4705
					'a' => array(
4706
						'href'  => true,
4707
						'title' => true,
4708
					),
4709
				)
4710
			);
4711
			?>
4712
		</p>
4713
	</div>
4714
</div>
4715
			<?php
4716
endif;
4717
	}
4718
4719
	/**
4720
	 * We can't always respond to a signed XML-RPC request with a
4721
	 * helpful error message. In some circumstances, doing so could
4722
	 * leak information.
4723
	 *
4724
	 * Instead, track that the error occurred via a Jetpack_Option,
4725
	 * and send that data back in the heartbeat.
4726
	 * All this does is increment a number, but it's enough to find
4727
	 * trends.
4728
	 *
4729
	 * @param WP_Error $xmlrpc_error The error produced during
4730
	 *                               signature validation.
4731
	 */
4732
	function track_xmlrpc_error( $xmlrpc_error ) {
4733
		$code = is_wp_error( $xmlrpc_error )
4734
			? $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...
4735
			: 'should-not-happen';
4736
4737
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4738
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4739
			// No need to update the option if we already have
4740
			// this code stored.
4741
			return;
4742
		}
4743
		$xmlrpc_errors[ $code ] = true;
4744
4745
		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...
4746
	}
4747
4748
	/**
4749
	 * Initialize the jetpack stats instance only when needed
4750
	 *
4751
	 * @return void
4752
	 */
4753
	private function initialize_stats() {
4754
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4755
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4756
		}
4757
	}
4758
4759
	/**
4760
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4761
	 */
4762
	function stat( $group, $detail ) {
4763
		$this->initialize_stats();
4764
		$this->a8c_mc_stats_instance->add( $group, $detail );
4765
4766
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4767
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4768
	}
4769
4770
	/**
4771
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4772
	 */
4773
	function do_stats( $method = '' ) {
4774
		$this->initialize_stats();
4775
		if ( 'server_side' === $method ) {
4776
			$this->a8c_mc_stats_instance->do_server_side_stats();
4777
		} else {
4778
			$this->a8c_mc_stats_instance->do_stats();
4779
		}
4780
4781
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4782
		$this->stats = array();
4783
	}
4784
4785
	/**
4786
	 * Runs stats code for a one-off, server-side.
4787
	 *
4788
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4789
	 *
4790
	 * @return bool If it worked.
4791
	 */
4792
	static function do_server_side_stat( $args ) {
4793
		$url                   = self::build_stats_url( $args );
4794
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4795
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4796
	}
4797
4798
	/**
4799
	 * Builds the stats url.
4800
	 *
4801
	 * @param $args array|string The arguments to append to the URL.
4802
	 *
4803
	 * @return string The URL to be pinged.
4804
	 */
4805
	static function build_stats_url( $args ) {
4806
4807
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4808
		return $a8c_mc_stats_instance->build_stats_url( $args );
4809
4810
	}
4811
4812
	/**
4813
	 * Builds a URL to the Jetpack connection auth page
4814
	 *
4815
	 * @since 3.9.5
4816
	 *
4817
	 * @param bool        $raw If true, URL will not be escaped.
4818
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4819
	 *                              If string, will be a custom redirect.
4820
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4821
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4822
	 *
4823
	 * @return string Connect URL
4824
	 */
4825
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4826
		$site_id    = Jetpack_Options::get_option( 'id' );
4827
		$blog_token = ( new Tokens() )->get_access_token();
4828
4829
		if ( $register || ! $blog_token || ! $site_id ) {
4830
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4831
4832
			if ( ! empty( $redirect ) ) {
4833
				$url = add_query_arg(
4834
					'redirect',
4835
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4836
					$url
4837
				);
4838
			}
4839
4840
			if ( is_network_admin() ) {
4841
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4842
			}
4843
4844
			$calypso_env = self::get_calypso_env();
4845
4846
			if ( ! empty( $calypso_env ) ) {
4847
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4848
			}
4849
		} else {
4850
4851
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4852
			// because otherwise this logic can get us in to a loop.
4853
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4854
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4855
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4856
4857
				$response = Client::wpcom_json_api_request_as_blog(
4858
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4859
					'1.1'
4860
				);
4861
4862
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4863
4864
					// Generating a register URL instead to refresh the existing token
4865
					return $this->build_connect_url( $raw, $redirect, $from, true );
4866
				}
4867
			}
4868
4869
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4825 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...
4870
		}
4871
4872
		if ( $from ) {
4873
			$url = add_query_arg( 'from', $from, $url );
4874
		}
4875
4876
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4877
		/**
4878
		 * Filter the URL used when connecting a user to a WordPress.com account.
4879
		 *
4880
		 * @since 8.1.0
4881
		 *
4882
		 * @param string $url Connection URL.
4883
		 * @param bool   $raw If true, URL will not be escaped.
4884
		 */
4885
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $raw.

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

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

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

Loading history...
4886
	}
4887
4888
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4889
4890
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4891
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4892
4893
		if ( $iframe ) {
4894
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4895
		}
4896
4897
		$c8n = self::connection();
4898
		$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...
4899
4900
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4901
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4902
4903
		if ( $iframe ) {
4904
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4905
		}
4906
4907
		/**
4908
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4909
		 *
4910
		 * @since 8.9.0
4911
		 *
4912
		 * @param string $url Connection URL.
4913
		 */
4914
		return apply_filters( 'jetpack_build_authorize_url', $url );
4915
	}
4916
4917
	/**
4918
	 * Filters the connection URL parameter array.
4919
	 *
4920
	 * @param array $args default URL parameters used by the package.
4921
	 * @return array the modified URL arguments array.
4922
	 */
4923
	public static function filter_connect_request_body( $args ) {
4924
		if (
4925
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4926
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4927
		) {
4928
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4929
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4930
				? $gp_locale->slug
4931
				: '';
4932
		}
4933
4934
		$tracking        = new Tracking();
4935
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4936
4937
		$args = array_merge(
4938
			$args,
4939
			array(
4940
				'_ui' => $tracks_identity['_ui'],
4941
				'_ut' => $tracks_identity['_ut'],
4942
			)
4943
		);
4944
4945
		$calypso_env = self::get_calypso_env();
4946
4947
		if ( ! empty( $calypso_env ) ) {
4948
			$args['calypso_env'] = $calypso_env;
4949
		}
4950
4951
		return $args;
4952
	}
4953
4954
	/**
4955
	 * Filters the URL that will process the connection data. It can be different from the URL
4956
	 * that we send the user to after everything is done.
4957
	 *
4958
	 * @param String $processing_url the default redirect URL used by the package.
4959
	 * @return String the modified URL.
4960
	 *
4961
	 * @deprecated since Jetpack 9.5.0
4962
	 */
4963
	public static function filter_connect_processing_url( $processing_url ) {
4964
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4965
4966
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4967
		return $processing_url;
4968
	}
4969
4970
	/**
4971
	 * Filters the redirection URL that is used for connect requests. The redirect
4972
	 * URL should return the user back to the Jetpack console.
4973
	 *
4974
	 * @param String $redirect the default redirect URL used by the package.
4975
	 * @return String the modified URL.
4976
	 */
4977
	public static function filter_connect_redirect_url( $redirect ) {
4978
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4979
		$redirect           = $redirect
4980
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4981
			: $jetpack_admin_page;
4982
4983
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4984
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4985
		}
4986
4987
		return $redirect;
4988
	}
4989
4990
	/**
4991
	 * This action fires at the beginning of the Manager::authorize method.
4992
	 */
4993
	public static function authorize_starting() {
4994
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4995
		// Checking if site has been active/connected previously before recording unique connection.
4996
		if ( ! $jetpack_unique_connection ) {
4997
			// jetpack_unique_connection option has never been set.
4998
			$jetpack_unique_connection = array(
4999
				'connected'    => 0,
5000
				'disconnected' => 0,
5001
				'version'      => '3.6.1',
5002
			);
5003
5004
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5005
5006
			// Track unique connection.
5007
			$jetpack = self::init();
5008
5009
			$jetpack->stat( 'connections', 'unique-connection' );
5010
			$jetpack->do_stats( 'server_side' );
5011
		}
5012
5013
		// Increment number of times connected.
5014
		$jetpack_unique_connection['connected'] += 1;
5015
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5016
	}
5017
5018
	/**
5019
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5020
	 * linked.
5021
	 */
5022
	public static function authorize_ending_linked() {
5023
		// Don't activate anything since we are just connecting a user.
5024
		self::state( 'message', 'linked' );
5025
	}
5026
5027
	/**
5028
	 * This action fires at the end of the Manager::authorize method when the master user is
5029
	 * authorized.
5030
	 *
5031
	 * @param array $data The request data.
5032
	 */
5033
	public static function authorize_ending_authorized( $data ) {
5034
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5035
		self::invalidate_onboarding_token();
5036
5037
		// If redirect_uri is SSO, ensure SSO module is enabled.
5038
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5039
5040
		/** This filter is documented in class.jetpack-cli.php */
5041
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5042
5043
		$activate_sso = (
5044
			isset( $redirect_options['action'] ) &&
5045
			'jetpack-sso' === $redirect_options['action'] &&
5046
			$jetpack_start_enable_sso
5047
		);
5048
5049
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5050
5051
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5052
	}
5053
5054
	/**
5055
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5056
	 */
5057
	public static function activate_default_modules_on_site_register() {
5058
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5059
		if ( $active_modules ) {
5060
			self::delete_active_modules();
5061
5062
			// If there was previously activated modules (a reconnection), re-activate them all including those that require a user, and do not re-activate those that have been deactivated.
5063
			self::activate_default_modules( 999, 1, $active_modules, false );
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...
5064
		} else {
5065
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5066
			self::activate_default_modules( false, false, array(), false, null, null, false );
5067
		}
5068
5069
		// Since this is a fresh connection, be sure to clear out IDC options.
5070
		Jetpack_IDC::clear_all_idc_options();
5071
	}
5072
5073
	/**
5074
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5075
	 * reconnect process is completed.
5076
	 * Note that this currently only happens when we don't need the user to re-authorize
5077
	 * their WP.com account, eg in cases where we are restoring a connection with
5078
	 * unhealthy blog token.
5079
	 */
5080
	public static function reconnection_completed() {
5081
		self::state( 'message', 'reconnection_completed' );
5082
	}
5083
5084
	/**
5085
	 * Get our assumed site creation date.
5086
	 * Calculated based on the earlier date of either:
5087
	 * - Earliest admin user registration date.
5088
	 * - Earliest date of post of any post type.
5089
	 *
5090
	 * @since 7.2.0
5091
	 * @deprecated since 7.8.0
5092
	 *
5093
	 * @return string Assumed site creation date and time.
5094
	 */
5095
	public static function get_assumed_site_creation_date() {
5096
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5097
		return self::connection()->get_assumed_site_creation_date();
5098
	}
5099
5100 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5101
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5102
5103
		if ( $activation_source_name ) {
5104
			$args['_as'] = urlencode( $activation_source_name );
5105
		}
5106
5107
		if ( $activation_source_keyword ) {
5108
			$args['_ak'] = urlencode( $activation_source_keyword );
5109
		}
5110
	}
5111
5112
	function build_reconnect_url( $raw = false ) {
5113
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5114
		return $raw ? $url : esc_url( $url );
5115
	}
5116
5117
	public static function admin_url( $args = null ) {
5118
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
Documentation introduced by
array('page' => 'jetpack') is of type array<string,string,{"page":"string"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
5119
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5120
		return $url;
5121
	}
5122
5123
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5124
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5125
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5126
	}
5127
5128
	function dismiss_jetpack_notice() {
5129
5130
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5131
			return;
5132
		}
5133
5134
		switch ( $_GET['jetpack-notice'] ) {
5135
			case 'dismiss':
5136
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5137
5138
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5139
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5140
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5141
				}
5142
				break;
5143
		}
5144
	}
5145
5146
	public static function sort_modules( $a, $b ) {
5147
		if ( $a['sort'] == $b['sort'] ) {
5148
			return 0;
5149
		}
5150
5151
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5152
	}
5153
5154
	function ajax_recheck_ssl() {
5155
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5156
		$result = self::permit_ssl( true );
5157
		wp_send_json(
5158
			array(
5159
				'enabled' => $result,
5160
				'message' => get_transient( 'jetpack_https_test_message' ),
5161
			)
5162
		);
5163
	}
5164
5165
	/* Client API */
5166
5167
	/**
5168
	 * Returns the requested Jetpack API URL
5169
	 *
5170
	 * @deprecated since 7.7
5171
	 * @return string
5172
	 */
5173
	public static function api_url( $relative_url ) {
5174
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5175
		$connection = self::connection();
5176
		return $connection->api_url( $relative_url );
5177
	}
5178
5179
	/**
5180
	 * @deprecated 8.0
5181
	 *
5182
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5183
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5184
	 */
5185
	public static function fix_url_for_bad_hosts( $url ) {
5186
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5187
		return $url;
5188
	}
5189
5190
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5191
		// Default to a blog token.
5192
		$token_type = 'blog';
5193
5194
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5195
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5196
			if ( ! empty( $_GET['onboarding'] ) ) {
5197
				$jpo = $_GET;
5198
			} else {
5199
				$jpo = json_decode( $request_data, true );
5200
			}
5201
5202
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5203
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5204
5205
			if (
5206
				isset( $jpo_user )
5207
				&& isset( $jpo_token )
5208
				&& is_email( $jpo_user )
5209
				&& ctype_alnum( $jpo_token )
5210
				&& isset( $_GET['rest_route'] )
5211
				&& self::validate_onboarding_token_action(
5212
					$jpo_token,
5213
					$_GET['rest_route']
5214
				)
5215
			) {
5216
				$jp_user = get_user_by( 'email', $jpo_user );
5217
				if ( is_a( $jp_user, 'WP_User' ) ) {
5218
					wp_set_current_user( $jp_user->ID );
5219
					$user_can = is_multisite()
5220
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5221
						: current_user_can( 'manage_options' );
5222
					if ( $user_can ) {
5223
						$token_type              = 'user';
5224
						$token->external_user_id = $jp_user->ID;
5225
					}
5226
				}
5227
			}
5228
5229
			$token_data['type']    = $token_type;
5230
			$token_data['user_id'] = $token->external_user_id;
5231
		}
5232
5233
		return $token_data;
5234
	}
5235
5236
	/**
5237
	 * Create a random secret for validating onboarding payload
5238
	 *
5239
	 * @return string Secret token
5240
	 */
5241
	public static function create_onboarding_token() {
5242
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5243
			$token = wp_generate_password( 32, false );
5244
			Jetpack_Options::update_option( 'onboarding', $token );
5245
		}
5246
5247
		return $token;
5248
	}
5249
5250
	/**
5251
	 * Remove the onboarding token
5252
	 *
5253
	 * @return bool True on success, false on failure
5254
	 */
5255
	public static function invalidate_onboarding_token() {
5256
		return Jetpack_Options::delete_option( 'onboarding' );
5257
	}
5258
5259
	/**
5260
	 * Validate an onboarding token for a specific action
5261
	 *
5262
	 * @return boolean True if token/action pair is accepted, false if not
5263
	 */
5264
	public static function validate_onboarding_token_action( $token, $action ) {
5265
		// Compare tokens, bail if tokens do not match
5266
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5267
			return false;
5268
		}
5269
5270
		// List of valid actions we can take
5271
		$valid_actions = array(
5272
			'/jetpack/v4/settings',
5273
		);
5274
5275
		// Only allow valid actions.
5276
		if ( ! in_array( $action, $valid_actions ) ) {
5277
			return false;
5278
		}
5279
5280
		return true;
5281
	}
5282
5283
	/**
5284
	 * Checks to see if the URL is using SSL to connect with Jetpack
5285
	 *
5286
	 * @since 2.3.3
5287
	 * @return boolean
5288
	 */
5289
	public static function permit_ssl( $force_recheck = false ) {
5290
		// Do some fancy tests to see if ssl is being supported
5291
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5292
			$message = '';
5293
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5294
				$ssl = 0;
5295
			} else {
5296
				$ssl = 1;
5297
5298
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5299
					$ssl     = 0;
5300
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5301
				} else {
5302
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5303
					if ( is_wp_error( $response ) ) {
5304
						$ssl     = 0;
5305
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5306
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5307
						$ssl     = 0;
5308
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5309
					}
5310
				}
5311
			}
5312
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5313
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5314
		}
5315
5316
		return (bool) $ssl;
5317
	}
5318
5319
	/*
5320
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5321
	 */
5322
	public function alert_auto_ssl_fail() {
5323
		if ( ! current_user_can( 'manage_options' ) ) {
5324
			return;
5325
		}
5326
5327
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5328
		?>
5329
5330
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5331
			<div class="jp-banner__content">
5332
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5333
				<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>
5334
				<p>
5335
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5336
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5337
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5338
				</p>
5339
				<p>
5340
					<?php
5341
					printf(
5342
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5343
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5344
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5345
					);
5346
					?>
5347
				</p>
5348
			</div>
5349
		</div>
5350
		<style>
5351
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5352
		</style>
5353
		<script type="text/javascript">
5354
			jQuery( document ).ready( function( $ ) {
5355
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5356
					var $this = $( this );
5357
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5358
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5359
					e.preventDefault();
5360
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5361
					$.post( ajaxurl, data )
5362
					  .done( function( response ) {
5363
						  if ( response.enabled ) {
5364
							  $( '#jetpack-ssl-warning' ).hide();
5365
						  } else {
5366
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5367
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5368
						  }
5369
					  }.bind( $this ) );
5370
				} );
5371
			} );
5372
		</script>
5373
5374
		<?php
5375
	}
5376
5377
	/**
5378
	 * Returns the Jetpack XML-RPC API
5379
	 *
5380
	 * @deprecated 8.0 Use Connection_Manager instead.
5381
	 * @return string
5382
	 */
5383
	public static function xmlrpc_api_url() {
5384
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5385
		return self::connection()->xmlrpc_api_url();
5386
	}
5387
5388
	/**
5389
	 * Returns the connection manager object.
5390
	 *
5391
	 * @return Automattic\Jetpack\Connection\Manager
5392
	 */
5393
	public static function connection() {
5394
		$jetpack = static::init();
5395
5396
		// If the connection manager hasn't been instantiated, do that now.
5397
		if ( ! $jetpack->connection_manager ) {
5398
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5399
		}
5400
5401
		return $jetpack->connection_manager;
5402
	}
5403
5404
	/**
5405
	 * Creates two secret tokens and the end of life timestamp for them.
5406
	 *
5407
	 * Note these tokens are unique per call, NOT static per site for connecting.
5408
	 *
5409
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5410
	 *
5411
	 * @since 2.6
5412
	 * @param String  $action  The action name.
5413
	 * @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...
5414
	 * @param Integer $exp     Expiration time in seconds.
5415
	 * @return array
5416
	 */
5417
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5418
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5419
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5420
	}
5421
5422
	public static function get_secrets( $action, $user_id ) {
5423
		$secrets = ( new Secrets() )->get( $action, $user_id );
5424
5425
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5426
			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...
5427
		}
5428
5429
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5430
			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...
5431
		}
5432
5433
		return $secrets;
5434
	}
5435
5436
	/**
5437
	 * Builds the timeout limit for queries talking with the wpcom servers.
5438
	 *
5439
	 * Based on local php max_execution_time in php.ini
5440
	 *
5441
	 * @since 2.6
5442
	 * @return int
5443
	 * @deprecated
5444
	 **/
5445
	public function get_remote_query_timeout_limit() {
5446
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5447
		return self::get_max_execution_time();
5448
	}
5449
5450
	/**
5451
	 * Builds the timeout limit for queries talking with the wpcom servers.
5452
	 *
5453
	 * Based on local php max_execution_time in php.ini
5454
	 *
5455
	 * @since 5.4
5456
	 * @return int
5457
	 **/
5458
	public static function get_max_execution_time() {
5459
		$timeout = (int) ini_get( 'max_execution_time' );
5460
5461
		// Ensure exec time set in php.ini
5462
		if ( ! $timeout ) {
5463
			$timeout = 30;
5464
		}
5465
		return $timeout;
5466
	}
5467
5468
	/**
5469
	 * Sets a minimum request timeout, and returns the current timeout
5470
	 *
5471
	 * @since 5.4
5472
	 **/
5473 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5474
		$timeout = self::get_max_execution_time();
5475
		if ( $timeout < $min_timeout ) {
5476
			$timeout = $min_timeout;
5477
			set_time_limit( $timeout );
5478
		}
5479
		return $timeout;
5480
	}
5481
5482
	/**
5483
	 * Takes the response from the Jetpack register new site endpoint and
5484
	 * verifies it worked properly.
5485
	 *
5486
	 * @since 2.6
5487
	 * @deprecated since 7.7.0
5488
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5489
	 **/
5490
	public function validate_remote_register_response() {
5491
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5492
	}
5493
5494
	/**
5495
	 * @return bool|WP_Error
5496
	 */
5497
	public static function register() {
5498
		$tracking = new Tracking();
5499
		$tracking->record_user_event( 'jpc_register_begin' );
5500
5501
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5502
5503
		$connection   = self::connection();
5504
		$registration = $connection->register();
5505
5506
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5507
5508
		if ( ! $registration || is_wp_error( $registration ) ) {
5509
			return $registration;
5510
		}
5511
5512
		return true;
5513
	}
5514
5515
	/**
5516
	 * Filters the registration request body to include tracking properties.
5517
	 *
5518
	 * @param array $properties
5519
	 * @return array amended properties.
5520
	 */
5521 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5522
		$tracking        = new Tracking();
5523
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5524
5525
		return array_merge(
5526
			$properties,
5527
			array(
5528
				'_ui' => $tracks_identity['_ui'],
5529
				'_ut' => $tracks_identity['_ut'],
5530
			)
5531
		);
5532
	}
5533
5534
	/**
5535
	 * Filters the token request body to include tracking properties.
5536
	 *
5537
	 * @param array $properties
5538
	 * @return array amended properties.
5539
	 */
5540 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5541
		$tracking        = new Tracking();
5542
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5543
5544
		return array_merge(
5545
			$properties,
5546
			array(
5547
				'_ui' => $tracks_identity['_ui'],
5548
				'_ut' => $tracks_identity['_ut'],
5549
			)
5550
		);
5551
	}
5552
5553
	/**
5554
	 * If the db version is showing something other that what we've got now, bump it to current.
5555
	 *
5556
	 * @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...
5557
	 */
5558
	public static function maybe_set_version_option() {
5559
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5560
		if ( JETPACK__VERSION != $version ) {
5561
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5562
5563
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5564
				/** This action is documented in class.jetpack.php */
5565
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5566
			}
5567
5568
			return true;
5569
		}
5570
		return false;
5571
	}
5572
5573
	/* Client Server API */
5574
5575
	/**
5576
	 * Loads the Jetpack XML-RPC client.
5577
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5578
	 *
5579
	 * @deprecated since 7.7.0
5580
	 */
5581
	public static function load_xml_rpc_client() {
5582
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5583
	}
5584
5585
	/**
5586
	 * Resets the saved authentication state in between testing requests.
5587
	 *
5588
	 * @deprecated since 8.9.0
5589
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5590
	 */
5591
	public function reset_saved_auth_state() {
5592
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5593
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5594
	}
5595
5596
	/**
5597
	 * Verifies the signature of the current request.
5598
	 *
5599
	 * @deprecated since 7.7.0
5600
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5601
	 *
5602
	 * @return false|array
5603
	 */
5604
	public function verify_xml_rpc_signature() {
5605
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5606
		return self::connection()->verify_xml_rpc_signature();
5607
	}
5608
5609
	/**
5610
	 * Verifies the signature of the current request.
5611
	 *
5612
	 * This function has side effects and should not be used. Instead,
5613
	 * use the memoized version `->verify_xml_rpc_signature()`.
5614
	 *
5615
	 * @deprecated since 7.7.0
5616
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5617
	 * @internal
5618
	 */
5619
	private function internal_verify_xml_rpc_signature() {
5620
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5621
	}
5622
5623
	/**
5624
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5625
	 *
5626
	 * @deprecated since 7.7.0
5627
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5628
	 *
5629
	 * @param \WP_User|mixed $user     User object if authenticated.
5630
	 * @param string         $username Username.
5631
	 * @param string         $password Password string.
5632
	 * @return \WP_User|mixed Authenticated user or error.
5633
	 */
5634 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5635
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5636
5637
		if ( ! $this->connection_manager ) {
5638
			$this->connection_manager = new Connection_Manager();
5639
		}
5640
5641
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5642
	}
5643
5644
	/**
5645
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5646
	 * Uses the existing XMLRPC request signing implementation.
5647
	 *
5648
	 * @deprecated since 8.9.0
5649
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5650
	 */
5651
	function wp_rest_authenticate( $user ) {
5652
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5653
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5654
	}
5655
5656
	/**
5657
	 * Report authentication status to the WP REST API.
5658
	 *
5659
	 * @deprecated since 8.9.0
5660
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5661
	 *
5662
	 * @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...
5663
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5664
	 */
5665
	public function wp_rest_authentication_errors( $value ) {
5666
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5667
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5668
	}
5669
5670
	/**
5671
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5672
	 * Capture it here so we can verify the signature later.
5673
	 *
5674
	 * @deprecated since 7.7.0
5675
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5676
	 *
5677
	 * @param array $methods XMLRPC methods.
5678
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5679
	 */
5680 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5681
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5682
5683
		if ( ! $this->connection_manager ) {
5684
			$this->connection_manager = new Connection_Manager();
5685
		}
5686
5687
		return $this->connection_manager->xmlrpc_methods( $methods );
5688
	}
5689
5690
	/**
5691
	 * Register additional public XMLRPC methods.
5692
	 *
5693
	 * @deprecated since 7.7.0
5694
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5695
	 *
5696
	 * @param array $methods Public XMLRPC methods.
5697
	 * @return array Public XMLRPC methods, with the getOptions one.
5698
	 */
5699 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5700
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5701
5702
		if ( ! $this->connection_manager ) {
5703
			$this->connection_manager = new Connection_Manager();
5704
		}
5705
5706
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5707
	}
5708
5709
	/**
5710
	 * Handles a getOptions XMLRPC method call.
5711
	 *
5712
	 * @deprecated since 7.7.0
5713
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5714
	 *
5715
	 * @param array $args method call arguments.
5716
	 * @return array an amended XMLRPC server options array.
5717
	 */
5718 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5719
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5720
5721
		if ( ! $this->connection_manager ) {
5722
			$this->connection_manager = new Connection_Manager();
5723
		}
5724
5725
		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...
5726
	}
5727
5728
	/**
5729
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5730
	 *
5731
	 * @deprecated since 7.7.0
5732
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5733
	 *
5734
	 * @param array $options Standard Core options.
5735
	 * @return array Amended options.
5736
	 */
5737 View Code Duplication
	public function xmlrpc_options( $options ) {
5738
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5739
5740
		if ( ! $this->connection_manager ) {
5741
			$this->connection_manager = new Connection_Manager();
5742
		}
5743
5744
		return $this->connection_manager->xmlrpc_options( $options );
5745
	}
5746
5747
	/**
5748
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5749
	 * SET: state( $key, $value );
5750
	 * GET: $value = state( $key );
5751
	 *
5752
	 * @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...
5753
	 * @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...
5754
	 * @param bool   $restate private
5755
	 */
5756
	public static function state( $key = null, $value = null, $restate = false ) {
5757
		static $state = array();
5758
		static $path, $domain;
5759
		if ( ! isset( $path ) ) {
5760
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5761
			$admin_url = self::admin_url();
5762
			$bits      = wp_parse_url( $admin_url );
5763
5764
			if ( is_array( $bits ) ) {
5765
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5766
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5767
			} else {
5768
				$path = $domain = null;
5769
			}
5770
		}
5771
5772
		// Extract state from cookies and delete cookies
5773
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5774
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5775
			unset( $_COOKIE['jetpackState'] );
5776
			foreach ( $yum as $k => $v ) {
0 ignored issues
show
Bug introduced by
The expression $yum of type string|array<integer,string> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

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

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

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

Loading history...
5777
				if ( strlen( $v ) ) {
5778
					$state[ $k ] = $v;
5779
				}
5780
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5781
			}
5782
		}
5783
5784
		if ( $restate ) {
5785
			foreach ( $state as $k => $v ) {
5786
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5787
			}
5788
			return;
5789
		}
5790
5791
		// Get a state variable.
5792
		if ( isset( $key ) && ! isset( $value ) ) {
5793
			if ( array_key_exists( $key, $state ) ) {
5794
				return $state[ $key ];
5795
			}
5796
			return null;
5797
		}
5798
5799
		// Set a state variable.
5800
		if ( isset( $key ) && isset( $value ) ) {
5801
			if ( is_array( $value ) && isset( $value[0] ) ) {
5802
				$value = $value[0];
5803
			}
5804
			$state[ $key ] = $value;
5805
			if ( ! headers_sent() ) {
5806
				if ( self::should_set_cookie( $key ) ) {
5807
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5808
				}
5809
			}
5810
		}
5811
	}
5812
5813
	public static function restate() {
5814
		self::state( null, null, true );
5815
	}
5816
5817
	/**
5818
	 * Determines whether the jetpackState[$key] value should be added to the
5819
	 * cookie.
5820
	 *
5821
	 * @param string $key The state key.
5822
	 *
5823
	 * @return boolean Whether the value should be added to the cookie.
5824
	 */
5825
	public static function should_set_cookie( $key ) {
5826
		global $current_screen;
5827
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5828
5829
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5830
			return false;
5831
		}
5832
5833
		return true;
5834
	}
5835
5836
	public static function check_privacy( $file ) {
5837
		static $is_site_publicly_accessible = null;
5838
5839
		if ( is_null( $is_site_publicly_accessible ) ) {
5840
			$is_site_publicly_accessible = false;
5841
5842
			$rpc = new Jetpack_IXR_Client();
5843
5844
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5845
			if ( $success ) {
5846
				$response = $rpc->getResponse();
5847
				if ( $response ) {
5848
					$is_site_publicly_accessible = true;
5849
				}
5850
			}
5851
5852
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5853
		}
5854
5855
		if ( $is_site_publicly_accessible ) {
5856
			return;
5857
		}
5858
5859
		$module_slug = self::get_module_slug( $file );
5860
5861
		$privacy_checks = self::state( 'privacy_checks' );
5862
		if ( ! $privacy_checks ) {
5863
			$privacy_checks = $module_slug;
5864
		} else {
5865
			$privacy_checks .= ",$module_slug";
5866
		}
5867
5868
		self::state( 'privacy_checks', $privacy_checks );
5869
	}
5870
5871
	/**
5872
	 * Helper method for multicall XMLRPC.
5873
	 *
5874
	 * @deprecated since 8.9.0
5875
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5876
	 *
5877
	 * @param ...$args Args for the async_call.
5878
	 */
5879
	public static function xmlrpc_async_call( ...$args ) {
5880
5881
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5882
5883
		global $blog_id;
5884
		static $clients = array();
5885
5886
		$client_blog_id = is_multisite() ? $blog_id : 0;
5887
5888
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5889
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5890
			if ( function_exists( 'ignore_user_abort' ) ) {
5891
				ignore_user_abort( true );
5892
			}
5893
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5894
		}
5895
5896
		if ( ! empty( $args[0] ) ) {
5897
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5898
		} elseif ( is_multisite() ) {
5899
			foreach ( $clients as $client_blog_id => $client ) {
5900
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5901
					continue;
5902
				}
5903
5904
				$switch_success = switch_to_blog( $client_blog_id, true );
5905
				if ( ! $switch_success ) {
5906
					continue;
5907
				}
5908
5909
				flush();
5910
				$client->query();
5911
5912
				restore_current_blog();
5913
			}
5914
		} else {
5915
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5916
				flush();
5917
				$clients[0]->query();
5918
			}
5919
		}
5920
	}
5921
5922
	/**
5923
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5924
	 *
5925
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5926
	 *
5927
	 * @param string $url WordPress.com static resource URL.
5928
	 */
5929
	public static function staticize_subdomain( $url ) {
5930
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5931
		return Assets::staticize_subdomain( $url );
5932
	}
5933
5934
	/* JSON API Authorization */
5935
5936
	/**
5937
	 * Handles the login action for Authorizing the JSON API
5938
	 */
5939
	function login_form_json_api_authorization() {
5940
		$this->verify_json_api_authorization_request();
5941
5942
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5943
5944
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5945
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5946
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5947
	}
5948
5949
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5950
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5951
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5952
			return $url;
5953
		}
5954
5955
		$parsed_url = wp_parse_url( $url );
5956
		$url        = strtok( $url, '?' );
5957
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5958
		if ( ! empty( $parsed_url['query'] ) ) {
5959
			$url .= "&{$parsed_url['query']}";
5960
		}
5961
5962
		return $url;
5963
	}
5964
5965
	// Make sure the POSTed request is handled by the same action
5966
	function preserve_action_in_login_form_for_json_api_authorization() {
5967
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5968
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5969
	}
5970
5971
	// If someone logs in to approve API access, store the Access Code in usermeta
5972
	function store_json_api_authorization_token( $user_login, $user ) {
5973
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5974
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5975
		$token = wp_generate_password( 32, false );
5976
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5977
	}
5978
5979
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5980
	function allow_wpcom_public_api_domain( $domains ) {
5981
		$domains[] = 'public-api.wordpress.com';
5982
		return $domains;
5983
	}
5984
5985
	static function is_redirect_encoded( $redirect_url ) {
5986
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5987
	}
5988
5989
	// Add all wordpress.com environments to the safe redirect allowed list.
5990
	function allow_wpcom_environments( $domains ) {
5991
		$domains[] = 'wordpress.com';
5992
		$domains[] = 'wpcalypso.wordpress.com';
5993
		$domains[] = 'horizon.wordpress.com';
5994
		$domains[] = 'calypso.localhost';
5995
		return $domains;
5996
	}
5997
5998
	// Add the Access Code details to the public-api.wordpress.com redirect
5999
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6000
		return add_query_arg(
6001
			urlencode_deep(
6002
				array(
6003
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6004
					'jetpack-user-id' => (int) $user->ID,
6005
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6006
				)
6007
			),
6008
			$redirect_to
6009
		);
6010
	}
6011
6012
	/**
6013
	 * Verifies the request by checking the signature
6014
	 *
6015
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6016
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6017
	 *
6018
	 * @param null|array $environment
6019
	 */
6020
	function verify_json_api_authorization_request( $environment = null ) {
6021
		$environment = is_null( $environment )
6022
			? $_REQUEST
6023
			: $environment;
6024
6025
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
6026
		list( $env_token, $env_version, $env_user_id ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $env_version 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...
6027
		$token = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
6028
		if ( ! $token || empty( $token->secret ) ) {
6029
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6030
		}
6031
6032
		$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' );
6033
6034
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6035
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6036
			/**
6037
			 * Jetpack authorisation request Error.
6038
			 *
6039
			 * @since 7.5.0
6040
			 */
6041
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6042
			$die_error = sprintf(
6043
				/* translators: %s is a URL */
6044
				__( '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' ),
6045
				Redirect::get_url( 'jetpack-support-double-encoding' )
6046
			);
6047
		}
6048
6049
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6050
6051
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6052
			$signature = $jetpack_signature->sign_request(
6053
				$environment['token'],
6054
				$environment['timestamp'],
6055
				$environment['nonce'],
6056
				'',
6057
				'GET',
6058
				$environment['jetpack_json_api_original_query'],
6059
				null,
6060
				true
6061
			);
6062
		} else {
6063
			$signature = $jetpack_signature->sign_current_request(
6064
				array(
6065
					'body'   => null,
6066
					'method' => 'GET',
6067
				)
6068
			);
6069
		}
6070
6071
		if ( ! $signature ) {
6072
			wp_die( $die_error );
6073
		} elseif ( is_wp_error( $signature ) ) {
6074
			wp_die( $die_error );
6075
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6076
			if ( is_ssl() ) {
6077
				// 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
6078
				$signature = $jetpack_signature->sign_current_request(
6079
					array(
6080
						'scheme' => 'http',
6081
						'body'   => null,
6082
						'method' => 'GET',
6083
					)
6084
				);
6085
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6086
					wp_die( $die_error );
6087
				}
6088
			} else {
6089
				wp_die( $die_error );
6090
			}
6091
		}
6092
6093
		$timestamp = (int) $environment['timestamp'];
6094
		$nonce     = stripslashes( (string) $environment['nonce'] );
6095
6096
		if ( ! $this->connection_manager ) {
6097
			$this->connection_manager = new Connection_Manager();
6098
		}
6099
6100
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6101
			// De-nonce the nonce, at least for 5 minutes.
6102
			// 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)
6103
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6104
			if ( $old_nonce_time < time() - 300 ) {
6105
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6106
			}
6107
		}
6108
6109
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6110
		$data_filters = array(
6111
			'state'        => 'opaque',
6112
			'client_id'    => 'int',
6113
			'client_title' => 'string',
6114
			'client_image' => 'url',
6115
		);
6116
6117
		foreach ( $data_filters as $key => $sanitation ) {
6118
			if ( ! isset( $data->$key ) ) {
6119
				wp_die( $die_error );
6120
			}
6121
6122
			switch ( $sanitation ) {
6123
				case 'int':
6124
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6125
					break;
6126
				case 'opaque':
6127
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6128
					break;
6129
				case 'string':
6130
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6131
					break;
6132
				case 'url':
6133
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6134
					break;
6135
			}
6136
		}
6137
6138
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6139
			wp_die( $die_error );
6140
		}
6141
	}
6142
6143
	function login_message_json_api_authorization( $message ) {
6144
		return '<p class="message">' . sprintf(
6145
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6146
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6147
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6148
	}
6149
6150
	/**
6151
	 * Get $content_width, but with a <s>twist</s> filter.
6152
	 */
6153
	public static function get_content_width() {
6154
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6155
			? $GLOBALS['content_width']
6156
			: false;
6157
		/**
6158
		 * Filter the Content Width value.
6159
		 *
6160
		 * @since 2.2.3
6161
		 *
6162
		 * @param string $content_width Content Width value.
6163
		 */
6164
		return apply_filters( 'jetpack_content_width', $content_width );
6165
	}
6166
6167
	/**
6168
	 * Pings the WordPress.com Mirror Site for the specified options.
6169
	 *
6170
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6171
	 *
6172
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6173
	 */
6174
	public function get_cloud_site_options( $option_names ) {
6175
		$option_names = array_filter( (array) $option_names, 'is_string' );
6176
6177
		$xml = new Jetpack_IXR_Client();
6178
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6179
		if ( $xml->isError() ) {
6180
			return array(
6181
				'error_code' => $xml->getErrorCode(),
6182
				'error_msg'  => $xml->getErrorMessage(),
6183
			);
6184
		}
6185
		$cloud_site_options = $xml->getResponse();
6186
6187
		return $cloud_site_options;
6188
	}
6189
6190
	/**
6191
	 * Checks if the site is currently in an identity crisis.
6192
	 *
6193
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6194
	 */
6195
	public static function check_identity_crisis() {
6196
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6197
			return false;
6198
		}
6199
6200
		return Jetpack_Options::get_option( 'sync_error_idc' );
6201
	}
6202
6203
	/**
6204
	 * Checks whether the home and siteurl specifically are allowed.
6205
	 * Written so that we don't have re-check $key and $value params every time
6206
	 * we want to check if this site is allowed, for example in footer.php
6207
	 *
6208
	 * @since  3.8.0
6209
	 * @return bool True = already allowed False = not on the allowed list.
6210
	 */
6211
	public static function is_staging_site() {
6212
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6213
		return ( new Status() )->is_staging_site();
6214
	}
6215
6216
	/**
6217
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6218
	 *
6219
	 * @since 4.4.0
6220
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6221
	 *
6222
	 * @return bool
6223
	 */
6224
	public static function validate_sync_error_idc_option() {
6225
		$is_valid = false;
6226
6227
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6228
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6229
		if ( $sync_error && self::sync_idc_optin() ) {
6230
			$local_options = self::get_sync_error_idc_option();
6231
			// Ensure all values are set.
6232
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6233
6234
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6235
				if (
6236
						isset( $sync_error['wpcom_home'] ) &&
6237
						isset( $sync_error['wpcom_siteurl'] ) &&
6238
						$sync_error['wpcom_home'] === $local_options['home'] &&
6239
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6240
				) {
6241
					$is_valid = false;
6242
					// Enable migrate_for_idc so that sync actions are accepted.
6243
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6244
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6245
					$is_valid = true;
6246
				}
6247
			}
6248
		}
6249
6250
		/**
6251
		 * Filters whether the sync_error_idc option is valid.
6252
		 *
6253
		 * @since 4.4.0
6254
		 *
6255
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6256
		 */
6257
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6258
6259
		if ( ! $is_valid && $sync_error ) {
6260
			// Since the option exists, and did not validate, delete it
6261
			Jetpack_Options::delete_option( 'sync_error_idc' );
6262
		}
6263
6264
		return $is_valid;
6265
	}
6266
6267
	/**
6268
	 * Normalizes a url by doing three things:
6269
	 *  - Strips protocol
6270
	 *  - Strips www
6271
	 *  - Adds a trailing slash
6272
	 *
6273
	 * @since 4.4.0
6274
	 * @param string $url
6275
	 * @return WP_Error|string
6276
	 */
6277
	public static function normalize_url_protocol_agnostic( $url ) {
6278
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6279
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsed_url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

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

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

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

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

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

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

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

Loading history...
7042
	 */
7043
	public static function dns_prefetch( $urls = null ) {
7044
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
7045
		if ( $urls ) {
7046
			Assets::add_resource_hint( $urls );
7047
		}
7048
	}
7049
7050
	public function wp_dashboard_setup() {
7051
		if ( self::is_connection_ready() ) {
7052
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
7053
		}
7054
7055
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
7056
			$jetpack_logo = new Jetpack_Logo();
7057
			$widget_title = sprintf(
7058
				/* translators: Placeholder is a Jetpack logo. */
7059
				__( 'Stats by %s', 'jetpack' ),
7060
				$jetpack_logo->get_jp_emblem( true )
7061
			);
7062
7063
			// Wrap title in span so Logo can be properly styled.
7064
			$widget_title = sprintf(
7065
				'<span>%s</span>',
7066
				$widget_title
7067
			);
7068
7069
			wp_add_dashboard_widget(
7070
				'jetpack_summary_widget',
7071
				$widget_title,
7072
				array( __CLASS__, 'dashboard_widget' )
7073
			);
7074
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
7075
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
7076
7077
			// If we're inactive and not in offline mode, sort our box to the top.
7078
			if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
7079
				global $wp_meta_boxes;
7080
7081
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7082
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7083
7084
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7085
			}
7086
		}
7087
	}
7088
7089
	/**
7090
	 * @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...
7091
	 * @return mixed
7092
	 */
7093
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7094
		if ( ! is_array( $sorted ) ) {
7095
			return $sorted;
7096
		}
7097
7098
		foreach ( $sorted as $box_context => $ids ) {
7099
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7100
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7101
				continue;
7102
			}
7103
7104
			$ids_array = explode( ',', $ids );
7105
			$key       = array_search( 'dashboard_stats', $ids_array );
7106
7107
			if ( false !== $key ) {
7108
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7109
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7110
				$sorted[ $box_context ] = implode( ',', $ids_array );
7111
				// We've found it, stop searching, and just return.
7112
				break;
7113
			}
7114
		}
7115
7116
		return $sorted;
7117
	}
7118
7119
	public static function dashboard_widget() {
7120
		/**
7121
		 * Fires when the dashboard is loaded.
7122
		 *
7123
		 * @since 3.4.0
7124
		 */
7125
		do_action( 'jetpack_dashboard_widget' );
7126
	}
7127
7128
	public static function dashboard_widget_footer() {
7129
		?>
7130
		<footer>
7131
7132
		<div class="protect">
7133
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7134
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7135
				<p class="blocked-count">
7136
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7137
				</p>
7138
				<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>
7139
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7140
				<a href="
7141
				<?php
7142
				echo esc_url(
7143
					wp_nonce_url(
7144
						self::admin_url(
7145
							array(
7146
								'action' => 'activate',
7147
								'module' => 'protect',
7148
							)
7149
						),
7150
						'jetpack_activate-protect'
7151
					)
7152
				);
7153
				?>
7154
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7155
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7156
				</a>
7157
			<?php else : ?>
7158
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7159
			<?php endif; ?>
7160
		</div>
7161
7162
		<div class="akismet">
7163
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7164
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7165
				<p class="blocked-count">
7166
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7167
				</p>
7168
				<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>
7169
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7170
				<a href="
7171
				<?php
7172
				echo esc_url(
7173
					wp_nonce_url(
7174
						add_query_arg(
7175
							array(
7176
								'action' => 'activate',
7177
								'plugin' => 'akismet/akismet.php',
7178
							),
7179
							admin_url( 'plugins.php' )
7180
						),
7181
						'activate-plugin_akismet/akismet.php'
7182
					)
7183
				);
7184
				?>
7185
							" class="button button-jetpack">
7186
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7187
				</a>
7188
			<?php else : ?>
7189
				<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>
7190
			<?php endif; ?>
7191
		</div>
7192
7193
		</footer>
7194
		<?php
7195
	}
7196
7197
	/*
7198
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7199
	 */
7200
	function jetpack_icon_user_connected( $columns ) {
7201
		$columns['user_jetpack'] = '';
7202
		return $columns;
7203
	}
7204
7205
	/*
7206
	 * Show Jetpack icon if the user is linked.
7207
	 */
7208
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7209
		if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
7210
			$jetpack_logo = new Jetpack_Logo();
7211
			$emblem_html  = sprintf(
7212
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7213
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7214
				$jetpack_logo->get_jp_emblem()
7215
			);
7216
			return $emblem_html;
7217
		}
7218
7219
		return $val;
7220
	}
7221
7222
	/*
7223
	 * Style the Jetpack user column
7224
	 */
7225
	function jetpack_user_col_style() {
7226
		global $current_screen;
7227
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7228
			?>
7229
			<style>
7230
				.fixed .column-user_jetpack {
7231
					width: 21px;
7232
				}
7233
				.jp-emblem-user-admin svg {
7234
					width: 20px;
7235
					height: 20px;
7236
				}
7237
				.jp-emblem-user-admin path {
7238
					fill: #00BE28;
7239
				}
7240
			</style>
7241
			<?php
7242
		}
7243
	}
7244
7245
	/**
7246
	 * Checks if Akismet is active and working.
7247
	 *
7248
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7249
	 * that implied usage of methods present since more recent version.
7250
	 * See https://github.com/Automattic/jetpack/pull/9585
7251
	 *
7252
	 * @since  5.1.0
7253
	 *
7254
	 * @return bool True = Akismet available. False = Aksimet not available.
7255
	 */
7256
	public static function is_akismet_active() {
7257
		static $status = null;
7258
7259
		if ( ! is_null( $status ) ) {
7260
			return $status;
7261
		}
7262
7263
		// Check if a modern version of Akismet is active.
7264
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7265
			$status = false;
7266
			return $status;
7267
		}
7268
7269
		// Make sure there is a key known to Akismet at all before verifying key.
7270
		$akismet_key = Akismet::get_api_key();
7271
		if ( ! $akismet_key ) {
7272
			$status = false;
7273
			return $status;
7274
		}
7275
7276
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7277
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7278
7279
		// 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.
7280
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7281
		// We cache the result of the Akismet key verification for ten minutes.
7282
		if ( ! $akismet_key_state || $recheck ) {
7283
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7284
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7285
		}
7286
7287
		$status = 'valid' === $akismet_key_state;
7288
7289
		return $status;
7290
	}
7291
7292
	/**
7293
	 * @deprecated
7294
	 *
7295
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7296
	 */
7297
	public static function is_function_in_backtrace() {
7298
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7299
	}
7300
7301
	/**
7302
	 * Given a minified path, and a non-minified path, will return
7303
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7304
	 *
7305
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7306
	 * root Jetpack directory.
7307
	 *
7308
	 * @since 5.6.0
7309
	 *
7310
	 * @param string $min_path
7311
	 * @param string $non_min_path
7312
	 * @return string The URL to the file
7313
	 */
7314
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7315
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7316
	}
7317
7318
	/**
7319
	 * Checks for whether Jetpack Backup is enabled.
7320
	 * Will return true if the state of Backup is anything except "unavailable".
7321
	 *
7322
	 * @return bool|int|mixed
7323
	 */
7324
	public static function is_rewind_enabled() {
7325
		// Rewind is a paid feature, therefore requires a user-level connection.
7326
		if ( ! static::connection()->has_connected_owner() ) {
7327
			return false;
7328
		}
7329
7330
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7331
		if ( false === $rewind_enabled ) {
7332
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7333
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7334
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7335
				&& ! empty( $rewind_data['state'] )
7336
				&& 'active' === $rewind_data['state'] )
7337
				? 1
7338
				: 0;
7339
7340
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7341
		}
7342
		return $rewind_enabled;
7343
	}
7344
7345
	/**
7346
	 * Return Calypso environment value; used for developing Jetpack and pairing
7347
	 * it with different Calypso enrionments, such as localhost.
7348
	 *
7349
	 * @since 7.4.0
7350
	 *
7351
	 * @return string Calypso environment
7352
	 */
7353
	public static function get_calypso_env() {
7354
		if ( isset( $_GET['calypso_env'] ) ) {
7355
			return sanitize_key( $_GET['calypso_env'] );
7356
		}
7357
7358
		if ( getenv( 'CALYPSO_ENV' ) ) {
7359
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7360
		}
7361
7362
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7363
			return sanitize_key( CALYPSO_ENV );
7364
		}
7365
7366
		return '';
7367
	}
7368
7369
	/**
7370
	 * Returns the hostname with protocol for Calypso.
7371
	 * Used for developing Jetpack with Calypso.
7372
	 *
7373
	 * @since 8.4.0
7374
	 *
7375
	 * @return string Calypso host.
7376
	 */
7377
	public static function get_calypso_host() {
7378
		$calypso_env = self::get_calypso_env();
7379
		switch ( $calypso_env ) {
7380
			case 'development':
7381
				return 'http://calypso.localhost:3000/';
7382
			case 'wpcalypso':
7383
				return 'https://wpcalypso.wordpress.com/';
7384
			case 'horizon':
7385
				return 'https://horizon.wordpress.com/';
7386
			default:
7387
				return 'https://wordpress.com/';
7388
		}
7389
	}
7390
7391
	/**
7392
	 * Handles activating default modules as well general cleanup for the new connection.
7393
	 *
7394
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7395
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7396
	 * @param boolean $send_state_messages          Whether to send state messages.
7397
	 * @return void
7398
	 */
7399
	public static function handle_post_authorization_actions(
7400
		$activate_sso = false,
7401
		$redirect_on_activation_error = false,
7402
		$send_state_messages = true
7403
	) {
7404
		$other_modules = $activate_sso
7405
			? array( 'sso' )
7406
			: array();
7407
7408
		if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
7409
			$active_modules = Jetpack_Options::get_option( 'active_modules' );
7410
			self::delete_active_modules();
7411
7412
			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...
7413
		} else {
7414
			// Default modules that don't require a user were already activated on site_register.
7415
			// This time let's activate only those that require a user, this assures we don't reactivate manually deactivated modules while the site was user-less.
7416
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
7417
			Jetpack_Options::update_option( 'active_modules_initialized', true );
7418
		}
7419
7420
		// Since this is a fresh connection, be sure to clear out IDC options
7421
		Jetpack_IDC::clear_all_idc_options();
7422
7423
		if ( $send_state_messages ) {
7424
			self::state( 'message', 'authorized' );
7425
		}
7426
	}
7427
7428
	/**
7429
	 * Returns a boolean for whether backups UI should be displayed or not.
7430
	 *
7431
	 * @return bool Should backups UI be displayed?
7432
	 */
7433
	public static function show_backups_ui() {
7434
		/**
7435
		 * Whether UI for backups should be displayed.
7436
		 *
7437
		 * @since 6.5.0
7438
		 *
7439
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7440
		 */
7441
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7442
	}
7443
7444
	/*
7445
	 * Deprecated manage functions
7446
	 */
7447
	function prepare_manage_jetpack_notice() {
7448
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7449
	}
7450
	function manage_activate_screen() {
7451
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7452
	}
7453
	function admin_jetpack_manage_notice() {
7454
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7455
	}
7456
	function opt_out_jetpack_manage_url() {
7457
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7458
	}
7459
	function opt_in_jetpack_manage_url() {
7460
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7461
	}
7462
	function opt_in_jetpack_manage_notice() {
7463
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7464
	}
7465
	function can_display_jetpack_manage_notice() {
7466
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7467
	}
7468
7469
	/**
7470
	 * Clean leftoveruser meta.
7471
	 *
7472
	 * Delete Jetpack-related user meta when it is no longer needed.
7473
	 *
7474
	 * @since 7.3.0
7475
	 *
7476
	 * @param int $user_id User ID being updated.
7477
	 */
7478
	public static function user_meta_cleanup( $user_id ) {
7479
		$meta_keys = array(
7480
			// AtD removed from Jetpack 7.3
7481
			'AtD_options',
7482
			'AtD_check_when',
7483
			'AtD_guess_lang',
7484
			'AtD_ignored_phrases',
7485
		);
7486
7487
		foreach ( $meta_keys as $meta_key ) {
7488
			if ( get_user_meta( $user_id, $meta_key ) ) {
7489
				delete_user_meta( $user_id, $meta_key );
7490
			}
7491
		}
7492
	}
7493
7494
	/**
7495
	 * Checks if a Jetpack site is both active and not in offline mode.
7496
	 *
7497
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7498
	 *
7499
	 * @deprecated 8.8.0
7500
	 *
7501
	 * @return bool True if Jetpack is active and not in offline mode.
7502
	 */
7503
	public static function is_active_and_not_development_mode() {
7504
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7505
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack::is_active() has been deprecated with message: 9.6.0

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...
7506
			return false;
7507
		}
7508
		return true;
7509
	}
7510
7511
	/**
7512
	 * Checks if a Jetpack site is both active and not in offline mode.
7513
	 *
7514
	 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
7515
	 *
7516
	 * @since 8.8.0
7517
	 *
7518
	 * @return bool True if Jetpack is active and not in offline mode.
7519
	 */
7520
	public static function is_active_and_not_offline_mode() {
7521
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
7522
			return false;
7523
		}
7524
		return true;
7525
	}
7526
7527
	/**
7528
	 * Returns the list of products that we have available for purchase.
7529
	 */
7530
	public static function get_products_for_purchase() {
7531
		$products = array();
7532
		if ( ! is_multisite() ) {
7533
			$products[] = array(
7534
				'key'               => 'backup',
7535
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7536
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7537
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7538
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7539
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7540
				'options'           => array(
7541
					array(
7542
						'type'        => 'daily',
7543
						'slug'        => 'jetpack-backup-daily',
7544
						'key'         => 'jetpack_backup_daily',
7545
						'name'        => __( 'Daily Backups', 'jetpack' ),
7546
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7547
					),
7548
					array(
7549
						'type'        => 'realtime',
7550
						'slug'        => 'jetpack-backup-realtime',
7551
						'key'         => 'jetpack_backup_realtime',
7552
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7553
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7554
					),
7555
				),
7556
				'default_option'    => 'realtime',
7557
				'show_promotion'    => true,
7558
				'discount_percent'  => 70,
7559
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7560
			);
7561
7562
			$products[] = array(
7563
				'key'               => 'scan',
7564
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7565
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7566
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7567
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7568
				'show_promotion'    => true,
7569
				'discount_percent'  => 30,
7570
				'options'           => array(
7571
					array(
7572
						'type' => 'scan',
7573
						'slug' => 'jetpack-scan',
7574
						'key'  => 'jetpack_scan',
7575
						'name' => __( 'Daily Scan', 'jetpack' ),
7576
					),
7577
				),
7578
				'default_option'    => 'scan',
7579
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7580
			);
7581
		}
7582
7583
		$products[] = array(
7584
			'key'               => 'search',
7585
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7586
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7587
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7588
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7589
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7590
			'options'           => array(
7591
				array(
7592
					'type' => 'search',
7593
					'slug' => 'jetpack-search',
7594
					'key'  => 'jetpack_search',
7595
					'name' => __( 'Search', 'jetpack' ),
7596
				),
7597
			),
7598
			'tears'             => array(),
7599
			'default_option'    => 'search',
7600
			'show_promotion'    => false,
7601
			'included_in_plans' => array( 'search-plan' ),
7602
		);
7603
7604
		$products[] = array(
7605
			'key'               => 'anti-spam',
7606
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7607
			'short_description' => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
7608
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7609
			'description'       => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
7610
			'options'           => array(
7611
				array(
7612
					'type' => 'anti-spam',
7613
					'slug' => 'jetpack-anti-spam',
7614
					'key'  => 'jetpack_anti_spam',
7615
					'name' => __( 'Anti-Spam', 'jetpack' ),
7616
				),
7617
			),
7618
			'default_option'    => 'anti-spam',
7619
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7620
		);
7621
7622
		return $products;
7623
	}
7624
}
7625