Completed
Push — feature/jetpack-packages-2 ( 256561...6d51bf )
by
unknown
706:29 queued 699:24
created

Jetpack   F

Complexity

Total Complexity 1109

Size/Duplication

Total Lines 7091
Duplicated Lines 2.81 %

Coupling/Cohesion

Components 5
Dependencies 31

Importance

Changes 0
Metric Value
dl 199
loc 7091
rs 0.8
c 0
b 0
f 0
wmc 1109
lcom 5
cbo 31

245 Methods

Rating   Name   Duplication   Size   Complexity  
D get_module() 12 91 11
B get_file_data() 0 28 6
A translate_module_tag() 0 3 1
A admin_body_class() 0 8 2
A add_jetpack_pagestyles() 0 3 1
A unlink_user() 0 31 5
B try_registration() 0 28 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() 5 15 4
A admin_banner_styles() 0 21 4
A plugin_action_links() 0 15 4
A is_development_mode() 0 21 3
A is_onboarding() 0 3 1
A sync_idc_optin() 0 18 3
B maybe_min_asset() 0 42 8
A set_suffix_on_min() 0 16 5
C maybe_inline_style() 0 50 13
A load_view() 0 11 2
A jetpack_user_col_style() 0 17 3
B is_akismet_active() 0 35 9
A is_function_in_backtrace() 0 23 5
A get_file_url_for_environment() 0 7 3
A is_rewind_enabled() 0 19 6
A get_calypso_env() 0 15 5
A jetpack_tos_agreed() 0 3 2
A handle_post_authorization_actions() 0 29 4
A show_backups_ui() 0 10 2
A prepare_manage_jetpack_notice() 0 3 1
A manage_activate_screen() 0 3 1
A admin_jetpack_manage_notice() 0 3 1
A opt_out_jetpack_manage_url() 0 3 1
A opt_in_jetpack_manage_url() 0 3 1
A opt_in_jetpack_manage_notice() 0 3 1
A can_display_jetpack_manage_notice() 0 3 1
A user_meta_cleanup() 0 15 3
A init() 0 9 2
B plugin_upgrade() 0 43 8
A upgrade_on_load() 0 27 5
A update_active_modules() 0 53 3
A delete_active_modules() 0 3 1
F __construct() 0 216 30
A initialize_rest_api_registration_connector() 0 3 1
A add_wpcom_to_allowed_redirect_hosts() 0 3 1
A allow_wpcom_domain() 0 7 2
A point_edit_post_links_to_calypso() 0 28 3
A point_edit_comment_links_to_calypso() 0 8 1
A jetpack_track_last_sync_callback() 0 22 5
A jetpack_connection_banner_callback() 0 10 2
A remove_non_jetpack_xmlrpc_methods() 0 11 3
A alternate_xmlrpc() 0 40 3
B jetpack_admin_ajax_tracks_callback() 0 23 8
C jetpack_jitm_ajax_callback() 18 57 12
A push_stats() 0 5 2
D jetpack_custom_caps() 0 72 21
A require_jetpack_authentication() 0 11 2
A plugin_textdomain() 0 4 1
B register_assets() 10 79 8
C guess_locale_from_lang() 39 39 12
A get_locale() 0 9 2
A devicepx() 0 5 3
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() 0 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() 4 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 8 1
A get_updates() 6 17 6
A get_update_details() 0 8 1
A refresh_update_data() 0 4 1
A refresh_theme_data() 0 3 1
A is_active() 0 3 1
A refresh_active_plan_from_wpcom() 0 4 1
A get_active_plan() 0 4 1
A active_plan_supports() 0 4 1
A development_mode_trigger_text() 0 16 6
A show_development_mode_notice() 11 28 4
A is_development_version() 0 15 1
A is_user_connected() 0 8 3
A get_connected_user_data() 0 24 4
A get_connected_user_email() 14 14 3
A get_master_user_email() 0 7 2
A current_user_is_connection_owner() 0 4 4
A current_user_ip() 0 20 5
A extra_oembed_providers() 0 9 1
A user_role_change() 0 4 1
D load_modules() 6 89 17
A check_rest_api_compat() 0 16 3
A get_active_plugins() 0 16 3
A get_parsed_plugin_data() 0 21 3
A get_parsed_theme_data() 0 22 3
A is_plugin_active() 0 3 1
B check_open_graph() 0 27 7
A check_twitter_tags() 0 24 5
A submit_security_report() 0 3 1
A get_option_names() 0 3 1
A get_option() 0 3 1
A update_option() 0 4 1
A update_options() 0 4 1
A delete_option() 0 4 1
A update_user_token() 0 14 3
B glob_php() 0 29 7
C activate_new_modules() 6 58 11
C get_available_modules() 0 57 13
B get_default_modules() 0 31 6
B handle_deprecated_modules() 0 26 8
B filter_default_modules() 0 24 6
A get_module_slug() 0 3 1
A get_module_path() 0 11 1
A get_i18n_data_json() 0 25 4
A setup_wp_i18n_locale_data() 0 10 2
A get_translated_modules() 0 13 4
B get_active_modules() 0 32 7
A is_module_active() 0 3 1
A is_module() 0 3 2
A catch_errors() 0 13 2
A catch_errors_on_shutdown() 0 3 1
A alias_directories() 0 8 1
F activate_default_modules() 21 138 22
D activate_module() 0 87 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 17 3
C get_activation_source() 0 49 14
A do_version_bump() 0 5 2
A plugin_initialize() 6 17 3
A plugin_deactivation() 0 9 2
B disconnect() 0 60 6
B admin_init() 0 43 11
B throw_error_on_activate_plugin() 0 24 7
A intercept_plugin_error_scrape_init() 0 3 1
A intercept_plugin_error_scrape() 0 11 4
A add_remote_request_handlers() 0 4 1
B remote_request_handlers() 0 40 7
F upload_handler() 0 122 24
A admin_help() 0 41 2
A admin_menu_css() 0 3 1
A admin_menu_order() 0 3 1
A jetpack_menu_order() 15 15 4
F admin_page_load() 16 266 55
B admin_notices() 0 92 7
A stat() 0 5 2
B do_stats() 0 15 7
A do_server_side_stat() 0 10 3
A build_stats_url() 0 20 1
A translate_current_user_to_role() 0 9 4
A translate_user_to_role() 0 9 4
A translate_role_to_cap() 0 7 2
A sign_role() 0 16 5
F build_connect_url() 0 127 19
A get_assumed_site_creation_date() 0 27 2
A apply_activation_source_to_args() 0 11 3
A build_reconnect_url() 0 4 2
A admin_url() 0 5 1
A nonce_url_no_esc() 0 4 1
B dismiss_jetpack_notice() 0 32 8
A sort_modules() 0 6 3
A ajax_recheck_ssl() 0 8 1
A api_url() 0 3 1
A fix_url_for_bad_hosts() 0 16 4
A create_onboarding_token() 0 8 2
A invalidate_onboarding_token() 0 3 1
A validate_onboarding_token_action() 0 18 3
B permit_ssl() 0 42 11
A alert_auto_ssl_fail() 0 49 2
A xmlrpc_api_url() 0 4 1
A connection() 0 3 1
A generate_secrets() 0 7 2
A get_secrets() 0 13 3
A delete_secrets() 0 3 1
A get_remote_query_timeout_limit() 0 4 1
A get_max_execution_time() 0 9 2
A set_min_time_limit() 0 8 2
C validate_remote_register_response() 0 40 13
C register() 10 105 12
A maybe_set_version_option() 0 14 3
A load_xml_rpc_client() 0 4 1
A reset_saved_auth_state() 0 4 1
F verify_xml_rpc_signature() 0 124 37
B authenticate_jetpack() 0 23 6
C wp_rest_authenticate() 0 75 16
A wp_rest_authentication_errors() 0 6 2
A add_nonce() 0 38 3
A xmlrpc_methods() 0 4 1
A public_xmlrpc_methods() 0 6 2
A jetpack_getOptions() 0 40 3
A xmlrpc_options() 0 18 2
A clean_nonces() 0 21 4
D state() 0 50 18
A restate() 0 3 1
B check_privacy() 0 35 6
C xmlrpc_async_call() 0 42 12
A staticize_subdomain() 0 35 4
A login_form_json_api_authorization() 0 9 1
A post_login_form_to_signed_url() 0 13 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 102 22
A login_message_json_api_authorization() 0 6 1
A get_content_width() 0 13 3
A get_cloud_site_options() 0 16 2
A check_identity_crisis() 0 7 4
B is_staging_site() 0 59 10
C validate_sync_error_idc_option() 0 44 13
A normalize_url_protocol_agnostic() 0 10 4
A get_sync_error_idc_option() 0 32 5
B deprecated_hooks() 0 68 6
B absolutize_css_urls() 0 44 9
B implode_frontend_css() 0 57 10
A concat_remove_style_loader_tag() 0 10 4
B jetpack_check_heartbeat_data() 0 53 10
A get_jetpack_options_for_reset() 0 3 1
A build_raw_urls() 0 6 1
B dns_prefetch() 0 17 7
A wp_dashboard_setup() 0 34 5
A get_user_option_meta_box_order_dashboard() 0 25 5
A dashboard_widget() 0 8 1
B dashboard_widget_footer() 0 33 7
A jetpack_icon_user_connected() 0 4 1
A jetpack_show_user_connected_icon() 0 13 3
A is_active_and_not_development_mode() 0 6 3

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\Constants;
4
use Automattic\Jetpack\Tracking\Manager as JetpackTracking;
5
6
/*
7
Options:
8
jetpack_options (array)
9
	An array of options.
10
	@see Jetpack_Options::get_option_names()
11
12
jetpack_register (string)
13
	Temporary verification secrets.
14
15
jetpack_activated (int)
16
	1: the plugin was activated normally
17
	2: the plugin was activated on this site because of a network-wide activation
18
	3: the plugin was auto-installed
19
	4: the plugin was manually disconnected (but is still installed)
20
21
jetpack_active_modules (array)
22
	Array of active module slugs.
23
24
jetpack_do_activate (bool)
25
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
26
*/
27
28
use \Automattic\Jetpack\Connection\Manager as Connection_Manager;
29
use \Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
30
use \Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
31
use \Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
32
33
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
34
require_once( dirname( __FILE__ ) . '/_inc/lib/tracks/client.php' );
35
36
class Jetpack {
37
	public $xmlrpc_server = null;
38
39
	private $xmlrpc_verification = null;
40
	private $rest_authentication_status = null;
41
42
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
43
44
	/**
45
	 * @var array The handles of styles that are concatenated into jetpack.css.
46
	 *
47
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
48
	 */
49
	public $concatenated_style_handles = array(
50
		'jetpack-carousel',
51
		'grunion.css',
52
		'the-neverending-homepage',
53
		'jetpack_likes',
54
		'jetpack_related-posts',
55
		'sharedaddy',
56
		'jetpack-slideshow',
57
		'presentations',
58
		'quiz',
59
		'jetpack-subscriptions',
60
		'jetpack-responsive-videos-style',
61
		'jetpack-social-menu',
62
		'tiled-gallery',
63
		'jetpack_display_posts_widget',
64
		'gravatar-profile-widget',
65
		'goodreads-widget',
66
		'jetpack_social_media_icons_widget',
67
		'jetpack-top-posts-widget',
68
		'jetpack_image_widget',
69
		'jetpack-my-community-widget',
70
		'jetpack-authors-widget',
71
		'wordads',
72
		'eu-cookie-law-style',
73
		'flickr-widget-style',
74
		'jetpack-search-widget',
75
		'jetpack-simple-payments-widget-style',
76
		'jetpack-widget-social-icons-styles',
77
	);
78
79
	/**
80
	 * Contains all assets that have had their URL rewritten to minified versions.
81
	 *
82
	 * @var array
83
	 */
84
	static $min_assets = array();
85
86
	public $plugins_to_deactivate = array(
87
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
88
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
89
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
90
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
91
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
92
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
93
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
94
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
95
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
96
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
97
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
98
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
99
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
100
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
101
	);
102
103
	static $capability_translations = array(
104
		'administrator' => 'manage_options',
105
		'editor'        => 'edit_others_posts',
106
		'author'        => 'publish_posts',
107
		'contributor'   => 'edit_posts',
108
		'subscriber'    => 'read',
109
	);
110
111
	/**
112
	 * Map of modules that have conflicts with plugins and should not be auto-activated
113
	 * if the plugins are active.  Used by filter_default_modules
114
	 *
115
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
116
	 * change `module-slug` and add this to your plugin:
117
	 *
118
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
119
	 * function my_jetpack_get_default_modules( $modules ) {
120
	 *     return array_diff( $modules, array( 'module-slug' ) );
121
	 * }
122
	 *
123
	 * @var array
124
	 */
125
	private $conflicting_plugins = array(
126
		'comments'          => array(
127
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
128
			'Disqus'                               => 'disqus-comment-system/disqus.php',
129
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
130
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
131
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
132
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
133
		),
134
		'comment-likes' => array(
135
			'Epoch'                                => 'epoch/plugincore.php',
136
		),
137
		'contact-form'      => array(
138
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
139
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
140
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
141
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
142
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
143
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
144
		),
145
		'minileven'         => array(
146
			'WPtouch'                              => 'wptouch/wptouch.php',
147
		),
148
		'latex'             => array(
149
			'LaTeX for WordPress'                  => 'latex/latex.php',
150
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
151
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
152
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
153
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
154
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
155
		),
156
		'protect'           => array(
157
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
158
			'Captcha'                              => 'captcha/captcha.php',
159
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
160
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
161
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
162
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
163
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
164
			'Security-protection'                  => 'security-protection/security-protection.php',
165
			'Login Security'                       => 'login-security/login-security.php',
166
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
167
			'Wordfence Security'                   => 'wordfence/wordfence.php',
168
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
169
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
170
		),
171
		'random-redirect'   => array(
172
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
173
		),
174
		'related-posts'     => array(
175
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
176
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
177
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
178
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
179
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
180
			'outbrain'                             => 'outbrain/outbrain.php',
181
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
182
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
183
		),
184
		'sharedaddy'        => array(
185
			'AddThis'                              => 'addthis/addthis_social_widget.php',
186
			'Add To Any'                           => 'add-to-any/add-to-any.php',
187
			'ShareThis'                            => 'share-this/sharethis.php',
188
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
189
		),
190
		'seo-tools' => array(
191
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
192
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
193
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
194
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
195
			'The SEO Framework'                    => 'autodescription/autodescription.php',
196
		),
197
		'verification-tools' => array(
198
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
199
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
200
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
201
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
202
			'The SEO Framework'                    => 'autodescription/autodescription.php',
203
		),
204
		'widget-visibility' => array(
205
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
206
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
207
		),
208
		'sitemaps' => array(
209
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
210
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
211
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
212
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
213
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
214
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
215
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
216
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
217
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
218
			'The SEO Framework'                    => 'autodescription/autodescription.php',
219
			'Sitemap'                              => 'sitemap/sitemap.php',
220
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
221
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
222
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
223
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
224
		),
225
		'lazy-images' => array(
226
			'Lazy Load'              => 'lazy-load/lazy-load.php',
227
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
228
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
229
		),
230
	);
231
232
	/**
233
	 * Plugins for which we turn off our Facebook OG Tags implementation.
234
	 *
235
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
236
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
237
	 *
238
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
239
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
240
	 */
241
	private $open_graph_conflicting_plugins = array(
242
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
243
		                                                         // 2 Click Social Media Buttons
244
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
245
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
246
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
247
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
248
		                                                         // Open Graph Meta Tags by Heateor
249
		'facebook/facebook.php',                                 // Facebook (official plugin)
250
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
251
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
252
		                                                         // Facebook Featured Image & OG Meta Tags
253
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
254
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
255
		                                                         // Facebook Open Graph Meta Tags for WordPress
256
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
257
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
258
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
259
		                                                         // Fedmich's Facebook Open Graph Meta
260
		'network-publisher/networkpub.php',                      // Network Publisher
261
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
262
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
263
		                                                         // NextScripts SNAP
264
		'og-tags/og-tags.php',                                   // OG Tags
265
		'opengraph/opengraph.php',                               // Open Graph
266
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
267
		                                                         // Open Graph Protocol Framework
268
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
269
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
270
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
271
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
272
		'sharepress/sharepress.php',                             // SharePress
273
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
274
		'social-discussions/social-discussions.php',             // Social Discussions
275
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
276
		'socialize/socialize.php',                               // Socialize
277
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
278
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
279
		                                                         // Tweet, Like, Google +1 and Share
280
		'wordbooker/wordbooker.php',                             // Wordbooker
281
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
282
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
283
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
284
		                                                         // WP Facebook Like Send & Open Graph Meta
285
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
286
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
287
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
288
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
289
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
290
	);
291
292
	/**
293
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
294
	 */
295
	private $twitter_cards_conflicting_plugins = array(
296
	//	'twitter/twitter.php',                       // The official one handles this on its own.
297
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
298
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
299
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
300
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
301
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
302
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
303
		'twitter-cards/twitter-cards.php',           // Twitter Cards
304
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
305
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
306
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
307
	);
308
309
	/**
310
	 * Message to display in admin_notice
311
	 * @var string
312
	 */
313
	public $message = '';
314
315
	/**
316
	 * Error to display in admin_notice
317
	 * @var string
318
	 */
319
	public $error = '';
320
321
	/**
322
	 * Modules that need more privacy description.
323
	 * @var string
324
	 */
325
	public $privacy_checks = '';
326
327
	/**
328
	 * Stats to record once the page loads
329
	 *
330
	 * @var array
331
	 */
332
	public $stats = array();
333
334
	/**
335
	 * Jetpack_Sync object
336
	 */
337
	public $sync;
338
339
	/**
340
	 * Verified data for JSON authorization request
341
	 */
342
	public $json_api_authorization_request = array();
343
344
	/**
345
	 * @var \Automattic\Jetpack\Connection\Manager
346
	 */
347
	protected $connection_manager;
348
349
	/**
350
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
351
	 */
352
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
353
354
	/**
355
	 * Holds the singleton instance of this class
356
	 * @since 2.3.3
357
	 * @var Jetpack
358
	 */
359
	static $instance = false;
360
361
	/**
362
	 * Singleton
363
	 * @static
364
	 */
365
	public static function init() {
366
		if ( ! self::$instance ) {
367
			self::$instance = new Jetpack;
368
369
			self::$instance->plugin_upgrade();
370
		}
371
372
		return self::$instance;
373
	}
374
375
	/**
376
	 * Must never be called statically
377
	 */
378
	function plugin_upgrade() {
379
		if ( Jetpack::is_active() ) {
380
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
381
			if ( JETPACK__VERSION != $version ) {
382
				// Prevent multiple upgrades at once - only a single process should trigger
383
				// an upgrade to avoid stampedes
384
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
385
					return;
386
				}
387
388
				// Set a short lock to prevent multiple instances of the upgrade
389
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
390
391
				// check which active modules actually exist and remove others from active_modules list
392
				$unfiltered_modules = Jetpack::get_active_modules();
393
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
394
				if ( array_diff( $unfiltered_modules, $modules ) ) {
395
					Jetpack::update_active_modules( $modules );
396
				}
397
398
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
399
400
				// Upgrade to 4.3.0
401
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
402
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
403
				}
404
405
				// Make sure Markdown for posts gets turned back on
406
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
407
					update_option( 'wpcom_publish_posts_with_markdown', true );
408
				}
409
410
				if ( did_action( 'wp_loaded' ) ) {
411
					self::upgrade_on_load();
412
				} else {
413
					add_action(
414
						'wp_loaded',
415
						array( __CLASS__, 'upgrade_on_load' )
416
					);
417
				}
418
			}
419
		}
420
	}
421
422
	/**
423
	 * Runs upgrade routines that need to have modules loaded.
424
	 */
425
	static function upgrade_on_load() {
426
427
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
428
		// This can happen in case Jetpack has been just upgraded and is
429
		// being initialized late during the page load. In this case we wait
430
		// until the next proper admin page load with Jetpack active.
431
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
432
			delete_transient( self::$plugin_upgrade_lock_key );
433
434
			return;
435
		}
436
437
		Jetpack::maybe_set_version_option();
438
439
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
440
			Jetpack_Widget_Conditions::migrate_post_type_rules();
441
		}
442
443
		if (
444
			class_exists( 'Jetpack_Sitemap_Manager' )
445
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
446
		) {
447
			do_action( 'jetpack_sitemaps_purge_data' );
448
		}
449
450
		delete_transient( self::$plugin_upgrade_lock_key );
451
	}
452
453
	/**
454
	 * Saves all the currently active modules to options.
455
	 * Also fires Action hooks for each newly activated and deactivated module.
456
	 *
457
	 * @param $modules Array Array of active modules to be saved in options.
458
	 *
459
	 * @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...
460
	 */
461
	static function update_active_modules( $modules ) {
462
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
463
		$active_modules       = Jetpack::get_active_modules();
464
		$new_active_modules   = array_diff( $modules, $current_modules );
465
		$new_inactive_modules = array_diff( $active_modules, $modules );
466
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
467
		$reindexed_modules    = array_values( $new_current_modules );
468
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
469
470
		foreach ( $new_active_modules as $module ) {
471
			/**
472
			 * Fires when a specific module is activated.
473
			 *
474
			 * @since 1.9.0
475
			 *
476
			 * @param string $module Module slug.
477
			 * @param boolean $success whether the module was activated. @since 4.2
478
			 */
479
			do_action( 'jetpack_activate_module', $module, $success );
480
			/**
481
			 * Fires when a module is activated.
482
			 * The dynamic part of the filter, $module, is the module slug.
483
			 *
484
			 * @since 1.9.0
485
			 *
486
			 * @param string $module Module slug.
487
			 */
488
			do_action( "jetpack_activate_module_$module", $module );
489
		}
490
491
		foreach ( $new_inactive_modules as $module ) {
492
			/**
493
			 * Fired after a module has been deactivated.
494
			 *
495
			 * @since 4.2.0
496
			 *
497
			 * @param string $module Module slug.
498
			 * @param boolean $success whether the module was deactivated.
499
			 */
500
			do_action( 'jetpack_deactivate_module', $module, $success );
501
			/**
502
			 * Fires when a module is deactivated.
503
			 * The dynamic part of the filter, $module, is the module slug.
504
			 *
505
			 * @since 1.9.0
506
			 *
507
			 * @param string $module Module slug.
508
			 */
509
			do_action( "jetpack_deactivate_module_$module", $module );
510
		}
511
512
		return $success;
513
	}
514
515
	static function delete_active_modules() {
516
		self::update_active_modules( array() );
517
	}
518
519
	/**
520
	 * Constructor.  Initializes WordPress hooks
521
	 */
522
	private function __construct() {
523
		/*
524
		 * Check for and alert any deprecated hooks
525
		 */
526
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
527
528
		/*
529
		 * Enable enhanced handling of previewing sites in Calypso
530
		 */
531
		if ( Jetpack::is_active() ) {
532
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
533
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
534
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
535
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
536
		}
537
538
		/*
539
		 * Load things that should only be in Network Admin.
540
		 *
541
		 * For now blow away everything else until a more full
542
		 * understanding of what is needed at the network level is
543
		 * available
544
		 */
545
		if ( is_multisite() ) {
546
			Jetpack_Network::init();
547
		}
548
549
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
550
			return function() {
551
				return wp_generate_password( 32, false );
552
			};
553
		} );
554
555
		$this->connection_manager = new Connection_Manager( );
556
557
		/**
558
		 * Prepare Gutenberg Editor functionality
559
		 */
560
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
561
		Jetpack_Gutenberg::init();
562
		Jetpack_Gutenberg::load_independent_blocks();
563
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
564
565
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
566
567
		// Unlink user before deleting the user from .com
568
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
569
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
570
571
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
572
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
573
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
574
				define( 'XMLRPC_REQUEST', true );
575
			}
576
577
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
578
579
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
580
		}
581
582
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
583
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
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...
584
585
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
586
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
587
588
			$this->require_jetpack_authentication();
589
590
			if ( Jetpack::is_active() ) {
591
				// Hack to preserve $HTTP_RAW_POST_DATA
592
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
593
594
				$signed = $this->verify_xml_rpc_signature();
595
				if ( $signed && ! is_wp_error( $signed ) ) {
596
					// The actual API methods.
597
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
598
				} else {
599
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
600
					// active Jetpack connection, so that additional users can link their account.
601
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
602
				}
603
			} else {
604
				new XMLRPC_Connector( $this->connection_manager );
605
606
				// The bootstrap API methods.
607
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
608
				$signed = $this->verify_xml_rpc_signature();
609
				if ( $signed && ! is_wp_error( $signed ) ) {
610
					// the jetpack Provision method is available for blog-token-signed requests
611
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
612
				}
613
			}
614
615
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
616
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
617
		} elseif (
618
			is_admin() &&
619
			isset( $_POST['action'] ) && (
620
				'jetpack_upload_file' == $_POST['action'] ||
621
				'jetpack_update_file' == $_POST['action']
622
			)
623
		) {
624
			$this->require_jetpack_authentication();
625
			$this->add_remote_request_handlers();
626
		} else {
627
			if ( Jetpack::is_active() ) {
628
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
629
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
630
			} else {
631
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
632
			}
633
		}
634
635
		if ( Jetpack::is_active() ) {
636
			Jetpack_Heartbeat::init();
637
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
638
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
639
				Jetpack_Search_Performance_Logger::init();
640
			}
641
		}
642
643
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
644
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
645
646
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
647
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
648
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
649
		}
650
651
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
652
653
		add_action( 'admin_init', array( $this, 'admin_init' ) );
654
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
655
656
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
657
658
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
659
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
660
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
661
662
		// returns HTTPS support status
663
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
664
665
		// JITM AJAX callback function
666
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
667
668
		// Universal ajax callback for all tracking events triggered via js
669
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
670
671
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
672
673
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
674
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
675
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
676
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
677
678
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
679
680
		/**
681
		 * These actions run checks to load additional files.
682
		 * They check for external files or plugins, so they need to run as late as possible.
683
		 */
684
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
685
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
686
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
687
688
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
689
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
690
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
691
692
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
693
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
694
695
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
696
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
697
698
		// A filter to control all just in time messages
699
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
700
701
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
702
703
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
704
		// We should make sure to only do this for front end links.
705
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
706
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
707
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
708
709
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
710
			//so they point moderation links on emails to Calypso
711
			jetpack_require_lib( 'functions.wp-notify' );
712
		}
713
714
		// Update the Jetpack plan from API on heartbeats
715
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
716
717
		/**
718
		 * This is the hack to concatenate all css files into one.
719
		 * For description and reasoning see the implode_frontend_css method
720
		 *
721
		 * Super late priority so we catch all the registered styles
722
		 */
723
		if( !is_admin() ) {
724
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
725
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
726
		}
727
728
		/**
729
		 * These are sync actions that we need to keep track of for jitms
730
		 */
731
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
732
733
		// Actually push the stats on shutdown.
734
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
735
			add_action( 'shutdown', array( $this, 'push_stats' ) );
736
		}
737
	}
738
739
	function initialize_rest_api_registration_connector() {
740
		new REST_Connector( $this->connection_manager );
741
	}
742
743
	/**
744
	 * This is ported over from the manage module, which has been deprecated and baked in here.
745
	 *
746
	 * @param $domains
747
	 */
748
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
749
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
750
	}
751
752
	/**
753
	 * Return $domains, with 'wordpress.com' appended.
754
	 * This is ported over from the manage module, which has been deprecated and baked in here.
755
	 *
756
	 * @param $domains
757
	 * @return array
758
	 */
759
	function allow_wpcom_domain( $domains ) {
760
		if ( empty( $domains ) ) {
761
			$domains = array();
762
		}
763
		$domains[] = 'wordpress.com';
764
		return array_unique( $domains );
765
	}
766
767
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
768
		$post = get_post( $post_id );
769
770
		if ( empty( $post ) ) {
771
			return $default_url;
772
		}
773
774
		$post_type = $post->post_type;
775
776
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
777
		// https://en.support.wordpress.com/custom-post-types/
778
		$allowed_post_types = array(
779
			'post' => 'post',
780
			'page' => 'page',
781
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
782
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
783
		);
784
785
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
786
			return $default_url;
787
		}
788
789
		$path_prefix = $allowed_post_types[ $post_type ];
790
791
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
792
793
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
794
	}
795
796
	function point_edit_comment_links_to_calypso( $url ) {
797
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
798
		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...
799
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
800
			Jetpack::build_raw_urls( get_home_url() ),
801
			$query_args['amp;c']
802
		) );
803
	}
804
805
	function jetpack_track_last_sync_callback( $params ) {
806
		/**
807
		 * Filter to turn off jitm caching
808
		 *
809
		 * @since 5.4.0
810
		 *
811
		 * @param bool false Whether to cache just in time messages
812
		 */
813
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
814
			return $params;
815
		}
816
817
		if ( is_array( $params ) && isset( $params[0] ) ) {
818
			$option = $params[0];
819
			if ( 'active_plugins' === $option ) {
820
				// use the cache if we can, but not terribly important if it gets evicted
821
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
822
			}
823
		}
824
825
		return $params;
826
	}
827
828
	function jetpack_connection_banner_callback() {
829
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
830
831
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
832
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
833
			wp_send_json_success();
834
		}
835
836
		wp_die();
837
	}
838
839
	/**
840
	 * Removes all XML-RPC methods that are not `jetpack.*`.
841
	 * Only used in our alternate XML-RPC endpoint, where we want to
842
	 * ensure that Core and other plugins' methods are not exposed.
843
	 *
844
	 * @param array $methods
845
	 * @return array filtered $methods
846
	 */
847
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
848
		$jetpack_methods = array();
849
850
		foreach ( $methods as $method => $callback ) {
851
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
852
				$jetpack_methods[ $method ] = $callback;
853
			}
854
		}
855
856
		return $jetpack_methods;
857
	}
858
859
	/**
860
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
861
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
862
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
863
	 * which is accessible via a different URI. Most of the below is copied directly
864
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
865
	 */
866
	function alternate_xmlrpc() {
867
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
868
		global $HTTP_RAW_POST_DATA;
869
870
		// Some browser-embedded clients send cookies. We don't want them.
871
		$_COOKIE = array();
872
873
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
874
		// but we can do it ourself.
875
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
876
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
877
		}
878
879
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
880
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
881
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
882
		}
883
884
		// phpcs:enable
885
886
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
887
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
888
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
889
890
		/**
891
		 * Filters the class used for handling XML-RPC requests.
892
		 *
893
		 * @since 3.1.0
894
		 *
895
		 * @param string $class The name of the XML-RPC server class.
896
		 */
897
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
898
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
899
900
		// Fire off the request
901
		nocache_headers();
902
		$wp_xmlrpc_server->serve_request();
903
904
		exit;
905
	}
906
907
	function jetpack_admin_ajax_tracks_callback() {
908
		// Check for nonce
909
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
910
			wp_die( 'Permissions check failed.' );
911
		}
912
913
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
914
			wp_die( 'No valid event name or type.' );
915
		}
916
917
		$tracks_data = array();
918
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
919
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
920
				$tracks_data = $_REQUEST['tracksEventProp'];
921
			} else {
922
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
923
			}
924
		}
925
926
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
927
		wp_send_json_success();
928
		wp_die();
929
	}
930
931
	/**
932
	 * The callback for the JITM ajax requests.
933
	 */
934
	function jetpack_jitm_ajax_callback() {
935
		// Check for nonce
936
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
937
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
938
		}
939
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
940
			$module_slug = $_REQUEST['jitmModule'];
941
			Jetpack::log( 'activate', $module_slug );
942
			Jetpack::activate_module( $module_slug, false, false );
943
			Jetpack::state( 'message', 'no_message' );
944
945
			//A Jetpack module is being activated through a JITM, track it
946
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
947
			$this->do_stats( 'server_side' );
948
949
			wp_send_json_success();
950
		}
951
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
952
			// get the hide_jitm options array
953
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
954
			$module_slug = $_REQUEST['jitmModule'];
955
956
			if( ! $jetpack_hide_jitm ) {
957
				$jetpack_hide_jitm = array(
958
					$module_slug => 'hide'
959
				);
960
			} else {
961
				$jetpack_hide_jitm[$module_slug] = 'hide';
962
			}
963
964
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
965
966
			//jitm is being dismissed forever, track it
967
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
968
			$this->do_stats( 'server_side' );
969
970
			wp_send_json_success();
971
		}
972 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
973
			$module_slug = $_REQUEST['jitmModule'];
974
975
			// User went to WordPress.com, track this
976
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
977
			$this->do_stats( 'server_side' );
978
979
			wp_send_json_success();
980
		}
981 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
982
			$track = $_REQUEST['jitmModule'];
983
984
			// User is viewing JITM, track it.
985
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
986
			$this->do_stats( 'server_side' );
987
988
			wp_send_json_success();
989
		}
990
	}
991
992
	/**
993
	 * If there are any stats that need to be pushed, but haven't been, push them now.
994
	 */
995
	function push_stats() {
996
		if ( ! empty( $this->stats ) ) {
997
			$this->do_stats( 'server_side' );
998
		}
999
	}
1000
1001
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1002
		switch( $cap ) {
1003
			case 'jetpack_connect' :
1004
			case 'jetpack_reconnect' :
1005
				if ( Jetpack::is_development_mode() ) {
1006
					$caps = array( 'do_not_allow' );
1007
					break;
1008
				}
1009
				/**
1010
				 * Pass through. If it's not development mode, these should match disconnect.
1011
				 * Let users disconnect if it's development mode, just in case things glitch.
1012
				 */
1013
			case 'jetpack_disconnect' :
1014
				/**
1015
				 * In multisite, can individual site admins manage their own connection?
1016
				 *
1017
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1018
				 */
1019
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1020
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1021
						/**
1022
						 * We need to update the option name -- it's terribly unclear which
1023
						 * direction the override goes.
1024
						 *
1025
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1026
						 */
1027
						$caps = array( 'do_not_allow' );
1028
						break;
1029
					}
1030
				}
1031
1032
				$caps = array( 'manage_options' );
1033
				break;
1034
			case 'jetpack_manage_modules' :
1035
			case 'jetpack_activate_modules' :
1036
			case 'jetpack_deactivate_modules' :
1037
				$caps = array( 'manage_options' );
1038
				break;
1039
			case 'jetpack_configure_modules' :
1040
				$caps = array( 'manage_options' );
1041
				break;
1042
			case 'jetpack_manage_autoupdates' :
1043
				$caps = array(
1044
					'manage_options',
1045
					'update_plugins',
1046
				);
1047
				break;
1048
			case 'jetpack_network_admin_page':
1049
			case 'jetpack_network_settings_page':
1050
				$caps = array( 'manage_network_plugins' );
1051
				break;
1052
			case 'jetpack_network_sites_page':
1053
				$caps = array( 'manage_sites' );
1054
				break;
1055
			case 'jetpack_admin_page' :
1056
				if ( Jetpack::is_development_mode() ) {
1057
					$caps = array( 'manage_options' );
1058
					break;
1059
				} else {
1060
					$caps = array( 'read' );
1061
				}
1062
				break;
1063
			case 'jetpack_connect_user' :
1064
				if ( Jetpack::is_development_mode() ) {
1065
					$caps = array( 'do_not_allow' );
1066
					break;
1067
				}
1068
				$caps = array( 'read' );
1069
				break;
1070
		}
1071
		return $caps;
1072
	}
1073
1074
	function require_jetpack_authentication() {
1075
		// Don't let anyone authenticate
1076
		$_COOKIE = array();
1077
		remove_all_filters( 'authenticate' );
1078
		remove_all_actions( 'wp_login_failed' );
1079
1080
		if ( Jetpack::is_active() ) {
1081
			// Allow Jetpack authentication
1082
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1083
		}
1084
	}
1085
1086
	/**
1087
	 * Load language files
1088
	 * @action plugins_loaded
1089
	 */
1090
	public static function plugin_textdomain() {
1091
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1092
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1093
	}
1094
1095
	/**
1096
	 * Register assets for use in various modules and the Jetpack admin page.
1097
	 *
1098
	 * @uses wp_script_is, wp_register_script, plugins_url
1099
	 * @action wp_loaded
1100
	 * @return null
1101
	 */
1102
	public function register_assets() {
1103
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1104
			wp_register_script(
1105
				'spin',
1106
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1107
				false,
1108
				'1.3'
1109
			);
1110
		}
1111
1112
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1113
			wp_register_script(
1114
				'jquery.spin',
1115
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1116
				array( 'jquery', 'spin' ),
1117
				'1.3'
1118
			);
1119
		}
1120
1121 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1122
			wp_register_script(
1123
				'jetpack-gallery-settings',
1124
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1125
				array( 'media-views' ),
1126
				'20121225'
1127
			);
1128
		}
1129
1130
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1131
			wp_register_script(
1132
				'jetpack-twitter-timeline',
1133
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1134
				array( 'jquery' ),
1135
				'4.0.0',
1136
				true
1137
			);
1138
		}
1139
1140
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1141
			wp_register_script(
1142
				'jetpack-facebook-embed',
1143
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1144
				array( 'jquery' ),
1145
				null,
1146
				true
1147
			);
1148
1149
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1150
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1151
			if ( ! is_numeric( $fb_app_id ) ) {
1152
				$fb_app_id = '';
1153
			}
1154
			wp_localize_script(
1155
				'jetpack-facebook-embed',
1156
				'jpfbembed',
1157
				array(
1158
					'appid' => $fb_app_id,
1159
					'locale' => $this->get_locale(),
1160
				)
1161
			);
1162
		}
1163
1164
		/**
1165
		 * As jetpack_register_genericons is by default fired off a hook,
1166
		 * the hook may have already fired by this point.
1167
		 * So, let's just trigger it manually.
1168
		 */
1169
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1170
		jetpack_register_genericons();
1171
1172
		/**
1173
		 * Register the social logos
1174
		 */
1175
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1176
		jetpack_register_social_logos();
1177
1178 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1179
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1180
	}
1181
1182
	/**
1183
	 * Guess locale from language code.
1184
	 *
1185
	 * @param string $lang Language code.
1186
	 * @return string|bool
1187
	 */
1188 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1189
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1190
			return 'en_US';
1191
		}
1192
1193
		if ( ! class_exists( 'GP_Locales' ) ) {
1194
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1195
				return false;
1196
			}
1197
1198
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1199
		}
1200
1201
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1202
			// WP.com: get_locale() returns 'it'
1203
			$locale = GP_Locales::by_slug( $lang );
1204
		} else {
1205
			// Jetpack: get_locale() returns 'it_IT';
1206
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1207
		}
1208
1209
		if ( ! $locale ) {
1210
			return false;
1211
		}
1212
1213
		if ( empty( $locale->facebook_locale ) ) {
1214
			if ( empty( $locale->wp_locale ) ) {
1215
				return false;
1216
			} else {
1217
				// Facebook SDK is smart enough to fall back to en_US if a
1218
				// locale isn't supported. Since supported Facebook locales
1219
				// can fall out of sync, we'll attempt to use the known
1220
				// wp_locale value and rely on said fallback.
1221
				return $locale->wp_locale;
1222
			}
1223
		}
1224
1225
		return $locale->facebook_locale;
1226
	}
1227
1228
	/**
1229
	 * Get the locale.
1230
	 *
1231
	 * @return string|bool
1232
	 */
1233
	function get_locale() {
1234
		$locale = $this->guess_locale_from_lang( get_locale() );
1235
1236
		if ( ! $locale ) {
1237
			$locale = 'en_US';
1238
		}
1239
1240
		return $locale;
1241
	}
1242
1243
	/**
1244
	 * Device Pixels support
1245
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1246
	 */
1247
	function devicepx() {
1248
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1249
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1250
		}
1251
	}
1252
1253
	/**
1254
	 * Return the network_site_url so that .com knows what network this site is a part of.
1255
	 * @param  bool $option
1256
	 * @return string
1257
	 */
1258
	public function jetpack_main_network_site_option( $option ) {
1259
		return network_site_url();
1260
	}
1261
	/**
1262
	 * Network Name.
1263
	 */
1264
	static function network_name( $option = null ) {
1265
		global $current_site;
1266
		return $current_site->site_name;
1267
	}
1268
	/**
1269
	 * Does the network allow new user and site registrations.
1270
	 * @return string
1271
	 */
1272
	static function network_allow_new_registrations( $option = null ) {
1273
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1274
	}
1275
	/**
1276
	 * Does the network allow admins to add new users.
1277
	 * @return boolian
1278
	 */
1279
	static function network_add_new_users( $option = null ) {
1280
		return (bool) get_site_option( 'add_new_users' );
1281
	}
1282
	/**
1283
	 * File upload psace left per site in MB.
1284
	 *  -1 means NO LIMIT.
1285
	 * @return number
1286
	 */
1287
	static function network_site_upload_space( $option = null ) {
1288
		// value in MB
1289
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1290
	}
1291
1292
	/**
1293
	 * Network allowed file types.
1294
	 * @return string
1295
	 */
1296
	static function network_upload_file_types( $option = null ) {
1297
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1298
	}
1299
1300
	/**
1301
	 * Maximum file upload size set by the network.
1302
	 * @return number
1303
	 */
1304
	static function network_max_upload_file_size( $option = null ) {
1305
		// value in KB
1306
		return get_site_option( 'fileupload_maxk', 300 );
1307
	}
1308
1309
	/**
1310
	 * Lets us know if a site allows admins to manage the network.
1311
	 * @return array
1312
	 */
1313
	static function network_enable_administration_menus( $option = null ) {
1314
		return get_site_option( 'menu_items' );
1315
	}
1316
1317
	/**
1318
	 * If a user has been promoted to or demoted from admin, we need to clear the
1319
	 * jetpack_other_linked_admins transient.
1320
	 *
1321
	 * @since 4.3.2
1322
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1323
	 *
1324
	 * @param int    $user_id   The user ID whose role changed.
1325
	 * @param string $role      The new role.
1326
	 * @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...
1327
	 */
1328
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1329
		if ( 'administrator' == $role
1330
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1331
			|| is_null( $old_roles )
1332
		) {
1333
			delete_transient( 'jetpack_other_linked_admins' );
1334
		}
1335
	}
1336
1337
	/**
1338
	 * Checks to see if there are any other users available to become primary
1339
	 * Users must both:
1340
	 * - Be linked to wpcom
1341
	 * - Be an admin
1342
	 *
1343
	 * @return mixed False if no other users are linked, Int if there are.
1344
	 */
1345
	static function get_other_linked_admins() {
1346
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1347
1348
		if ( false === $other_linked_users ) {
1349
			$admins = get_users( array( 'role' => 'administrator' ) );
1350
			if ( count( $admins ) > 1 ) {
1351
				$available = array();
1352
				foreach ( $admins as $admin ) {
1353
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1354
						$available[] = $admin->ID;
1355
					}
1356
				}
1357
1358
				$count_connected_admins = count( $available );
1359
				if ( count( $available ) > 1 ) {
1360
					$other_linked_users = $count_connected_admins;
1361
				} else {
1362
					$other_linked_users = 0;
1363
				}
1364
			} else {
1365
				$other_linked_users = 0;
1366
			}
1367
1368
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1369
		}
1370
1371
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1372
	}
1373
1374
	/**
1375
	 * Return whether we are dealing with a multi network setup or not.
1376
	 * The reason we are type casting this is because we want to avoid the situation where
1377
	 * the result is false since when is_main_network_option return false it cases
1378
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1379
	 * database which could be set to anything as opposed to what this function returns.
1380
	 * @param  bool  $option
1381
	 *
1382
	 * @return boolean
1383
	 */
1384
	public function is_main_network_option( $option ) {
1385
		// return '1' or ''
1386
		return (string) (bool) Jetpack::is_multi_network();
1387
	}
1388
1389
	/**
1390
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1391
	 *
1392
	 * @param  string  $option
1393
	 * @return boolean
1394
	 */
1395
	public function is_multisite( $option ) {
1396
		return (string) (bool) is_multisite();
1397
	}
1398
1399
	/**
1400
	 * Implemented since there is no core is multi network function
1401
	 * Right now there is no way to tell if we which network is the dominant network on the system
1402
	 *
1403
	 * @since  3.3
1404
	 * @return boolean
1405
	 */
1406
	public static function is_multi_network() {
1407
		global  $wpdb;
1408
1409
		// if we don't have a multi site setup no need to do any more
1410
		if ( ! is_multisite() ) {
1411
			return false;
1412
		}
1413
1414
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1415
		if ( $num_sites > 1 ) {
1416
			return true;
1417
		} else {
1418
			return false;
1419
		}
1420
	}
1421
1422
	/**
1423
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1424
	 * @return null
1425
	 */
1426
	function update_jetpack_main_network_site_option() {
1427
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1428
	}
1429
	/**
1430
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1431
	 *
1432
	 */
1433
	function update_jetpack_network_settings() {
1434
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1435
		// Only sync this info for the main network site.
1436
	}
1437
1438
	/**
1439
	 * Get back if the current site is single user site.
1440
	 *
1441
	 * @return bool
1442
	 */
1443
	public static function is_single_user_site() {
1444
		global $wpdb;
1445
1446 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1447
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1448
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1449
		}
1450
		return 1 === (int) $some_users;
1451
	}
1452
1453
	/**
1454
	 * Returns true if the site has file write access false otherwise.
1455
	 * @return string ( '1' | '0' )
1456
	 **/
1457
	public static function file_system_write_access() {
1458
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1459
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1460
		}
1461
1462
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1463
1464
		$filesystem_method = get_filesystem_method();
1465
		if ( $filesystem_method === 'direct' ) {
1466
			return 1;
1467
		}
1468
1469
		ob_start();
1470
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1471
		ob_end_clean();
1472
		if ( $filesystem_credentials_are_stored ) {
1473
			return 1;
1474
		}
1475
		return 0;
1476
	}
1477
1478
	/**
1479
	 * Finds out if a site is using a version control system.
1480
	 * @return string ( '1' | '0' )
1481
	 **/
1482
	public static function is_version_controlled() {
1483
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1484
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1485
	}
1486
1487
	/**
1488
	 * Determines whether the current theme supports featured images or not.
1489
	 * @return string ( '1' | '0' )
1490
	 */
1491
	public static function featured_images_enabled() {
1492
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1493
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1494
	}
1495
1496
	/**
1497
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1498
	 *
1499
	 * @deprecated 4.7 use get_avatar_url instead.
1500
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1501
	 * @param int $size Size of the avatar image
1502
	 * @param string $default URL to a default image to use if no avatar is available
1503
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1504
	 *
1505
	 * @return array
1506
	 */
1507
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1508
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1509
		return get_avatar_url( $id_or_email, array(
1510
			'size' => $size,
1511
			'default' => $default,
1512
			'force_default' => $force_display,
1513
		) );
1514
	}
1515
1516
	/**
1517
	 * jetpack_updates is saved in the following schema:
1518
	 *
1519
	 * array (
1520
	 *      'plugins'                       => (int) Number of plugin updates available.
1521
	 *      'themes'                        => (int) Number of theme updates available.
1522
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1523
	 *      'translations'                  => (int) Number of translation updates available.
1524
	 *      'total'                         => (int) Total of all available updates.
1525
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1526
	 * )
1527
	 * @return array
1528
	 */
1529
	public static function get_updates() {
1530
		$update_data = wp_get_update_data();
1531
1532
		// Stores the individual update counts as well as the total count.
1533
		if ( isset( $update_data['counts'] ) ) {
1534
			$updates = $update_data['counts'];
1535
		}
1536
1537
		// If we need to update WordPress core, let's find the latest version number.
1538 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1539
			$cur = get_preferred_from_update_core();
1540
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1541
				$updates['wp_update_version'] = $cur->current;
1542
			}
1543
		}
1544
		return isset( $updates ) ? $updates : array();
1545
	}
1546
1547
	public static function get_update_details() {
1548
		$update_details = array(
1549
			'update_core' => get_site_transient( 'update_core' ),
1550
			'update_plugins' => get_site_transient( 'update_plugins' ),
1551
			'update_themes' => get_site_transient( 'update_themes' ),
1552
		);
1553
		return $update_details;
1554
	}
1555
1556
	public static function refresh_update_data() {
1557
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1558
1559
	}
1560
1561
	public static function refresh_theme_data() {
1562
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1563
	}
1564
1565
	/**
1566
	 * Is Jetpack active?
1567
	 */
1568
	public static function is_active() {
1569
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
1570
	}
1571
1572
	/**
1573
	 * Make an API call to WordPress.com for plan status
1574
	 *
1575
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1576
	 *
1577
	 * @return bool True if plan is updated, false if no update
1578
	 */
1579
	public static function refresh_active_plan_from_wpcom() {
1580
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1581
		return Jetpack_Plan::refresh_from_wpcom();
1582
	}
1583
1584
	/**
1585
	 * Get the plan that this Jetpack site is currently using
1586
	 *
1587
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1588
	 * @return array Active Jetpack plan details.
1589
	 */
1590
	public static function get_active_plan() {
1591
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1592
		return Jetpack_Plan::get();
1593
	}
1594
1595
	/**
1596
	 * Determine whether the active plan supports a particular feature
1597
	 *
1598
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1599
	 * @return bool True if plan supports feature, false if not.
1600
	 */
1601
	public static function active_plan_supports( $feature ) {
1602
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1603
		return Jetpack_Plan::supports( $feature );
1604
	}
1605
1606
	/**
1607
	 * Is Jetpack in development (offline) mode?
1608
	 */
1609
	public static function is_development_mode() {
1610
		$development_mode = false;
1611
1612
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1613
			$development_mode = JETPACK_DEV_DEBUG;
1614
		} elseif ( $site_url = site_url() ) {
1615
			$development_mode = false === strpos( $site_url, '.' );
1616
		}
1617
1618
		/**
1619
		 * Filters Jetpack's development mode.
1620
		 *
1621
		 * @see https://jetpack.com/support/development-mode/
1622
		 *
1623
		 * @since 2.2.1
1624
		 *
1625
		 * @param bool $development_mode Is Jetpack's development mode active.
1626
		 */
1627
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1628
		return $development_mode;
1629
	}
1630
1631
	/**
1632
	 * Whether the site is currently onboarding or not.
1633
	 * A site is considered as being onboarded if it currently has an onboarding token.
1634
	 *
1635
	 * @since 5.8
1636
	 *
1637
	 * @access public
1638
	 * @static
1639
	 *
1640
	 * @return bool True if the site is currently onboarding, false otherwise
1641
	 */
1642
	public static function is_onboarding() {
1643
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1644
	}
1645
1646
	/**
1647
	 * Determines reason for Jetpack development mode.
1648
	 */
1649
	public static function development_mode_trigger_text() {
1650
		if ( ! Jetpack::is_development_mode() ) {
1651
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1652
		}
1653
1654
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1655
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1656
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1657
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1658
		} else {
1659
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1660
		}
1661
1662
		return $notice;
1663
1664
	}
1665
	/**
1666
	* Get Jetpack development mode notice text and notice class.
1667
	*
1668
	* Mirrors the checks made in Jetpack::is_development_mode
1669
	*
1670
	*/
1671
	public static function show_development_mode_notice() {
1672 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1673
			$notice = sprintf(
1674
			/* translators: %s is a URL */
1675
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1676
				'https://jetpack.com/support/development-mode/'
1677
			);
1678
1679
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1680
1681
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1682
		}
1683
1684
		// Throw up a notice if using a development version and as for feedback.
1685
		if ( Jetpack::is_development_version() ) {
1686
			/* translators: %s is a URL */
1687
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), 'https://jetpack.com/contact-support/beta-group/' );
1688
1689
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1690
		}
1691
		// Throw up a notice if using staging mode
1692
		if ( Jetpack::is_staging_site() ) {
1693
			/* translators: %s is a URL */
1694
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1695
1696
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1697
		}
1698
	}
1699
1700
	/**
1701
	 * Whether Jetpack's version maps to a public release, or a development version.
1702
	 */
1703
	public static function is_development_version() {
1704
		/**
1705
		 * Allows filtering whether this is a development version of Jetpack.
1706
		 *
1707
		 * This filter is especially useful for tests.
1708
		 *
1709
		 * @since 4.3.0
1710
		 *
1711
		 * @param bool $development_version Is this a develoment version of Jetpack?
1712
		 */
1713
		return (bool) apply_filters(
1714
			'jetpack_development_version',
1715
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1716
		);
1717
	}
1718
1719
	/**
1720
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1721
	 */
1722
	public static function is_user_connected( $user_id = false ) {
1723
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1724
		if ( ! $user_id ) {
1725
			return false;
1726
		}
1727
1728
		return (bool) Jetpack_Data::get_access_token( $user_id );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
1729
	}
1730
1731
	/**
1732
	 * Get the wpcom user data of the current|specified connected user.
1733
	 */
1734
	public static function get_connected_user_data( $user_id = null ) {
1735
		if ( ! $user_id ) {
1736
			$user_id = get_current_user_id();
1737
		}
1738
1739
		$transient_key = "jetpack_connected_user_data_$user_id";
1740
1741
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1742
			return $cached_user_data;
1743
		}
1744
1745
		Jetpack::load_xml_rpc_client();
1746
		$xml = new Jetpack_IXR_Client( array(
1747
			'user_id' => $user_id,
1748
		) );
1749
		$xml->query( 'wpcom.getUser' );
1750
		if ( ! $xml->isError() ) {
1751
			$user_data = $xml->getResponse();
1752
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1753
			return $user_data;
1754
		}
1755
1756
		return false;
1757
	}
1758
1759
	/**
1760
	 * Get the wpcom email of the current|specified connected user.
1761
	 */
1762 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1763
		if ( ! $user_id ) {
1764
			$user_id = get_current_user_id();
1765
		}
1766
		Jetpack::load_xml_rpc_client();
1767
		$xml = new Jetpack_IXR_Client( array(
1768
			'user_id' => $user_id,
1769
		) );
1770
		$xml->query( 'wpcom.getUserEmail' );
1771
		if ( ! $xml->isError() ) {
1772
			return $xml->getResponse();
1773
		}
1774
		return false;
1775
	}
1776
1777
	/**
1778
	 * Get the wpcom email of the master user.
1779
	 */
1780
	public static function get_master_user_email() {
1781
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1782
		if ( $master_user_id ) {
1783
			return self::get_connected_user_email( $master_user_id );
1784
		}
1785
		return '';
1786
	}
1787
1788
	function current_user_is_connection_owner() {
1789
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
1790
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1791
	}
1792
1793
	/**
1794
	 * Gets current user IP address.
1795
	 *
1796
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1797
	 *
1798
	 * @return string                  Current user IP address.
1799
	 */
1800
	public static function current_user_ip( $check_all_headers = false ) {
1801
		if ( $check_all_headers ) {
1802
			foreach ( array(
1803
				'HTTP_CF_CONNECTING_IP',
1804
				'HTTP_CLIENT_IP',
1805
				'HTTP_X_FORWARDED_FOR',
1806
				'HTTP_X_FORWARDED',
1807
				'HTTP_X_CLUSTER_CLIENT_IP',
1808
				'HTTP_FORWARDED_FOR',
1809
				'HTTP_FORWARDED',
1810
				'HTTP_VIA',
1811
			) as $key ) {
1812
				if ( ! empty( $_SERVER[ $key ] ) ) {
1813
					return $_SERVER[ $key ];
1814
				}
1815
			}
1816
		}
1817
1818
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1819
	}
1820
1821
	/**
1822
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1823
	 */
1824
	function extra_oembed_providers() {
1825
		// Cloudup: https://dev.cloudup.com/#oembed
1826
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1827
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1828
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1829
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1830
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1831
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1832
	}
1833
1834
	/**
1835
	 * Synchronize connected user role changes
1836
	 */
1837
	function user_role_change( $user_id ) {
1838
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1839
		Jetpack_Sync_Users::user_role_change( $user_id );
1840
	}
1841
1842
	/**
1843
	 * Loads the currently active modules.
1844
	 */
1845
	public static function load_modules() {
1846
		if (
1847
			! self::is_active()
1848
			&& ! self::is_development_mode()
1849
			&& ! self::is_onboarding()
1850
			&& (
1851
				! is_multisite()
1852
				|| ! get_site_option( 'jetpack_protect_active' )
1853
			)
1854
		) {
1855
			return;
1856
		}
1857
1858
		$version = Jetpack_Options::get_option( 'version' );
1859 View Code Duplication
		if ( ! $version ) {
1860
			$version = $old_version = JETPACK__VERSION . ':' . time();
1861
			/** This action is documented in class.jetpack.php */
1862
			do_action( 'updating_jetpack_version', $version, false );
1863
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1864
		}
1865
		list( $version ) = explode( ':', $version );
1866
1867
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1868
1869
		$modules_data = array();
1870
1871
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1872
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1873
			$updated_modules = array();
1874
			foreach ( $modules as $module ) {
1875
				$modules_data[ $module ] = Jetpack::get_module( $module );
1876
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1877
					continue;
1878
				}
1879
1880
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1881
					continue;
1882
				}
1883
1884
				$updated_modules[] = $module;
1885
			}
1886
1887
			$modules = array_diff( $modules, $updated_modules );
1888
		}
1889
1890
		$is_development_mode = Jetpack::is_development_mode();
1891
1892
		foreach ( $modules as $index => $module ) {
1893
			// If we're in dev mode, disable modules requiring a connection
1894
			if ( $is_development_mode ) {
1895
				// Prime the pump if we need to
1896
				if ( empty( $modules_data[ $module ] ) ) {
1897
					$modules_data[ $module ] = Jetpack::get_module( $module );
1898
				}
1899
				// If the module requires a connection, but we're in local mode, don't include it.
1900
				if ( $modules_data[ $module ]['requires_connection'] ) {
1901
					continue;
1902
				}
1903
			}
1904
1905
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1906
				continue;
1907
			}
1908
1909
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1910
				unset( $modules[ $index ] );
1911
				self::update_active_modules( array_values( $modules ) );
1912
				continue;
1913
			}
1914
1915
			/**
1916
			 * Fires when a specific module is loaded.
1917
			 * The dynamic part of the hook, $module, is the module slug.
1918
			 *
1919
			 * @since 1.1.0
1920
			 */
1921
			do_action( 'jetpack_module_loaded_' . $module );
1922
		}
1923
1924
		/**
1925
		 * Fires when all the modules are loaded.
1926
		 *
1927
		 * @since 1.1.0
1928
		 */
1929
		do_action( 'jetpack_modules_loaded' );
1930
1931
		// 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.
1932
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1933
	}
1934
1935
	/**
1936
	 * Check if Jetpack's REST API compat file should be included
1937
	 * @action plugins_loaded
1938
	 * @return null
1939
	 */
1940
	public function check_rest_api_compat() {
1941
		/**
1942
		 * Filters the list of REST API compat files to be included.
1943
		 *
1944
		 * @since 2.2.5
1945
		 *
1946
		 * @param array $args Array of REST API compat files to include.
1947
		 */
1948
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1949
1950
		if ( function_exists( 'bbpress' ) )
1951
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1952
1953
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1954
			require_once $_jetpack_rest_api_compat_include;
1955
	}
1956
1957
	/**
1958
	 * Gets all plugins currently active in values, regardless of whether they're
1959
	 * traditionally activated or network activated.
1960
	 *
1961
	 * @todo Store the result in core's object cache maybe?
1962
	 */
1963
	public static function get_active_plugins() {
1964
		$active_plugins = (array) get_option( 'active_plugins', array() );
1965
1966
		if ( is_multisite() ) {
1967
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1968
			// whereas active_plugins stores them in the values.
1969
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1970
			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...
1971
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1972
			}
1973
		}
1974
1975
		sort( $active_plugins );
1976
1977
		return array_unique( $active_plugins );
1978
	}
1979
1980
	/**
1981
	 * Gets and parses additional plugin data to send with the heartbeat data
1982
	 *
1983
	 * @since 3.8.1
1984
	 *
1985
	 * @return array Array of plugin data
1986
	 */
1987
	public static function get_parsed_plugin_data() {
1988
		if ( ! function_exists( 'get_plugins' ) ) {
1989
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1990
		}
1991
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1992
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1993
		$active_plugins = Jetpack::get_active_plugins();
1994
1995
		$plugins = array();
1996
		foreach ( $all_plugins as $path => $plugin_data ) {
1997
			$plugins[ $path ] = array(
1998
					'is_active' => in_array( $path, $active_plugins ),
1999
					'file'      => $path,
2000
					'name'      => $plugin_data['Name'],
2001
					'version'   => $plugin_data['Version'],
2002
					'author'    => $plugin_data['Author'],
2003
			);
2004
		}
2005
2006
		return $plugins;
2007
	}
2008
2009
	/**
2010
	 * Gets and parses theme data to send with the heartbeat data
2011
	 *
2012
	 * @since 3.8.1
2013
	 *
2014
	 * @return array Array of theme data
2015
	 */
2016
	public static function get_parsed_theme_data() {
2017
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2018
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2019
2020
		$themes = array();
2021
		foreach ( $all_themes as $slug => $theme_data ) {
2022
			$theme_headers = array();
2023
			foreach ( $header_keys as $header_key ) {
2024
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2025
			}
2026
2027
			$themes[ $slug ] = array(
2028
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2029
					'slug' => $slug,
2030
					'theme_root' => $theme_data->get_theme_root_uri(),
2031
					'parent' => $theme_data->parent(),
2032
					'headers' => $theme_headers
2033
			);
2034
		}
2035
2036
		return $themes;
2037
	}
2038
2039
	/**
2040
	 * Checks whether a specific plugin is active.
2041
	 *
2042
	 * We don't want to store these in a static variable, in case
2043
	 * there are switch_to_blog() calls involved.
2044
	 */
2045
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2046
		return in_array( $plugin, self::get_active_plugins() );
2047
	}
2048
2049
	/**
2050
	 * Check if Jetpack's Open Graph tags should be used.
2051
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2052
	 *
2053
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2054
	 * @action plugins_loaded
2055
	 * @return null
2056
	 */
2057
	public function check_open_graph() {
2058
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2059
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2060
		}
2061
2062
		$active_plugins = self::get_active_plugins();
2063
2064
		if ( ! empty( $active_plugins ) ) {
2065
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2066
				if ( in_array( $plugin, $active_plugins ) ) {
2067
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2068
					break;
2069
				}
2070
			}
2071
		}
2072
2073
		/**
2074
		 * Allow the addition of Open Graph Meta Tags to all pages.
2075
		 *
2076
		 * @since 2.0.3
2077
		 *
2078
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2079
		 */
2080
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2081
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2082
		}
2083
	}
2084
2085
	/**
2086
	 * Check if Jetpack's Twitter tags should be used.
2087
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2088
	 *
2089
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2090
	 * @action plugins_loaded
2091
	 * @return null
2092
	 */
2093
	public function check_twitter_tags() {
2094
2095
		$active_plugins = self::get_active_plugins();
2096
2097
		if ( ! empty( $active_plugins ) ) {
2098
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2099
				if ( in_array( $plugin, $active_plugins ) ) {
2100
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2101
					break;
2102
				}
2103
			}
2104
		}
2105
2106
		/**
2107
		 * Allow Twitter Card Meta tags to be disabled.
2108
		 *
2109
		 * @since 2.6.0
2110
		 *
2111
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2112
		 */
2113
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2114
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2115
		}
2116
	}
2117
2118
	/**
2119
	 * Allows plugins to submit security reports.
2120
 	 *
2121
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2122
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2123
	 * @param array   $args         See definitions above
2124
	 */
2125
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2126
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2127
	}
2128
2129
/* Jetpack Options API */
2130
2131
	public static function get_option_names( $type = 'compact' ) {
2132
		return Jetpack_Options::get_option_names( $type );
2133
	}
2134
2135
	/**
2136
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2137
 	 *
2138
	 * @param string $name    Option name
2139
	 * @param mixed  $default (optional)
2140
	 */
2141
	public static function get_option( $name, $default = false ) {
2142
		return Jetpack_Options::get_option( $name, $default );
2143
	}
2144
2145
	/**
2146
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2147
 	 *
2148
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2149
	 * @param string $name  Option name
2150
	 * @param mixed  $value Option value
2151
	 */
2152
	public static function update_option( $name, $value ) {
2153
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2154
		return Jetpack_Options::update_option( $name, $value );
2155
	}
2156
2157
	/**
2158
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2159
 	 *
2160
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2161
	 * @param array $array array( option name => option value, ... )
2162
	 */
2163
	public static function update_options( $array ) {
2164
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2165
		return Jetpack_Options::update_options( $array );
2166
	}
2167
2168
	/**
2169
	 * Deletes the given option.  May be passed multiple option names as an array.
2170
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2171
	 *
2172
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2173
	 * @param string|array $names
2174
	 */
2175
	public static function delete_option( $names ) {
2176
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2177
		return Jetpack_Options::delete_option( $names );
2178
	}
2179
2180
	/**
2181
	 * Enters a user token into the user_tokens option
2182
	 *
2183
	 * @param int $user_id
2184
	 * @param string $token
2185
	 * return bool
2186
	 */
2187
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2188
		// not designed for concurrent updates
2189
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2190
		if ( ! is_array( $user_tokens ) )
2191
			$user_tokens = array();
2192
		$user_tokens[$user_id] = $token;
2193
		if ( $is_master_user ) {
2194
			$master_user = $user_id;
2195
			$options     = compact( 'user_tokens', 'master_user' );
2196
		} else {
2197
			$options = compact( 'user_tokens' );
2198
		}
2199
		return Jetpack_Options::update_options( $options );
2200
	}
2201
2202
	/**
2203
	 * Returns an array of all PHP files in the specified absolute path.
2204
	 * Equivalent to glob( "$absolute_path/*.php" ).
2205
	 *
2206
	 * @param string $absolute_path The absolute path of the directory to search.
2207
	 * @return array Array of absolute paths to the PHP files.
2208
	 */
2209
	public static function glob_php( $absolute_path ) {
2210
		if ( function_exists( 'glob' ) ) {
2211
			return glob( "$absolute_path/*.php" );
2212
		}
2213
2214
		$absolute_path = untrailingslashit( $absolute_path );
2215
		$files = array();
2216
		if ( ! $dir = @opendir( $absolute_path ) ) {
2217
			return $files;
2218
		}
2219
2220
		while ( false !== $file = readdir( $dir ) ) {
2221
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2222
				continue;
2223
			}
2224
2225
			$file = "$absolute_path/$file";
2226
2227
			if ( ! is_file( $file ) ) {
2228
				continue;
2229
			}
2230
2231
			$files[] = $file;
2232
		}
2233
2234
		closedir( $dir );
2235
2236
		return $files;
2237
	}
2238
2239
	public static function activate_new_modules( $redirect = false ) {
2240
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2241
			return;
2242
		}
2243
2244
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2245 View Code Duplication
		if ( ! $jetpack_old_version ) {
2246
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2247
			/** This action is documented in class.jetpack.php */
2248
			do_action( 'updating_jetpack_version', $version, false );
2249
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2250
		}
2251
2252
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2253
2254
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2255
			return;
2256
		}
2257
2258
		$active_modules     = Jetpack::get_active_modules();
2259
		$reactivate_modules = array();
2260
		foreach ( $active_modules as $active_module ) {
2261
			$module = Jetpack::get_module( $active_module );
2262
			if ( ! isset( $module['changed'] ) ) {
2263
				continue;
2264
			}
2265
2266
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2267
				continue;
2268
			}
2269
2270
			$reactivate_modules[] = $active_module;
2271
			Jetpack::deactivate_module( $active_module );
2272
		}
2273
2274
		$new_version = JETPACK__VERSION . ':' . time();
2275
		/** This action is documented in class.jetpack.php */
2276
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2277
		Jetpack_Options::update_options(
2278
			array(
2279
				'version'     => $new_version,
2280
				'old_version' => $jetpack_old_version,
2281
			)
2282
		);
2283
2284
		Jetpack::state( 'message', 'modules_activated' );
2285
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
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...
2286
2287
		if ( $redirect ) {
2288
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2289
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2290
				$page = $_GET['page'];
2291
			}
2292
2293
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2294
			exit;
2295
		}
2296
	}
2297
2298
	/**
2299
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2300
	 * Make sure to tuck away module "library" files in a sub-directory.
2301
	 */
2302
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2303
		static $modules = null;
2304
2305
		if ( ! isset( $modules ) ) {
2306
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2307
			// Use the cache if we're on the front-end and it's available...
2308
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2309
				$modules = $available_modules_option[ JETPACK__VERSION ];
2310
			} else {
2311
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2312
2313
				$modules = array();
2314
2315
				foreach ( $files as $file ) {
2316
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2317
						continue;
2318
					}
2319
2320
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2321
				}
2322
2323
				Jetpack_Options::update_option( 'available_modules', array(
2324
					JETPACK__VERSION => $modules,
2325
				) );
2326
			}
2327
		}
2328
2329
		/**
2330
		 * Filters the array of modules available to be activated.
2331
		 *
2332
		 * @since 2.4.0
2333
		 *
2334
		 * @param array $modules Array of available modules.
2335
		 * @param string $min_version Minimum version number required to use modules.
2336
		 * @param string $max_version Maximum version number required to use modules.
2337
		 */
2338
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2339
2340
		if ( ! $min_version && ! $max_version ) {
2341
			return array_keys( $mods );
2342
		}
2343
2344
		$r = array();
2345
		foreach ( $mods as $slug => $introduced ) {
2346
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2347
				continue;
2348
			}
2349
2350
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2351
				continue;
2352
			}
2353
2354
			$r[] = $slug;
2355
		}
2356
2357
		return $r;
2358
	}
2359
2360
	/**
2361
	 * Default modules loaded on activation.
2362
	 */
2363
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2364
		$return = array();
2365
2366
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2367
			$module_data = Jetpack::get_module( $module );
2368
2369
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2370
				case 'yes' :
2371
					$return[] = $module;
2372
					break;
2373
				case 'public' :
2374
					if ( Jetpack_Options::get_option( 'public' ) ) {
2375
						$return[] = $module;
2376
					}
2377
					break;
2378
				case 'no' :
2379
				default :
2380
					break;
2381
			}
2382
		}
2383
		/**
2384
		 * Filters the array of default modules.
2385
		 *
2386
		 * @since 2.5.0
2387
		 *
2388
		 * @param array $return Array of default modules.
2389
		 * @param string $min_version Minimum version number required to use modules.
2390
		 * @param string $max_version Maximum version number required to use modules.
2391
		 */
2392
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2393
	}
2394
2395
	/**
2396
	 * Checks activated modules during auto-activation to determine
2397
	 * if any of those modules are being deprecated.  If so, close
2398
	 * them out, and add any replacement modules.
2399
	 *
2400
	 * Runs at priority 99 by default.
2401
	 *
2402
	 * This is run late, so that it can still activate a module if
2403
	 * the new module is a replacement for another that the user
2404
	 * currently has active, even if something at the normal priority
2405
	 * would kibosh everything.
2406
	 *
2407
	 * @since 2.6
2408
	 * @uses jetpack_get_default_modules filter
2409
	 * @param array $modules
2410
	 * @return array
2411
	 */
2412
	function handle_deprecated_modules( $modules ) {
2413
		$deprecated_modules = array(
2414
			'debug'            => null,  // Closed out and moved to the debugger library.
2415
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2416
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2417
		);
2418
2419
		// Don't activate SSO if they never completed activating WPCC.
2420
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2421
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2422
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2423
				$deprecated_modules['wpcc'] = null;
2424
			}
2425
		}
2426
2427
		foreach ( $deprecated_modules as $module => $replacement ) {
2428
			if ( Jetpack::is_module_active( $module ) ) {
2429
				self::deactivate_module( $module );
2430
				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...
2431
					$modules[] = $replacement;
2432
				}
2433
			}
2434
		}
2435
2436
		return array_unique( $modules );
2437
	}
2438
2439
	/**
2440
	 * Checks activated plugins during auto-activation to determine
2441
	 * if any of those plugins are in the list with a corresponding module
2442
	 * that is not compatible with the plugin. The module will not be allowed
2443
	 * to auto-activate.
2444
	 *
2445
	 * @since 2.6
2446
	 * @uses jetpack_get_default_modules filter
2447
	 * @param array $modules
2448
	 * @return array
2449
	 */
2450
	function filter_default_modules( $modules ) {
2451
2452
		$active_plugins = self::get_active_plugins();
2453
2454
		if ( ! empty( $active_plugins ) ) {
2455
2456
			// For each module we'd like to auto-activate...
2457
			foreach ( $modules as $key => $module ) {
2458
				// If there are potential conflicts for it...
2459
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2460
					// For each potential conflict...
2461
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2462
						// If that conflicting plugin is active...
2463
						if ( in_array( $plugin, $active_plugins ) ) {
2464
							// Remove that item from being auto-activated.
2465
							unset( $modules[ $key ] );
2466
						}
2467
					}
2468
				}
2469
			}
2470
		}
2471
2472
		return $modules;
2473
	}
2474
2475
	/**
2476
	 * Extract a module's slug from its full path.
2477
	 */
2478
	public static function get_module_slug( $file ) {
2479
		return str_replace( '.php', '', basename( $file ) );
2480
	}
2481
2482
	/**
2483
	 * Generate a module's path from its slug.
2484
	 */
2485
	public static function get_module_path( $slug ) {
2486
		/**
2487
		 * Filters the path of a modules.
2488
		 *
2489
		 * @since 7.4.0
2490
		 *
2491
		 * @param array $return The absolute path to a module's root php file
2492
		 * @param string $slug The module slug
2493
		 */
2494
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2495
	}
2496
2497
	/**
2498
	 * Load module data from module file. Headers differ from WordPress
2499
	 * plugin headers to avoid them being identified as standalone
2500
	 * plugins on the WordPress plugins page.
2501
	 */
2502
	public static function get_module( $module ) {
2503
		$headers = array(
2504
			'name'                      => 'Module Name',
2505
			'description'               => 'Module Description',
2506
			'jumpstart_desc'            => 'Jumpstart Description',
2507
			'sort'                      => 'Sort Order',
2508
			'recommendation_order'      => 'Recommendation Order',
2509
			'introduced'                => 'First Introduced',
2510
			'changed'                   => 'Major Changes In',
2511
			'deactivate'                => 'Deactivate',
2512
			'free'                      => 'Free',
2513
			'requires_connection'       => 'Requires Connection',
2514
			'auto_activate'             => 'Auto Activate',
2515
			'module_tags'               => 'Module Tags',
2516
			'feature'                   => 'Feature',
2517
			'additional_search_queries' => 'Additional Search Queries',
2518
			'plan_classes'              => 'Plans',
2519
		);
2520
2521
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2522
2523
		$mod = Jetpack::get_file_data( $file, $headers );
2524
		if ( empty( $mod['name'] ) ) {
2525
			return false;
2526
		}
2527
2528
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2529
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2530
		$mod['deactivate']              = empty( $mod['deactivate'] );
2531
		$mod['free']                    = empty( $mod['free'] );
2532
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2533
2534
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2535
			$mod['auto_activate'] = 'No';
2536
		} else {
2537
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2538
		}
2539
2540
		if ( $mod['module_tags'] ) {
2541
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2542
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2543
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2544
		} else {
2545
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2546
		}
2547
2548 View Code Duplication
		if ( $mod['plan_classes'] ) {
2549
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2550
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2551
		} else {
2552
			$mod['plan_classes'] = array( 'free' );
2553
		}
2554
2555 View Code Duplication
		if ( $mod['feature'] ) {
2556
			$mod['feature'] = explode( ',', $mod['feature'] );
2557
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2558
		} else {
2559
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2560
		}
2561
2562
		/**
2563
		 * Filters the feature array on a module.
2564
		 *
2565
		 * This filter allows you to control where each module is filtered: Recommended,
2566
		 * Jumpstart, and the default "Other" listing.
2567
		 *
2568
		 * @since 3.5.0
2569
		 *
2570
		 * @param array   $mod['feature'] The areas to feature this module:
2571
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2572
		 *     'Recommended' shows on the main Jetpack admin screen.
2573
		 *     'Other' should be the default if no other value is in the array.
2574
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2575
		 * @param array   $mod All the currently assembled module data.
2576
		 */
2577
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2578
2579
		/**
2580
		 * Filter the returned data about a module.
2581
		 *
2582
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2583
		 * so please be careful.
2584
		 *
2585
		 * @since 3.6.0
2586
		 *
2587
		 * @param array   $mod    The details of the requested module.
2588
		 * @param string  $module The slug of the module, e.g. sharedaddy
2589
		 * @param string  $file   The path to the module source file.
2590
		 */
2591
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2592
	}
2593
2594
	/**
2595
	 * Like core's get_file_data implementation, but caches the result.
2596
	 */
2597
	public static function get_file_data( $file, $headers ) {
2598
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2599
		$file_name = basename( $file );
2600
2601
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2602
2603
		$file_data_option = get_transient( $cache_key );
2604
2605
		if ( false === $file_data_option ) {
2606
			$file_data_option = array();
2607
		}
2608
2609
		$key           = md5( $file_name . serialize( $headers ) );
2610
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2611
2612
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2613
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2614
			return $file_data_option[ $key ];
2615
		}
2616
2617
		$data = get_file_data( $file, $headers );
2618
2619
		$file_data_option[ $key ] = $data;
2620
2621
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2622
2623
		return $data;
2624
	}
2625
2626
2627
	/**
2628
	 * Return translated module tag.
2629
	 *
2630
	 * @param string $tag Tag as it appears in each module heading.
2631
	 *
2632
	 * @return mixed
2633
	 */
2634
	public static function translate_module_tag( $tag ) {
2635
		return jetpack_get_module_i18n_tag( $tag );
2636
	}
2637
2638
	/**
2639
	 * Get i18n strings as a JSON-encoded string
2640
	 *
2641
	 * @return string The locale as JSON
2642
	 */
2643
	public static function get_i18n_data_json() {
2644
2645
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2646
		// JSON files with the file they should be included for. This is an md5
2647
		// of '_inc/build/admin.js'.
2648
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2649
2650
		$i18n_json =
2651
				   JETPACK__PLUGIN_DIR
2652
				   . 'languages/json/jetpack-'
2653
				   . get_user_locale()
2654
				   . '-'
2655
				   . $path_md5
2656
				   . '.json';
2657
2658
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2659
			$locale_data = @file_get_contents( $i18n_json );
2660
			if ( $locale_data ) {
2661
				return $locale_data;
2662
			}
2663
		}
2664
2665
		// Return valid empty Jed locale
2666
		return '{ "locale_data": { "messages": { "": {} } } }';
2667
	}
2668
2669
	/**
2670
	 * Add locale data setup to wp-i18n
2671
	 *
2672
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2673
	 *
2674
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2675
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2676
	 *
2677
	 * This method provides a safe way to request the setup multiple times but add the script at
2678
	 * most once.
2679
	 *
2680
	 * @since 6.7.0
2681
	 *
2682
	 * @return void
2683
	 */
2684
	public static function setup_wp_i18n_locale_data() {
2685
		static $script_added = false;
2686
		if ( ! $script_added ) {
2687
			$script_added = true;
2688
			wp_add_inline_script(
2689
				'wp-i18n',
2690
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2691
			);
2692
		}
2693
	}
2694
2695
	/**
2696
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2697
	 *
2698
	 * @since 3.9.2
2699
	 *
2700
	 * @param array $modules
2701
	 *
2702
	 * @return string|void
2703
	 */
2704
	public static function get_translated_modules( $modules ) {
2705
		foreach ( $modules as $index => $module ) {
2706
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2707
			if ( isset( $module['name'] ) ) {
2708
				$modules[ $index ]['name'] = $i18n_module['name'];
2709
			}
2710
			if ( isset( $module['description'] ) ) {
2711
				$modules[ $index ]['description'] = $i18n_module['description'];
2712
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2713
			}
2714
		}
2715
		return $modules;
2716
	}
2717
2718
	/**
2719
	 * Get a list of activated modules as an array of module slugs.
2720
	 */
2721
	public static function get_active_modules() {
2722
		$active = Jetpack_Options::get_option( 'active_modules' );
2723
2724
		if ( ! is_array( $active ) ) {
2725
			$active = array();
2726
		}
2727
2728
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2729
			$active[] = 'vaultpress';
2730
		} else {
2731
			$active = array_diff( $active, array( 'vaultpress' ) );
2732
		}
2733
2734
		//If protect is active on the main site of a multisite, it should be active on all sites.
2735
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2736
			$active[] = 'protect';
2737
		}
2738
2739
		/**
2740
		 * Allow filtering of the active modules.
2741
		 *
2742
		 * Gives theme and plugin developers the power to alter the modules that
2743
		 * are activated on the fly.
2744
		 *
2745
		 * @since 5.8.0
2746
		 *
2747
		 * @param array $active Array of active module slugs.
2748
		 */
2749
		$active = apply_filters( 'jetpack_active_modules', $active );
2750
2751
		return array_unique( $active );
2752
	}
2753
2754
	/**
2755
	 * Check whether or not a Jetpack module is active.
2756
	 *
2757
	 * @param string $module The slug of a Jetpack module.
2758
	 * @return bool
2759
	 *
2760
	 * @static
2761
	 */
2762
	public static function is_module_active( $module ) {
2763
		return in_array( $module, self::get_active_modules() );
2764
	}
2765
2766
	public static function is_module( $module ) {
2767
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2768
	}
2769
2770
	/**
2771
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2772
	 *
2773
	 * @param bool $catch True to start catching, False to stop.
2774
	 *
2775
	 * @static
2776
	 */
2777
	public static function catch_errors( $catch ) {
2778
		static $display_errors, $error_reporting;
2779
2780
		if ( $catch ) {
2781
			$display_errors  = @ini_set( 'display_errors', 1 );
2782
			$error_reporting = @error_reporting( E_ALL );
2783
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2784
		} else {
2785
			@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...
2786
			@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...
2787
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2788
		}
2789
	}
2790
2791
	/**
2792
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2793
	 */
2794
	public static function catch_errors_on_shutdown() {
2795
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2796
	}
2797
2798
	/**
2799
	 * Rewrite any string to make paths easier to read.
2800
	 *
2801
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2802
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2803
	 *
2804
	 * @param $string
2805
	 * @return mixed
2806
	 */
2807
	public static function alias_directories( $string ) {
2808
		// ABSPATH has a trailing slash.
2809
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2810
		// WP_CONTENT_DIR does not have a trailing slash.
2811
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2812
2813
		return $string;
2814
	}
2815
2816
	public static function activate_default_modules(
2817
		$min_version = false,
2818
		$max_version = false,
2819
		$other_modules = array(),
2820
		$redirect = true,
2821
		$send_state_messages = true
2822
	) {
2823
		$jetpack = Jetpack::init();
2824
2825
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2826
		$modules = array_merge( $other_modules, $modules );
2827
2828
		// Look for standalone plugins and disable if active.
2829
2830
		$to_deactivate = array();
2831
		foreach ( $modules as $module ) {
2832
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2833
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2834
			}
2835
		}
2836
2837
		$deactivated = array();
2838
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2839
			list( $probable_file, $probable_title ) = $deactivate_me;
2840
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2841
				$deactivated[] = $module;
2842
			}
2843
		}
2844
2845
		if ( $deactivated && $redirect ) {
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...
2846
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2847
2848
			$url = add_query_arg(
2849
				array(
2850
					'action'   => 'activate_default_modules',
2851
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2852
				),
2853
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2854
			);
2855
			wp_safe_redirect( $url );
2856
			exit;
2857
		}
2858
2859
		/**
2860
		 * Fires before default modules are activated.
2861
		 *
2862
		 * @since 1.9.0
2863
		 *
2864
		 * @param string $min_version Minimum version number required to use modules.
2865
		 * @param string $max_version Maximum version number required to use modules.
2866
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2867
		 */
2868
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2869
2870
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2871
		if ( $send_state_messages ) {
2872
			Jetpack::restate();
2873
			Jetpack::catch_errors( true );
2874
		}
2875
2876
		$active = Jetpack::get_active_modules();
2877
2878
		foreach ( $modules as $module ) {
2879
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2880
				$active[] = $module;
2881
				self::update_active_modules( $active );
2882
				continue;
2883
			}
2884
2885
			if ( $send_state_messages && in_array( $module, $active ) ) {
2886
				$module_info = Jetpack::get_module( $module );
2887 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2888
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2889
					if ( $active_state = Jetpack::state( $state ) ) {
2890
						$active_state = explode( ',', $active_state );
2891
					} else {
2892
						$active_state = array();
2893
					}
2894
					$active_state[] = $module;
2895
					Jetpack::state( $state, implode( ',', $active_state ) );
2896
				}
2897
				continue;
2898
			}
2899
2900
			$file = Jetpack::get_module_path( $module );
2901
			if ( ! file_exists( $file ) ) {
2902
				continue;
2903
			}
2904
2905
			// we'll override this later if the plugin can be included without fatal error
2906
			if ( $redirect ) {
2907
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2908
			}
2909
2910
			if ( $send_state_messages ) {
2911
				Jetpack::state( 'error', 'module_activation_failed' );
2912
				Jetpack::state( 'module', $module );
2913
			}
2914
2915
			ob_start();
2916
			require_once $file;
2917
2918
			$active[] = $module;
2919
2920 View Code Duplication
			if ( $send_state_messages ) {
2921
2922
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2923
				if ( $active_state = Jetpack::state( $state ) ) {
2924
					$active_state = explode( ',', $active_state );
2925
				} else {
2926
					$active_state = array();
2927
				}
2928
				$active_state[] = $module;
2929
				Jetpack::state( $state, implode( ',', $active_state ) );
2930
			}
2931
2932
			Jetpack::update_active_modules( $active );
2933
2934
			ob_end_clean();
2935
		}
2936
2937
		if ( $send_state_messages ) {
2938
			Jetpack::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...
2939
			Jetpack::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...
2940
		}
2941
2942
		Jetpack::catch_errors( false );
2943
		/**
2944
		 * Fires when default modules are activated.
2945
		 *
2946
		 * @since 1.9.0
2947
		 *
2948
		 * @param string $min_version Minimum version number required to use modules.
2949
		 * @param string $max_version Maximum version number required to use modules.
2950
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2951
		 */
2952
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2953
	}
2954
2955
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2956
		/**
2957
		 * Fires before a module is activated.
2958
		 *
2959
		 * @since 2.6.0
2960
		 *
2961
		 * @param string $module Module slug.
2962
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2963
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2964
		 */
2965
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2966
2967
		$jetpack = Jetpack::init();
2968
2969
		if ( ! strlen( $module ) )
2970
			return false;
2971
2972
		if ( ! Jetpack::is_module( $module ) )
2973
			return false;
2974
2975
		// If it's already active, then don't do it again
2976
		$active = Jetpack::get_active_modules();
2977
		foreach ( $active as $act ) {
2978
			if ( $act == $module )
2979
				return true;
2980
		}
2981
2982
		$module_data = Jetpack::get_module( $module );
2983
2984
		if ( ! Jetpack::is_active() ) {
2985
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2986
				return false;
2987
2988
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2989
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2990
				return false;
2991
		}
2992
2993
		// Check and see if the old plugin is active
2994
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2995
			// Deactivate the old plugin
2996
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2997
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2998
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2999
				Jetpack::state( 'deactivated_plugins', $module );
3000
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3001
				exit;
3002
			}
3003
		}
3004
3005
		// Protect won't work with mis-configured IPs
3006
		if ( 'protect' === $module ) {
3007
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3008
			if ( ! jetpack_protect_get_ip() ) {
3009
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3010
				return false;
3011
			}
3012
		}
3013
3014
		if ( ! Jetpack_Plan::supports( $module ) ) {
3015
			return false;
3016
		}
3017
3018
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3019
		Jetpack::state( 'module', $module );
3020
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3021
3022
		Jetpack::catch_errors( true );
3023
		ob_start();
3024
		require Jetpack::get_module_path( $module );
3025
		/** This action is documented in class.jetpack.php */
3026
		do_action( 'jetpack_activate_module', $module );
3027
		$active[] = $module;
3028
		Jetpack::update_active_modules( $active );
3029
3030
		Jetpack::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...
3031
		ob_end_clean();
3032
		Jetpack::catch_errors( false );
3033
3034
		if ( $redirect ) {
3035
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3036
		}
3037
		if ( $exit ) {
3038
			exit;
3039
		}
3040
		return true;
3041
	}
3042
3043
	function activate_module_actions( $module ) {
3044
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3045
	}
3046
3047
	public static function deactivate_module( $module ) {
3048
		/**
3049
		 * Fires when a module is deactivated.
3050
		 *
3051
		 * @since 1.9.0
3052
		 *
3053
		 * @param string $module Module slug.
3054
		 */
3055
		do_action( 'jetpack_pre_deactivate_module', $module );
3056
3057
		$jetpack = Jetpack::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...
3058
3059
		$active = Jetpack::get_active_modules();
3060
		$new    = array_filter( array_diff( $active, (array) $module ) );
3061
3062
		return self::update_active_modules( $new );
3063
	}
3064
3065
	public static function enable_module_configurable( $module ) {
3066
		$module = Jetpack::get_module_slug( $module );
3067
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3068
	}
3069
3070
	/**
3071
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3072
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3073
	 *
3074
	 * @param string $module Module slug
3075
	 * @return string $url module configuration URL
3076
	 */
3077
	public static function module_configuration_url( $module ) {
3078
		$module = Jetpack::get_module_slug( $module );
3079
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3080
		/**
3081
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3082
		 *
3083
		 * @since 6.9.0
3084
		 *
3085
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3086
		 */
3087
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3088
3089
		return $url;
3090
	}
3091
3092
/* Installation */
3093
	public static function bail_on_activation( $message, $deactivate = true ) {
3094
?>
3095
<!doctype html>
3096
<html>
3097
<head>
3098
<meta charset="<?php bloginfo( 'charset' ); ?>">
3099
<style>
3100
* {
3101
	text-align: center;
3102
	margin: 0;
3103
	padding: 0;
3104
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3105
}
3106
p {
3107
	margin-top: 1em;
3108
	font-size: 18px;
3109
}
3110
</style>
3111
<body>
3112
<p><?php echo esc_html( $message ); ?></p>
3113
</body>
3114
</html>
3115
<?php
3116
		if ( $deactivate ) {
3117
			$plugins = get_option( 'active_plugins' );
3118
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3119
			$update  = false;
3120
			foreach ( $plugins as $i => $plugin ) {
3121
				if ( $plugin === $jetpack ) {
3122
					$plugins[$i] = false;
3123
					$update = true;
3124
				}
3125
			}
3126
3127
			if ( $update ) {
3128
				update_option( 'active_plugins', array_filter( $plugins ) );
3129
			}
3130
		}
3131
		exit;
3132
	}
3133
3134
	/**
3135
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3136
	 * @static
3137
	 */
3138
	public static function plugin_activation( $network_wide ) {
3139
		Jetpack_Options::update_option( 'activated', 1 );
3140
3141
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3142
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3143
		}
3144
3145
		if ( $network_wide )
3146
			Jetpack::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...
3147
3148
		// For firing one-off events (notices) immediately after activation
3149
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3150
3151
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3152
3153
		Jetpack::plugin_initialize();
3154
	}
3155
3156
	public static function get_activation_source( $referer_url ) {
3157
3158
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3159
			return array( 'wp-cli', null );
3160
		}
3161
3162
		$referer = parse_url( $referer_url );
3163
3164
		$source_type = 'unknown';
3165
		$source_query = null;
3166
3167
		if ( ! is_array( $referer ) ) {
3168
			return array( $source_type, $source_query );
3169
		}
3170
3171
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3172
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3173
3174
		if ( isset( $referer['query'] ) ) {
3175
			parse_str( $referer['query'], $query_parts );
3176
		} else {
3177
			$query_parts = array();
3178
		}
3179
3180
		if ( $plugins_path === $referer['path'] ) {
3181
			$source_type = 'list';
3182
		} elseif ( $plugins_install_path === $referer['path'] ) {
3183
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3184
			switch( $tab ) {
3185
				case 'popular':
3186
					$source_type = 'popular';
3187
					break;
3188
				case 'recommended':
3189
					$source_type = 'recommended';
3190
					break;
3191
				case 'favorites':
3192
					$source_type = 'favorites';
3193
					break;
3194
				case 'search':
3195
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3196
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3197
					break;
3198
				default:
3199
					$source_type = 'featured';
3200
			}
3201
		}
3202
3203
		return array( $source_type, $source_query );
3204
	}
3205
3206
	/**
3207
	 * Runs before bumping version numbers up to a new version
3208
	 * @param  string $version    Version:timestamp
3209
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3210
	 * @return null              [description]
3211
	 */
3212
	public static function do_version_bump( $version, $old_version ) {
3213
		if ( ! $old_version ) { // For new sites
3214
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3215
		}
3216
	}
3217
3218
	/**
3219
	 * Sets the internal version number and activation state.
3220
	 * @static
3221
	 */
3222
	public static function plugin_initialize() {
3223
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3224
			Jetpack_Options::update_option( 'activated', 2 );
3225
		}
3226
3227 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3228
			$version = $old_version = JETPACK__VERSION . ':' . time();
3229
			/** This action is documented in class.jetpack.php */
3230
			do_action( 'updating_jetpack_version', $version, false );
3231
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3232
		}
3233
3234
		Jetpack::load_modules();
3235
3236
		Jetpack_Options::delete_option( 'do_activate' );
3237
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3238
	}
3239
3240
	/**
3241
	 * Removes all connection options
3242
	 * @static
3243
	 */
3244
	public static function plugin_deactivation( ) {
3245
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3246
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3247
			Jetpack_Network::init()->deactivate();
3248
		} else {
3249
			Jetpack::disconnect( false );
3250
			//Jetpack_Heartbeat::init()->deactivate();
3251
		}
3252
	}
3253
3254
	/**
3255
	 * Disconnects from the Jetpack servers.
3256
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3257
	 * @static
3258
	 */
3259
	public static function disconnect( $update_activated_state = true ) {
3260
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3261
		Jetpack::clean_nonces( true );
3262
3263
		// If the site is in an IDC because sync is not allowed,
3264
		// let's make sure to not disconnect the production site.
3265
		if ( ! self::validate_sync_error_idc_option() ) {
3266
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3267
			Jetpack::load_xml_rpc_client();
3268
			$xml = new Jetpack_IXR_Client();
3269
			$xml->query( 'jetpack.deregister' );
3270
		}
3271
3272
		Jetpack_Options::delete_option(
3273
			array(
3274
				'blog_token',
3275
				'user_token',
3276
				'user_tokens',
3277
				'master_user',
3278
				'time_diff',
3279
				'fallback_no_verify_ssl_certs',
3280
			)
3281
		);
3282
3283
		Jetpack_IDC::clear_all_idc_options();
3284
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3285
3286
		if ( $update_activated_state ) {
3287
			Jetpack_Options::update_option( 'activated', 4 );
3288
		}
3289
3290
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3291
			// Check then record unique disconnection if site has never been disconnected previously
3292
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3293
				$jetpack_unique_connection['disconnected'] = 1;
3294
			} else {
3295
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3296
					//track unique disconnect
3297
					$jetpack = Jetpack::init();
3298
3299
					$jetpack->stat( 'connections', 'unique-disconnect' );
3300
					$jetpack->do_stats( 'server_side' );
3301
				}
3302
				// increment number of times disconnected
3303
				$jetpack_unique_connection['disconnected'] += 1;
3304
			}
3305
3306
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3307
		}
3308
3309
		// Delete cached connected user data
3310
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3311
		delete_transient( $transient_key );
3312
3313
		// Delete all the sync related data. Since it could be taking up space.
3314
		Jetpack_Sync_Sender::get_instance()->uninstall();
3315
3316
		// Disable the Heartbeat cron
3317
		Jetpack_Heartbeat::init()->deactivate();
3318
	}
3319
3320
	/**
3321
	 * Unlinks the current user from the linked WordPress.com user
3322
	 */
3323
	public static function unlink_user( $user_id = null ) {
3324
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3325
			return false;
3326
3327
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3328
3329
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3330
			return false;
3331
3332
		if ( ! isset( $tokens[ $user_id ] ) )
3333
			return false;
3334
3335
		Jetpack::load_xml_rpc_client();
3336
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3337
		$xml->query( 'jetpack.unlink_user', $user_id );
3338
3339
		unset( $tokens[ $user_id ] );
3340
3341
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3342
3343
		/**
3344
		 * Fires after the current user has been unlinked from WordPress.com.
3345
		 *
3346
		 * @since 4.1.0
3347
		 *
3348
		 * @param int $user_id The current user's ID.
3349
		 */
3350
		do_action( 'jetpack_unlinked_user', $user_id );
3351
3352
		return true;
3353
	}
3354
3355
	/**
3356
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3357
	 */
3358
	public static function try_registration() {
3359
		// The user has agreed to the TOS at some point by now.
3360
		Jetpack_Options::update_option( 'tos_agreed', true );
3361
3362
		// Let's get some testing in beta versions and such.
3363
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3364
			// Before attempting to connect, let's make sure that the domains are viable.
3365
			$domains_to_check = array_unique( array(
3366
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3367
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3368
			) );
3369
			foreach ( $domains_to_check as $domain ) {
3370
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3369 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...
3371
				if ( is_wp_error( $result ) ) {
3372
					return $result;
3373
				}
3374
			}
3375
		}
3376
3377
		$result = Jetpack::register();
3378
3379
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3380
		if ( ! $result || is_wp_error( $result ) ) {
3381
			return $result;
3382
		} else {
3383
			return true;
3384
		}
3385
	}
3386
3387
	/**
3388
	 * Tracking an internal event log. Try not to put too much chaff in here.
3389
	 *
3390
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3391
	 */
3392
	public static function log( $code, $data = null ) {
3393
		// only grab the latest 200 entries
3394
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3395
3396
		// Append our event to the log
3397
		$log_entry = array(
3398
			'time'    => time(),
3399
			'user_id' => get_current_user_id(),
3400
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3401
			'code'    => $code,
3402
		);
3403
		// Don't bother storing it unless we've got some.
3404
		if ( ! is_null( $data ) ) {
3405
			$log_entry['data'] = $data;
3406
		}
3407
		$log[] = $log_entry;
3408
3409
		// Try add_option first, to make sure it's not autoloaded.
3410
		// @todo: Add an add_option method to Jetpack_Options
3411
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3412
			Jetpack_Options::update_option( 'log', $log );
3413
		}
3414
3415
		/**
3416
		 * Fires when Jetpack logs an internal event.
3417
		 *
3418
		 * @since 3.0.0
3419
		 *
3420
		 * @param array $log_entry {
3421
		 *	Array of details about the log entry.
3422
		 *
3423
		 *	@param string time Time of the event.
3424
		 *	@param int user_id ID of the user who trigerred the event.
3425
		 *	@param int blog_id Jetpack Blog ID.
3426
		 *	@param string code Unique name for the event.
3427
		 *	@param string data Data about the event.
3428
		 * }
3429
		 */
3430
		do_action( 'jetpack_log_entry', $log_entry );
3431
	}
3432
3433
	/**
3434
	 * Get the internal event log.
3435
	 *
3436
	 * @param $event (string) - only return the specific log events
3437
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3438
	 *
3439
	 * @return array of log events || WP_Error for invalid params
3440
	 */
3441
	public static function get_log( $event = false, $num = false ) {
3442
		if ( $event && ! is_string( $event ) ) {
3443
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3444
		}
3445
3446
		if ( $num && ! is_numeric( $num ) ) {
3447
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3448
		}
3449
3450
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3451
3452
		// If nothing set - act as it did before, otherwise let's start customizing the output
3453
		if ( ! $num && ! $event ) {
3454
			return $entire_log;
3455
		} else {
3456
			$entire_log = array_reverse( $entire_log );
3457
		}
3458
3459
		$custom_log_output = array();
3460
3461
		if ( $event ) {
3462
			foreach ( $entire_log as $log_event ) {
3463
				if ( $event == $log_event[ 'code' ] ) {
3464
					$custom_log_output[] = $log_event;
3465
				}
3466
			}
3467
		} else {
3468
			$custom_log_output = $entire_log;
3469
		}
3470
3471
		if ( $num ) {
3472
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3473
		}
3474
3475
		return $custom_log_output;
3476
	}
3477
3478
	/**
3479
	 * Log modification of important settings.
3480
	 */
3481
	public static function log_settings_change( $option, $old_value, $value ) {
3482
		switch( $option ) {
3483
			case 'jetpack_sync_non_public_post_stati':
3484
				self::log( $option, $value );
3485
				break;
3486
		}
3487
	}
3488
3489
	/**
3490
	 * Return stat data for WPCOM sync
3491
	 */
3492
	public static function get_stat_data( $encode = true, $extended = true ) {
3493
		$data = Jetpack_Heartbeat::generate_stats_array();
3494
3495
		if ( $extended ) {
3496
			$additional_data = self::get_additional_stat_data();
3497
			$data = array_merge( $data, $additional_data );
3498
		}
3499
3500
		if ( $encode ) {
3501
			return json_encode( $data );
3502
		}
3503
3504
		return $data;
3505
	}
3506
3507
	/**
3508
	 * Get additional stat data to sync to WPCOM
3509
	 */
3510
	public static function get_additional_stat_data( $prefix = '' ) {
3511
		$return["{$prefix}themes"]         = Jetpack::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...
3512
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3513
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3514
		$return["{$prefix}site-count"]     = 0;
3515
3516
		if ( function_exists( 'get_blog_count' ) ) {
3517
			$return["{$prefix}site-count"] = get_blog_count();
3518
		}
3519
		return $return;
3520
	}
3521
3522
	private static function get_site_user_count() {
3523
		global $wpdb;
3524
3525
		if ( function_exists( 'wp_is_large_network' ) ) {
3526
			if ( wp_is_large_network( 'users' ) ) {
3527
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3528
			}
3529
		}
3530 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3531
			// It wasn't there, so regenerate the data and save the transient
3532
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3533
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3534
		}
3535
		return $user_count;
3536
	}
3537
3538
	/* Admin Pages */
3539
3540
	function admin_init() {
3541
		// If the plugin is not connected, display a connect message.
3542
		if (
3543
			// the plugin was auto-activated and needs its candy
3544
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3545
		||
3546
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3547
			! Jetpack_Options::get_option( 'activated' )
3548
		) {
3549
			Jetpack::plugin_initialize();
3550
		}
3551
3552
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3553
			Jetpack_Connection_Banner::init();
3554
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3555
			// Upgrade: 1.1 -> 1.1.1
3556
			// Check and see if host can verify the Jetpack servers' SSL certificate
3557
			$args = array();
3558
			Jetpack_Client::_wp_remote_request(
3559
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3560
				$args,
3561
				true
3562
			);
3563
		}
3564
3565
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3566
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3567
		}
3568
3569
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3570
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3571
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3572
3573
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3574
			// Artificially throw errors in certain whitelisted cases during plugin activation
3575
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3576
		}
3577
3578
		// Add custom column in wp-admin/users.php to show whether user is linked.
3579
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3580
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3581
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3582
	}
3583
3584
	function admin_body_class( $admin_body_class = '' ) {
3585
		$classes = explode( ' ', trim( $admin_body_class ) );
3586
3587
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3588
3589
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3590
		return " $admin_body_class ";
3591
	}
3592
3593
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3594
		return $admin_body_class . ' jetpack-pagestyles ';
3595
	}
3596
3597
	/**
3598
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3599
	 * This function artificially throws errors for such cases (whitelisted).
3600
	 *
3601
	 * @param string $plugin The activated plugin.
3602
	 */
3603
	function throw_error_on_activate_plugin( $plugin ) {
3604
		$active_modules = Jetpack::get_active_modules();
3605
3606
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3607
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3608
			$throw = false;
3609
3610
			// Try and make sure it really was the stats plugin
3611
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3612
				if ( 'stats.php' == basename( $plugin ) ) {
3613
					$throw = true;
3614
				}
3615
			} else {
3616
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3617
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3618
					$throw = true;
3619
				}
3620
			}
3621
3622
			if ( $throw ) {
3623
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3624
			}
3625
		}
3626
	}
3627
3628
	function intercept_plugin_error_scrape_init() {
3629
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3630
	}
3631
3632
	function intercept_plugin_error_scrape( $action, $result ) {
3633
		if ( ! $result ) {
3634
			return;
3635
		}
3636
3637
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3638
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3639
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3640
			}
3641
		}
3642
	}
3643
3644
	function add_remote_request_handlers() {
3645
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3646
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3647
	}
3648
3649
	function remote_request_handlers() {
3650
		$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...
3651
3652
		switch ( current_filter() ) {
3653
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3654
			$response = $this->upload_handler();
3655
			break;
3656
3657
		case 'wp_ajax_nopriv_jetpack_update_file' :
3658
			$response = $this->upload_handler( true );
3659
			break;
3660
		default :
3661
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3662
			break;
3663
		}
3664
3665
		if ( ! $response ) {
3666
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3667
		}
3668
3669
		if ( is_wp_error( $response ) ) {
3670
			$status_code       = $response->get_error_data();
3671
			$error             = $response->get_error_code();
3672
			$error_description = $response->get_error_message();
3673
3674
			if ( ! is_int( $status_code ) ) {
3675
				$status_code = 400;
3676
			}
3677
3678
			status_header( $status_code );
3679
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3680
		}
3681
3682
		status_header( 200 );
3683
		if ( true === $response ) {
3684
			exit;
3685
		}
3686
3687
		die( json_encode( (object) $response ) );
3688
	}
3689
3690
	/**
3691
	 * Uploads a file gotten from the global $_FILES.
3692
	 * If `$update_media_item` is true and `post_id` is defined
3693
	 * the attachment file of the media item (gotten through of the post_id)
3694
	 * will be updated instead of add a new one.
3695
	 *
3696
	 * @param  boolean $update_media_item - update media attachment
3697
	 * @return array - An array describing the uploadind files process
3698
	 */
3699
	function upload_handler( $update_media_item = false ) {
3700
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3701
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3702
		}
3703
3704
		$user = wp_authenticate( '', '' );
3705
		if ( ! $user || is_wp_error( $user ) ) {
3706
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3707
		}
3708
3709
		wp_set_current_user( $user->ID );
3710
3711
		if ( ! current_user_can( 'upload_files' ) ) {
3712
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3713
		}
3714
3715
		if ( empty( $_FILES ) ) {
3716
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3717
		}
3718
3719
		foreach ( array_keys( $_FILES ) as $files_key ) {
3720
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3721
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3722
			}
3723
		}
3724
3725
		$media_keys = array_keys( $_FILES['media'] );
3726
3727
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
3728
		if ( ! $token || is_wp_error( $token ) ) {
3729
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3730
		}
3731
3732
		$uploaded_files = array();
3733
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3734
		unset( $GLOBALS['post'] );
3735
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3736
			$file = array();
3737
			foreach ( $media_keys as $media_key ) {
3738
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3739
			}
3740
3741
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3742
3743
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3744
			if ( $hmac_provided !== $hmac_file ) {
3745
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3746
				continue;
3747
			}
3748
3749
			$_FILES['.jetpack.upload.'] = $file;
3750
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3751
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3752
				$post_id = 0;
3753
			}
3754
3755
			if ( $update_media_item ) {
3756
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3757
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3758
				}
3759
3760
				$media_array = $_FILES['media'];
3761
3762
				$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...
3763
				$file_array['type'] = $media_array['type'][0];
3764
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3765
				$file_array['error'] = $media_array['error'][0];
3766
				$file_array['size'] = $media_array['size'][0];
3767
3768
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3769
3770
				if ( is_wp_error( $edited_media_item ) ) {
3771
					return $edited_media_item;
3772
				}
3773
3774
				$response = (object) array(
3775
					'id'   => (string) $post_id,
3776
					'file' => (string) $edited_media_item->post_title,
3777
					'url'  => (string) wp_get_attachment_url( $post_id ),
3778
					'type' => (string) $edited_media_item->post_mime_type,
3779
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3780
				);
3781
3782
				return (array) array( $response );
3783
			}
3784
3785
			$attachment_id = media_handle_upload(
3786
				'.jetpack.upload.',
3787
				$post_id,
3788
				array(),
3789
				array(
3790
					'action' => 'jetpack_upload_file',
3791
				)
3792
			);
3793
3794
			if ( ! $attachment_id ) {
3795
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3796
			} elseif ( is_wp_error( $attachment_id ) ) {
3797
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3798
			} else {
3799
				$attachment = get_post( $attachment_id );
3800
				$uploaded_files[$index] = (object) array(
3801
					'id'   => (string) $attachment_id,
3802
					'file' => $attachment->post_title,
3803
					'url'  => wp_get_attachment_url( $attachment_id ),
3804
					'type' => $attachment->post_mime_type,
3805
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3806
				);
3807
				// Zip files uploads are not supported unless they are done for installation purposed
3808
				// lets delete them in case something goes wrong in this whole process
3809
				if ( 'application/zip' === $attachment->post_mime_type ) {
3810
					// Schedule a cleanup for 2 hours from now in case of failed install.
3811
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3812
				}
3813
			}
3814
		}
3815
		if ( ! is_null( $global_post ) ) {
3816
			$GLOBALS['post'] = $global_post;
3817
		}
3818
3819
		return $uploaded_files;
3820
	}
3821
3822
	/**
3823
	 * Add help to the Jetpack page
3824
	 *
3825
	 * @since Jetpack (1.2.3)
3826
	 * @return false if not the Jetpack page
3827
	 */
3828
	function admin_help() {
3829
		$current_screen = get_current_screen();
3830
3831
		// Overview
3832
		$current_screen->add_help_tab(
3833
			array(
3834
				'id'		=> 'home',
3835
				'title'		=> __( 'Home', 'jetpack' ),
3836
				'content'	=>
3837
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3838
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3839
					'<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>',
3840
			)
3841
		);
3842
3843
		// Screen Content
3844
		if ( current_user_can( 'manage_options' ) ) {
3845
			$current_screen->add_help_tab(
3846
				array(
3847
					'id'		=> 'settings',
3848
					'title'		=> __( 'Settings', 'jetpack' ),
3849
					'content'	=>
3850
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3851
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3852
						'<ol>' .
3853
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3854
							'<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>' .
3855
						'</ol>' .
3856
						'<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>'
3857
				)
3858
			);
3859
		}
3860
3861
		// Help Sidebar
3862
		$current_screen->set_help_sidebar(
3863
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3864
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3865
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3866
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3867
		);
3868
	}
3869
3870
	function admin_menu_css() {
3871
		wp_enqueue_style( 'jetpack-icons' );
3872
	}
3873
3874
	function admin_menu_order() {
3875
		return true;
3876
	}
3877
3878 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3879
		$jp_menu_order = array();
3880
3881
		foreach ( $menu_order as $index => $item ) {
3882
			if ( $item != 'jetpack' ) {
3883
				$jp_menu_order[] = $item;
3884
			}
3885
3886
			if ( $index == 0 ) {
3887
				$jp_menu_order[] = 'jetpack';
3888
			}
3889
		}
3890
3891
		return $jp_menu_order;
3892
	}
3893
3894
	function admin_banner_styles() {
3895
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3896
3897
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3898
			wp_register_style(
3899
				'jetpack-dops-style',
3900
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3901
				array(),
3902
				JETPACK__VERSION
3903
			);
3904
		}
3905
3906
		wp_enqueue_style(
3907
			'jetpack',
3908
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3909
			array( 'jetpack-dops-style' ),
3910
			 JETPACK__VERSION . '-20121016'
3911
		);
3912
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3913
		wp_style_add_data( 'jetpack', 'suffix', $min );
3914
	}
3915
3916
	function plugin_action_links( $actions ) {
3917
3918
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3919
3920
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3921
			return array_merge(
3922
				$jetpack_home,
3923
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3924
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3925
				$actions
3926
				);
3927
			}
3928
3929
		return array_merge( $jetpack_home, $actions );
3930
	}
3931
3932
	/*
3933
	 * Registration flow:
3934
	 * 1 - ::admin_page_load() action=register
3935
	 * 2 - ::try_registration()
3936
	 * 3 - ::register()
3937
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3938
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3939
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3940
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3941
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3942
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3943
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3944
	 *       jetpack_id, jetpack_secret, jetpack_public
3945
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3946
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3947
	 * 5 - user logs in with WP.com account
3948
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3949
	 *		- Jetpack_Client_Server::authorize()
3950
	 *		- Jetpack_Client_Server::get_token()
3951
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3952
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3953
	 *			- which responds with access_token, token_type, scope
3954
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3955
	 *		- Jetpack::activate_default_modules()
3956
	 *     		- Deactivates deprecated plugins
3957
	 *     		- Activates all default modules
3958
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3959
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3960
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3961
	 *     Done!
3962
	 */
3963
3964
	/**
3965
	 * Handles the page load events for the Jetpack admin page
3966
	 */
3967
	function admin_page_load() {
3968
		$error = false;
3969
3970
		// Make sure we have the right body class to hook stylings for subpages off of.
3971
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3972
3973
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3974
			// Should only be used in intermediate redirects to preserve state across redirects
3975
			Jetpack::restate();
3976
		}
3977
3978
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3979
			// @todo: Add validation against a known whitelist
3980
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3981
			// User clicked in the iframe to link their accounts
3982
			if ( ! Jetpack::is_user_connected() ) {
3983
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3984
3985
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3986
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3987
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3988
3989
				if ( isset( $_GET['notes_iframe'] ) )
3990
					$connect_url .= '&notes_iframe';
3991
				wp_redirect( $connect_url );
3992
				exit;
3993
			} else {
3994
				if ( ! isset( $_GET['calypso_env'] ) ) {
3995
					Jetpack::state( 'message', 'already_authorized' );
3996
					wp_safe_redirect( Jetpack::admin_url() );
3997
					exit;
3998
				} else {
3999
					$connect_url = $this->build_connect_url( true, false, $from );
4000
					$connect_url .= '&already_authorized=true';
4001
					wp_redirect( $connect_url );
4002
					exit;
4003
				}
4004
			}
4005
		}
4006
4007
4008
		if ( isset( $_GET['action'] ) ) {
4009
			switch ( $_GET['action'] ) {
4010
			case 'authorize':
4011
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4012
					Jetpack::state( 'message', 'already_authorized' );
4013
					wp_safe_redirect( Jetpack::admin_url() );
4014
					exit;
4015
				}
4016
				Jetpack::log( 'authorize' );
4017
				$client_server = new Jetpack_Client_Server;
4018
				$client_server->client_authorize();
4019
				exit;
4020
			case 'register' :
4021
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4022
					$error = 'cheatin';
4023
					break;
4024
				}
4025
				check_admin_referer( 'jetpack-register' );
4026
				Jetpack::log( 'register' );
4027
				Jetpack::maybe_set_version_option();
4028
				$registered = Jetpack::try_registration();
4029
				if ( is_wp_error( $registered ) ) {
4030
					$error = $registered->get_error_code();
4031
					Jetpack::state( 'error', $error );
4032
					Jetpack::state( 'error', $registered->get_error_message() );
4033
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4034
						'error_code' => $error,
4035
						'error_message' => $registered->get_error_message()
4036
					) );
4037
					break;
4038
				}
4039
4040
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4041
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4042
4043
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4044
					'from' => $from
4045
				) );
4046
4047
				$url = $this->build_connect_url( true, $redirect, $from );
4048
4049
				if ( ! empty( $_GET['onboarding'] ) ) {
4050
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4051
				}
4052
4053
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4054
					$url = add_query_arg( 'auth_approved', 'true', $url );
4055
				}
4056
4057
				wp_redirect( $url );
4058
				exit;
4059
			case 'activate' :
4060
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4061
					$error = 'cheatin';
4062
					break;
4063
				}
4064
4065
				$module = stripslashes( $_GET['module'] );
4066
				check_admin_referer( "jetpack_activate-$module" );
4067
				Jetpack::log( 'activate', $module );
4068
				if ( ! Jetpack::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \Jetpack::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...
4069
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4070
				}
4071
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4072
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4073
				exit;
4074
			case 'activate_default_modules' :
4075
				check_admin_referer( 'activate_default_modules' );
4076
				Jetpack::log( 'activate_default_modules' );
4077
				Jetpack::restate();
4078
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4079
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4080
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4081
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4082
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4083
				exit;
4084
			case 'disconnect' :
4085
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4086
					$error = 'cheatin';
4087
					break;
4088
				}
4089
4090
				check_admin_referer( 'jetpack-disconnect' );
4091
				Jetpack::log( 'disconnect' );
4092
				Jetpack::disconnect();
4093
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4094
				exit;
4095
			case 'reconnect' :
4096
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4097
					$error = 'cheatin';
4098
					break;
4099
				}
4100
4101
				check_admin_referer( 'jetpack-reconnect' );
4102
				Jetpack::log( 'reconnect' );
4103
				$this->disconnect();
4104
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4105
				exit;
4106 View Code Duplication
			case 'deactivate' :
4107
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4108
					$error = 'cheatin';
4109
					break;
4110
				}
4111
4112
				$modules = stripslashes( $_GET['module'] );
4113
				check_admin_referer( "jetpack_deactivate-$modules" );
4114
				foreach ( explode( ',', $modules ) as $module ) {
4115
					Jetpack::log( 'deactivate', $module );
4116
					Jetpack::deactivate_module( $module );
4117
					Jetpack::state( 'message', 'module_deactivated' );
4118
				}
4119
				Jetpack::state( 'module', $modules );
4120
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4121
				exit;
4122
			case 'unlink' :
4123
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4124
				check_admin_referer( 'jetpack-unlink' );
4125
				Jetpack::log( 'unlink' );
4126
				$this->unlink_user();
4127
				Jetpack::state( 'message', 'unlinked' );
4128
				if ( 'sub-unlink' == $redirect ) {
4129
					wp_safe_redirect( admin_url() );
4130
				} else {
4131
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4132
				}
4133
				exit;
4134
			case 'onboard' :
4135
				if ( ! current_user_can( 'manage_options' ) ) {
4136
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4137
				} else {
4138
					Jetpack::create_onboarding_token();
4139
					$url = $this->build_connect_url( true );
4140
4141
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4142
						$url = add_query_arg( 'onboarding', $token, $url );
4143
					}
4144
4145
					$calypso_env = $this->get_calypso_env();
4146
					if ( ! empty( $calypso_env ) ) {
4147
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4148
					}
4149
4150
					wp_redirect( $url );
4151
					exit;
4152
				}
4153
				exit;
4154
			default:
4155
				/**
4156
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4157
				 *
4158
				 * @since 2.6.0
4159
				 *
4160
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4161
				 */
4162
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4163
			}
4164
		}
4165
4166
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4167
			self::activate_new_modules( true );
4168
		}
4169
4170
		$message_code = Jetpack::state( 'message' );
4171
		if ( Jetpack::state( 'optin-manage' ) ) {
4172
			$activated_manage = $message_code;
4173
			$message_code = 'jetpack-manage';
4174
		}
4175
4176
		switch ( $message_code ) {
4177
		case 'jetpack-manage':
4178
			$this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), 'https://wordpress.com/sites' ) . '</strong>';
4179
			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...
4180
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4181
			}
4182
			break;
4183
4184
		}
4185
4186
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4187
4188
		if ( ! empty( $deactivated_plugins ) ) {
4189
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4190
			$deactivated_titles  = array();
4191
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4192
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4193
					continue;
4194
				}
4195
4196
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4197
			}
4198
4199
			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...
4200
				if ( $this->message ) {
4201
					$this->message .= "<br /><br />\n";
4202
				}
4203
4204
				$this->message .= wp_sprintf(
4205
					_n(
4206
						'Jetpack contains the most recent version of the old %l plugin.',
4207
						'Jetpack contains the most recent versions of the old %l plugins.',
4208
						count( $deactivated_titles ),
4209
						'jetpack'
4210
					),
4211
					$deactivated_titles
4212
				);
4213
4214
				$this->message .= "<br />\n";
4215
4216
				$this->message .= _n(
4217
					'The old version has been deactivated and can be removed from your site.',
4218
					'The old versions have been deactivated and can be removed from your site.',
4219
					count( $deactivated_titles ),
4220
					'jetpack'
4221
				);
4222
			}
4223
		}
4224
4225
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4226
4227
		if ( $this->message || $this->error || $this->privacy_checks ) {
4228
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4229
		}
4230
4231
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4232
	}
4233
4234
	function admin_notices() {
4235
4236
		if ( $this->error ) {
4237
?>
4238
<div id="message" class="jetpack-message jetpack-err">
4239
	<div class="squeezer">
4240
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4241
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4242
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4243
<?php	endif; ?>
4244
	</div>
4245
</div>
4246
<?php
4247
		}
4248
4249
		if ( $this->message ) {
4250
?>
4251
<div id="message" class="jetpack-message">
4252
	<div class="squeezer">
4253
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4254
	</div>
4255
</div>
4256
<?php
4257
		}
4258
4259
		if ( $this->privacy_checks ) :
4260
			$module_names = $module_slugs = array();
4261
4262
			$privacy_checks = explode( ',', $this->privacy_checks );
4263
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4264
			foreach ( $privacy_checks as $module_slug ) {
4265
				$module = Jetpack::get_module( $module_slug );
4266
				if ( ! $module ) {
4267
					continue;
4268
				}
4269
4270
				$module_slugs[] = $module_slug;
4271
				$module_names[] = "<strong>{$module['name']}</strong>";
4272
			}
4273
4274
			$module_slugs = join( ',', $module_slugs );
4275
?>
4276
<div id="message" class="jetpack-message jetpack-err">
4277
	<div class="squeezer">
4278
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4279
		<p><?php
4280
			echo wp_kses(
4281
				wptexturize(
4282
					wp_sprintf(
4283
						_nx(
4284
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4285
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4286
							count( $privacy_checks ),
4287
							'%l = list of Jetpack module/feature names',
4288
							'jetpack'
4289
						),
4290
						$module_names
4291
					)
4292
				),
4293
				array( 'strong' => true )
4294
			);
4295
4296
			echo "\n<br />\n";
4297
4298
			echo wp_kses(
4299
				sprintf(
4300
					_nx(
4301
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4302
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4303
						count( $privacy_checks ),
4304
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4305
						'jetpack'
4306
					),
4307
					wp_nonce_url(
4308
						Jetpack::admin_url(
4309
							array(
4310
								'page'   => 'jetpack',
4311
								'action' => 'deactivate',
4312
								'module' => urlencode( $module_slugs ),
4313
							)
4314
						),
4315
						"jetpack_deactivate-$module_slugs"
4316
					),
4317
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4318
				),
4319
				array( 'a' => array( 'href' => true, 'title' => true ) )
4320
			);
4321
		?></p>
4322
	</div>
4323
</div>
4324
<?php endif;
4325
	}
4326
4327
	/**
4328
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4329
	 */
4330
	function stat( $group, $detail ) {
4331
		if ( ! isset( $this->stats[ $group ] ) )
4332
			$this->stats[ $group ] = array();
4333
		$this->stats[ $group ][] = $detail;
4334
	}
4335
4336
	/**
4337
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4338
	 */
4339
	function do_stats( $method = '' ) {
4340
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4341
			foreach ( $this->stats as $group => $stats ) {
4342
				if ( is_array( $stats ) && count( $stats ) ) {
4343
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4344
					if ( 'server_side' === $method ) {
4345
						self::do_server_side_stat( $args );
4346
					} else {
4347
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4348
					}
4349
				}
4350
				unset( $this->stats[ $group ] );
4351
			}
4352
		}
4353
	}
4354
4355
	/**
4356
	 * Runs stats code for a one-off, server-side.
4357
	 *
4358
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4359
	 *
4360
	 * @return bool If it worked.
4361
	 */
4362
	static function do_server_side_stat( $args ) {
4363
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4364
		if ( is_wp_error( $response ) )
4365
			return false;
4366
4367
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4368
			return false;
4369
4370
		return true;
4371
	}
4372
4373
	/**
4374
	 * Builds the stats url.
4375
	 *
4376
	 * @param $args array|string The arguments to append to the URL.
4377
	 *
4378
	 * @return string The URL to be pinged.
4379
	 */
4380
	static function build_stats_url( $args ) {
4381
		$defaults = array(
4382
			'v'    => 'wpcom2',
4383
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4384
		);
4385
		$args     = wp_parse_args( $args, $defaults );
4386
		/**
4387
		 * Filter the URL used as the Stats tracking pixel.
4388
		 *
4389
		 * @since 2.3.2
4390
		 *
4391
		 * @param string $url Base URL used as the Stats tracking pixel.
4392
		 */
4393
		$base_url = apply_filters(
4394
			'jetpack_stats_base_url',
4395
			'https://pixel.wp.com/g.gif'
4396
		);
4397
		$url      = add_query_arg( $args, $base_url );
4398
		return $url;
4399
	}
4400
4401
	static function translate_current_user_to_role() {
4402
		foreach ( self::$capability_translations as $role => $cap ) {
4403
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4404
				return $role;
4405
			}
4406
		}
4407
4408
		return false;
4409
	}
4410
4411
	static function translate_user_to_role( $user ) {
4412
		foreach ( self::$capability_translations as $role => $cap ) {
4413
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4414
				return $role;
4415
			}
4416
		}
4417
4418
		return false;
4419
    }
4420
4421
	static function translate_role_to_cap( $role ) {
4422
		if ( ! isset( self::$capability_translations[$role] ) ) {
4423
			return false;
4424
		}
4425
4426
		return self::$capability_translations[$role];
4427
	}
4428
4429
	static function sign_role( $role, $user_id = null ) {
4430
		if ( empty( $user_id ) ) {
4431
			$user_id = (int) get_current_user_id();
4432
		}
4433
4434
		if ( ! $user_id  ) {
4435
			return false;
4436
		}
4437
4438
		$token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4439
		if ( ! $token || is_wp_error( $token ) ) {
4440
			return false;
4441
		}
4442
4443
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4444
	}
4445
4446
4447
	/**
4448
	 * Builds a URL to the Jetpack connection auth page
4449
	 *
4450
	 * @since 3.9.5
4451
	 *
4452
	 * @param bool $raw If true, URL will not be escaped.
4453
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4454
	 *                              If string, will be a custom redirect.
4455
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4456
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4457
	 *
4458
	 * @return string Connect URL
4459
	 */
4460
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4461
		$site_id = Jetpack_Options::get_option( 'id' );
4462
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4463
4464
		if ( $register || ! $blog_token || ! $site_id ) {
4465
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4466
4467
			if ( ! empty( $redirect ) ) {
4468
				$url = add_query_arg(
4469
					'redirect',
4470
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4471
					$url
4472
				);
4473
			}
4474
4475
			if( is_network_admin() ) {
4476
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4477
			}
4478
		} else {
4479
4480
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4481
			// because otherwise this logic can get us in to a loop.
4482
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4483
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4484
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4485
4486
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4487
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4488
					'1.1'
4489
				);
4490
4491
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4492
4493
					// Generating a register URL instead to refresh the existing token
4494
					return $this->build_connect_url( $raw, $redirect, $from, true );
4495
				}
4496
			}
4497
4498
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4499
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4500
			}
4501
4502
			$role = self::translate_current_user_to_role();
4503
			$signed_role = self::sign_role( $role );
4504
4505
			$user = wp_get_current_user();
4506
4507
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4508
			$redirect = $redirect
4509
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4510
				: $jetpack_admin_page;
4511
4512
			if( isset( $_REQUEST['is_multisite'] ) ) {
4513
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4514
			}
4515
4516
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4517
4518
			/**
4519
			 * Filter the type of authorization.
4520
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4521
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4522
			 *
4523
			 * @since 4.3.3
4524
			 *
4525
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4526
			 */
4527
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4528
4529
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4530
4531
			$args = urlencode_deep(
4532
				array(
4533
					'response_type' => 'code',
4534
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4535
					'redirect_uri'  => add_query_arg(
4536
						array(
4537
							'action'   => 'authorize',
4538
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4539
							'redirect' => urlencode( $redirect ),
4540
						),
4541
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4542
					),
4543
					'state'         => $user->ID,
4544
					'scope'         => $signed_role,
4545
					'user_email'    => $user->user_email,
4546
					'user_login'    => $user->user_login,
4547
					'is_active'     => Jetpack::is_active(),
4548
					'jp_version'    => JETPACK__VERSION,
4549
					'auth_type'     => $auth_type,
4550
					'secret'        => $secrets['secret_1'],
4551
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4552
					'blogname'      => get_option( 'blogname' ),
4553
					'site_url'      => site_url(),
4554
					'home_url'      => home_url(),
4555
					'site_icon'     => get_site_icon_url(),
4556
					'site_lang'     => get_locale(),
4557
					'_ui'           => $tracks_identity['_ui'],
4558
					'_ut'           => $tracks_identity['_ut'],
4559
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4560
				)
4561
			);
4562
4563
			self::apply_activation_source_to_args( $args );
4564
4565
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4566
		}
4567
4568
		if ( $from ) {
4569
			$url = add_query_arg( 'from', $from, $url );
4570
		}
4571
4572
		// Ensure that class to get the affiliate code is loaded
4573
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4574
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4575
		}
4576
		// Get affiliate code and add it to the URL
4577
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4578
4579
		$calypso_env = $this->get_calypso_env();
4580
4581
		if ( ! empty( $calypso_env ) ) {
4582
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4583
		}
4584
4585
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4586
	}
4587
4588
	/**
4589
	 * Get our assumed site creation date.
4590
	 * Calculated based on the earlier date of either:
4591
	 * - Earliest admin user registration date.
4592
	 * - Earliest date of post of any post type.
4593
	 *
4594
	 * @since 7.2.0
4595
	 *
4596
	 * @return string Assumed site creation date and time.
4597
	 */
4598
	public static function get_assumed_site_creation_date() {
4599
		$earliest_registered_users = get_users( array(
4600
			'role'    => 'administrator',
4601
			'orderby' => 'user_registered',
4602
			'order'   => 'ASC',
4603
			'fields'  => array( 'user_registered' ),
4604
			'number'  => 1,
4605
		) );
4606
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4607
4608
		$earliest_posts = get_posts( array(
4609
			'posts_per_page' => 1,
4610
			'post_type'      => 'any',
4611
			'post_status'    => 'any',
4612
			'orderby'        => 'date',
4613
			'order'          => 'ASC',
4614
		) );
4615
4616
		// If there are no posts at all, we'll count only on user registration date.
4617
		if ( $earliest_posts ) {
4618
			$earliest_post_date = $earliest_posts[0]->post_date;
4619
		} else {
4620
			$earliest_post_date = PHP_INT_MAX;
4621
		}
4622
4623
		return min( $earliest_registration_date, $earliest_post_date );
4624
	}
4625
4626
	public static function apply_activation_source_to_args( &$args ) {
4627
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4628
4629
		if ( $activation_source_name ) {
4630
			$args['_as'] = urlencode( $activation_source_name );
4631
		}
4632
4633
		if ( $activation_source_keyword ) {
4634
			$args['_ak'] = urlencode( $activation_source_keyword );
4635
		}
4636
	}
4637
4638
	function build_reconnect_url( $raw = false ) {
4639
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4640
		return $raw ? $url : esc_url( $url );
4641
	}
4642
4643
	public static function admin_url( $args = null ) {
4644
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4645
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4646
		return $url;
4647
	}
4648
4649
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4650
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4651
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4652
	}
4653
4654
	function dismiss_jetpack_notice() {
4655
4656
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4657
			return;
4658
		}
4659
4660
		switch( $_GET['jetpack-notice'] ) {
4661
			case 'dismiss':
4662
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4663
4664
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4665
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4666
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4667
				}
4668
				break;
4669
			case 'jetpack-protect-multisite-opt-out':
4670
4671
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4672
					// Don't show the banner again
4673
4674
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4675
					// redirect back to the page that had the notice
4676
					if ( wp_get_referer() ) {
4677
						wp_safe_redirect( wp_get_referer() );
4678
					} else {
4679
						// Take me to Jetpack
4680
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4681
					}
4682
				}
4683
				break;
4684
		}
4685
	}
4686
4687
	public static function sort_modules( $a, $b ) {
4688
		if ( $a['sort'] == $b['sort'] )
4689
			return 0;
4690
4691
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4692
	}
4693
4694
	function ajax_recheck_ssl() {
4695
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4696
		$result = Jetpack::permit_ssl( true );
4697
		wp_send_json( array(
4698
			'enabled' => $result,
4699
			'message' => get_transient( 'jetpack_https_test_message' )
4700
		) );
4701
	}
4702
4703
/* Client API */
4704
4705
	/**
4706
	 * Returns the requested Jetpack API URL
4707
	 *
4708
	 * @return string
4709
	 */
4710
	public static function api_url( $relative_url ) {
4711
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4712
	}
4713
4714
	/**
4715
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4716
	 */
4717
	public static function fix_url_for_bad_hosts( $url ) {
4718
		if ( 0 !== strpos( $url, 'https://' ) ) {
4719
			return $url;
4720
		}
4721
4722
		switch ( JETPACK_CLIENT__HTTPS ) {
4723
			case 'ALWAYS' :
4724
				return $url;
4725
			case 'NEVER' :
4726
				return set_url_scheme( $url, 'http' );
4727
			// default : case 'AUTO' :
4728
		}
4729
4730
		// we now return the unmodified SSL URL by default, as a security precaution
4731
		return $url;
4732
	}
4733
4734
	/**
4735
	 * Create a random secret for validating onboarding payload
4736
	 *
4737
	 * @return string Secret token
4738
	 */
4739
	public static function create_onboarding_token() {
4740
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4741
			$token = wp_generate_password( 32, false );
4742
			Jetpack_Options::update_option( 'onboarding', $token );
4743
		}
4744
4745
		return $token;
4746
	}
4747
4748
	/**
4749
	 * Remove the onboarding token
4750
	 *
4751
	 * @return bool True on success, false on failure
4752
	 */
4753
	public static function invalidate_onboarding_token() {
4754
		return Jetpack_Options::delete_option( 'onboarding' );
4755
	}
4756
4757
	/**
4758
	 * Validate an onboarding token for a specific action
4759
	 *
4760
	 * @return boolean True if token/action pair is accepted, false if not
4761
	 */
4762
	public static function validate_onboarding_token_action( $token, $action ) {
4763
		// Compare tokens, bail if tokens do not match
4764
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4765
			return false;
4766
		}
4767
4768
		// List of valid actions we can take
4769
		$valid_actions = array(
4770
			'/jetpack/v4/settings',
4771
		);
4772
4773
		// Whitelist the action
4774
		if ( ! in_array( $action, $valid_actions ) ) {
4775
			return false;
4776
		}
4777
4778
		return true;
4779
	}
4780
4781
	/**
4782
	 * Checks to see if the URL is using SSL to connect with Jetpack
4783
	 *
4784
	 * @since 2.3.3
4785
	 * @return boolean
4786
	 */
4787
	public static function permit_ssl( $force_recheck = false ) {
4788
		// Do some fancy tests to see if ssl is being supported
4789
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4790
			$message = '';
4791
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4792
				$ssl = 0;
4793
			} else {
4794
				switch ( JETPACK_CLIENT__HTTPS ) {
4795
					case 'NEVER':
4796
						$ssl = 0;
4797
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4798
						break;
4799
					case 'ALWAYS':
4800
					case 'AUTO':
4801
					default:
4802
						$ssl = 1;
4803
						break;
4804
				}
4805
4806
				// If it's not 'NEVER', test to see
4807
				if ( $ssl ) {
4808
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4809
						$ssl = 0;
4810
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4811
					} else {
4812
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4813
						if ( is_wp_error( $response ) ) {
4814
							$ssl = 0;
4815
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4816
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4817
							$ssl = 0;
4818
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4819
						}
4820
					}
4821
				}
4822
			}
4823
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4824
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4825
		}
4826
4827
		return (bool) $ssl;
4828
	}
4829
4830
	/*
4831
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4832
	 */
4833
	public function alert_auto_ssl_fail() {
4834
		if ( ! current_user_can( 'manage_options' ) )
4835
			return;
4836
4837
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4838
		?>
4839
4840
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4841
			<div class="jp-banner__content">
4842
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4843
				<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>
4844
				<p>
4845
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4846
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4847
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4848
				</p>
4849
				<p>
4850
					<?php printf( __( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
4851
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4852
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4853
				</p>
4854
			</div>
4855
		</div>
4856
		<style>
4857
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4858
		</style>
4859
		<script type="text/javascript">
4860
			jQuery( document ).ready( function( $ ) {
4861
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4862
					var $this = $( this );
4863
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4864
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4865
					e.preventDefault();
4866
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4867
					$.post( ajaxurl, data )
4868
					  .done( function( response ) {
4869
					  	if ( response.enabled ) {
4870
					  		$( '#jetpack-ssl-warning' ).hide();
4871
					  	} else {
4872
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4873
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4874
					  	}
4875
					  }.bind( $this ) );
4876
				} );
4877
			} );
4878
		</script>
4879
4880
		<?php
4881
	}
4882
4883
	/**
4884
	 * Returns the Jetpack XML-RPC API
4885
	 *
4886
	 * @return string
4887
	 */
4888
	public static function xmlrpc_api_url() {
4889
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4890
		return untrailingslashit( $base ) . '/xmlrpc.php';
4891
	}
4892
4893
	public static function connection() {
4894
		return self::init()->connection_manager;
4895
	}
4896
4897
	/**
4898
	 * Creates two secret tokens and the end of life timestamp for them.
4899
	 *
4900
	 * Note these tokens are unique per call, NOT static per site for connecting.
4901
	 *
4902
	 * @since 2.6
4903
	 * @return array
4904
	 */
4905
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4906
		if ( false === $user_id ) {
4907
			$user_id = get_current_user_id();
4908
		}
4909
4910
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4911
	}
4912
4913
	public static function get_secrets( $action, $user_id ) {
4914
		$secrets = self::connection()->get_secrets( $action, $user_id );
4915
4916
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4917
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4918
		}
4919
4920
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4921
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4922
		}
4923
4924
		return $secrets;
4925
	}
4926
4927
	/**
4928
	 * @deprecated 7.5 Use Connection_Manager instead.
4929
	 *
4930
	 * @param $action
4931
	 * @param $user_id
4932
	 */
4933
	public static function delete_secrets( $action, $user_id ) {
4934
		return self::connection()->delete_secrets( $action, $user_id );
4935
	}
4936
4937
	/**
4938
	 * Builds the timeout limit for queries talking with the wpcom servers.
4939
	 *
4940
	 * Based on local php max_execution_time in php.ini
4941
	 *
4942
	 * @since 2.6
4943
	 * @return int
4944
	 * @deprecated
4945
	 **/
4946
	public function get_remote_query_timeout_limit() {
4947
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4948
		return Jetpack::get_max_execution_time();
4949
	}
4950
4951
	/**
4952
	 * Builds the timeout limit for queries talking with the wpcom servers.
4953
	 *
4954
	 * Based on local php max_execution_time in php.ini
4955
	 *
4956
	 * @since 5.4
4957
	 * @return int
4958
	 **/
4959
	public static function get_max_execution_time() {
4960
		$timeout = (int) ini_get( 'max_execution_time' );
4961
4962
		// Ensure exec time set in php.ini
4963
		if ( ! $timeout ) {
4964
			$timeout = 30;
4965
		}
4966
		return $timeout;
4967
	}
4968
4969
	/**
4970
	 * Sets a minimum request timeout, and returns the current timeout
4971
	 *
4972
	 * @since 5.4
4973
	 **/
4974
	public static function set_min_time_limit( $min_timeout ) {
4975
		$timeout = self::get_max_execution_time();
4976
		if ( $timeout < $min_timeout ) {
4977
			$timeout = $min_timeout;
4978
			set_time_limit( $timeout );
4979
		}
4980
		return $timeout;
4981
	}
4982
4983
4984
	/**
4985
	 * Takes the response from the Jetpack register new site endpoint and
4986
	 * verifies it worked properly.
4987
	 *
4988
	 * @since 2.6
4989
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4990
	 **/
4991
	public function validate_remote_register_response( $response ) {
4992
	  if ( is_wp_error( $response ) ) {
4993
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4994
		}
4995
4996
		$code   = wp_remote_retrieve_response_code( $response );
4997
		$entity = wp_remote_retrieve_body( $response );
4998
		if ( $entity )
4999
			$registration_response = json_decode( $entity );
5000
		else
5001
			$registration_response = false;
5002
5003
		$code_type = intval( $code / 100 );
5004
		if ( 5 == $code_type ) {
5005
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5006
		} elseif ( 408 == $code ) {
5007
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5008
		} elseif ( ! empty( $registration_response->error ) ) {
5009
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5010
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
5011
			} else {
5012
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5013
			}
5014
5015
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5016
		} elseif ( 200 != $code ) {
5017
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5018
		}
5019
5020
		// Jetpack ID error block
5021
		if ( empty( $registration_response->jetpack_id ) ) {
5022
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5023
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5024
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5025
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5026
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5027
		}
5028
5029
	    return $registration_response;
5030
	}
5031
	/**
5032
	 * @return bool|WP_Error
5033
	 */
5034
	public static function register() {
5035
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5036
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5037
		$secrets = Jetpack::generate_secrets( 'register' );
5038
5039 View Code Duplication
		if (
5040
			empty( $secrets['secret_1'] ) ||
5041
			empty( $secrets['secret_2'] ) ||
5042
			empty( $secrets['exp'] )
5043
		) {
5044
			return new Jetpack_Error( 'missing_secrets' );
5045
		}
5046
5047
		// better to try (and fail) to set a higher timeout than this system
5048
		// supports than to have register fail for more users than it should
5049
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5050
5051
		$gmt_offset = get_option( 'gmt_offset' );
5052
		if ( ! $gmt_offset ) {
5053
			$gmt_offset = 0;
5054
		}
5055
5056
		$stats_options = get_option( 'stats_options' );
5057
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5058
5059
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5060
5061
		$args = array(
5062
			'method'  => 'POST',
5063
			'body'    => array(
5064
				'siteurl'         => site_url(),
5065
				'home'            => home_url(),
5066
				'gmt_offset'      => $gmt_offset,
5067
				'timezone_string' => (string) get_option( 'timezone_string' ),
5068
				'site_name'       => (string) get_option( 'blogname' ),
5069
				'secret_1'        => $secrets['secret_1'],
5070
				'secret_2'        => $secrets['secret_2'],
5071
				'site_lang'       => get_locale(),
5072
				'timeout'         => $timeout,
5073
				'stats_id'        => $stats_id,
5074
				'state'           => get_current_user_id(),
5075
				'_ui'             => $tracks_identity['_ui'],
5076
				'_ut'             => $tracks_identity['_ut'],
5077
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5078
				'jetpack_version' => JETPACK__VERSION
5079
			),
5080
			'headers' => array(
5081
				'Accept' => 'application/json',
5082
			),
5083
			'timeout' => $timeout,
5084
		);
5085
5086
		self::apply_activation_source_to_args( $args['body'] );
5087
5088
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5089
5090
		// Make sure the response is valid and does not contain any Jetpack errors
5091
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5092
		if ( is_wp_error( $registration_details ) ) {
5093
			return $registration_details;
5094
		} elseif ( ! $registration_details ) {
5095
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5096
		}
5097
5098 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5099
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5100
		}
5101
5102
		if ( isset( $registration_details->jetpack_public ) ) {
5103
			$jetpack_public = (int) $registration_details->jetpack_public;
5104
		} else {
5105
			$jetpack_public = false;
5106
		}
5107
5108
		Jetpack_Options::update_options(
5109
			array(
5110
				'id'         => (int)    $registration_details->jetpack_id,
5111
				'blog_token' => (string) $registration_details->jetpack_secret,
5112
				'public'     => $jetpack_public,
5113
			)
5114
		);
5115
5116
		/**
5117
		 * Fires when a site is registered on WordPress.com.
5118
		 *
5119
		 * @since 3.7.0
5120
		 *
5121
		 * @param int $json->jetpack_id Jetpack Blog ID.
5122
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5123
		 * @param int|bool $jetpack_public Is the site public.
5124
		 */
5125
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5126
5127
		// Initialize Jump Start for the first and only time.
5128
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5129
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5130
5131
			$jetpack = Jetpack::init();
5132
5133
			$jetpack->stat( 'jumpstart', 'unique-views' );
5134
			$jetpack->do_stats( 'server_side' );
5135
		};
5136
5137
		return true;
5138
	}
5139
5140
	/**
5141
	 * If the db version is showing something other that what we've got now, bump it to current.
5142
	 *
5143
	 * @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...
5144
	 */
5145
	public static function maybe_set_version_option() {
5146
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5147
		if ( JETPACK__VERSION != $version ) {
5148
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5149
5150
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5151
				/** This action is documented in class.jetpack.php */
5152
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5153
			}
5154
5155
			return true;
5156
		}
5157
		return false;
5158
	}
5159
5160
/* Client Server API */
5161
5162
	/**
5163
	 * Loads the Jetpack XML-RPC client
5164
	 */
5165
	public static function load_xml_rpc_client() {
5166
		require_once ABSPATH . WPINC . '/class-IXR.php';
5167
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5168
	}
5169
5170
	/**
5171
	 * Resets the saved authentication state in between testing requests.
5172
	 */
5173
	public function reset_saved_auth_state() {
5174
		$this->xmlrpc_verification = null;
5175
		$this->rest_authentication_status = null;
5176
	}
5177
5178
	function verify_xml_rpc_signature() {
5179
		if ( $this->xmlrpc_verification ) {
5180
			return $this->xmlrpc_verification;
5181
		}
5182
5183
		// It's not for us
5184
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5185
			return false;
5186
		}
5187
5188
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
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...
5189
		if (
5190
			empty( $token_key )
5191
		||
5192
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5193
		) {
5194
			return false;
5195
		}
5196
5197
		if ( '0' === $user_id ) {
5198
			$token_type = 'blog';
5199
			$user_id = 0;
5200
		} else {
5201
			$token_type = 'user';
5202
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5203
				return false;
5204
			}
5205
			$user_id = (int) $user_id;
5206
5207
			$user = new WP_User( $user_id );
5208
			if ( ! $user || ! $user->exists() ) {
5209
				return false;
5210
			}
5211
		}
5212
5213
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
0 ignored issues
show
Documentation introduced by
$user_id 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...
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
5214
		if ( ! $token ) {
5215
			return false;
5216
		}
5217
5218
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5219
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5220
			$post_data   = $_POST;
5221
			$file_hashes = array();
5222
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5223
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5224
					continue;
5225
				}
5226
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5227
				$file_hashes[$post_data_key] = $post_data_value;
5228
			}
5229
5230
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5231
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5232
				$post_data[$post_data_key] = $post_data_value;
5233
			}
5234
5235
			ksort( $post_data );
5236
5237
			$body = http_build_query( stripslashes_deep( $post_data ) );
5238
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5239
			$body = file_get_contents( 'php://input' );
5240
		} else {
5241
			$body = null;
5242
		}
5243
5244
		$signature = $jetpack_signature->sign_current_request(
5245
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5246
		);
5247
5248
		if ( ! $signature ) {
5249
			return false;
5250
		} else if ( is_wp_error( $signature ) ) {
5251
			return $signature;
5252
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5253
			return false;
5254
		}
5255
5256
		$timestamp = (int) $_GET['timestamp'];
5257
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5258
5259
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5260
			return false;
5261
		}
5262
5263
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5264
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5265
			if ( ! empty( $_GET['onboarding'] ) ) {
5266
				$jpo = $_GET;
5267
			} else {
5268
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5269
			}
5270
5271
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5272
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5273
5274
			if (
5275
				isset( $jpo_user ) && isset( $jpo_token ) &&
5276
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5277
				isset( $_GET['rest_route'] ) &&
5278
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5279
			) {
5280
				$jpUser = get_user_by( 'email', $jpo_user );
5281
				if ( is_a( $jpUser, 'WP_User' ) ) {
5282
					wp_set_current_user( $jpUser->ID );
5283
					$user_can = is_multisite()
5284
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5285
						: current_user_can( 'manage_options' );
5286
					if ( $user_can ) {
5287
						$token_type = 'user';
5288
						$token->external_user_id = $jpUser->ID;
5289
					}
5290
				}
5291
			}
5292
		}
5293
5294
		$this->xmlrpc_verification = array(
5295
			'type'      => $token_type,
5296
			'token_key' => $token_key,
5297
			'user_id'   => $token->external_user_id,
5298
		);
5299
5300
		return $this->xmlrpc_verification;
5301
	}
5302
5303
	/**
5304
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5305
	 */
5306
	function authenticate_jetpack( $user, $username, $password ) {
5307
		if ( is_a( $user, 'WP_User' ) ) {
5308
			return $user;
5309
		}
5310
5311
		$token_details = $this->verify_xml_rpc_signature();
5312
5313
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5314
			return $user;
5315
		}
5316
5317
		if ( 'user' !== $token_details['type'] ) {
5318
			return $user;
5319
		}
5320
5321
		if ( ! $token_details['user_id'] ) {
5322
			return $user;
5323
		}
5324
5325
		nocache_headers();
5326
5327
		return new WP_User( $token_details['user_id'] );
5328
	}
5329
5330
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5331
	// Uses the existing XMLRPC request signing implementation.
5332
	function wp_rest_authenticate( $user ) {
5333
		if ( ! empty( $user ) ) {
5334
			// Another authentication method is in effect.
5335
			return $user;
5336
		}
5337
5338
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5339
			// Nothing to do for this authentication method.
5340
			return null;
5341
		}
5342
5343
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5344
			// Nothing to do for this authentication method.
5345
			return null;
5346
		}
5347
5348
		// Ensure that we always have the request body available.  At this
5349
		// point, the WP REST API code to determine the request body has not
5350
		// run yet.  That code may try to read from 'php://input' later, but
5351
		// this can only be done once per request in PHP versions prior to 5.6.
5352
		// So we will go ahead and perform this read now if needed, and save
5353
		// the request body where both the Jetpack signature verification code
5354
		// and the WP REST API code can see it.
5355
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5356
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5357
		}
5358
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5359
5360
		// Only support specific request parameters that have been tested and
5361
		// are known to work with signature verification.  A different method
5362
		// can be passed to the WP REST API via the '?_method=' parameter if
5363
		// needed.
5364
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5365
			$this->rest_authentication_status = new WP_Error(
5366
				'rest_invalid_request',
5367
				__( 'This request method is not supported.', 'jetpack' ),
5368
				array( 'status' => 400 )
5369
			);
5370
			return null;
5371
		}
5372
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5373
			$this->rest_authentication_status = new WP_Error(
5374
				'rest_invalid_request',
5375
				__( 'This request method does not support body parameters.', 'jetpack' ),
5376
				array( 'status' => 400 )
5377
			);
5378
			return null;
5379
		}
5380
5381
		$verified = $this->verify_xml_rpc_signature();
5382
5383
		if ( is_wp_error( $verified ) ) {
5384
			$this->rest_authentication_status = $verified;
5385
			return null;
5386
		}
5387
5388
		if (
5389
			$verified &&
5390
			isset( $verified['type'] ) &&
5391
			'user' === $verified['type'] &&
5392
			! empty( $verified['user_id'] )
5393
		) {
5394
			// Authentication successful.
5395
			$this->rest_authentication_status = true;
5396
			return $verified['user_id'];
5397
		}
5398
5399
		// Something else went wrong.  Probably a signature error.
5400
		$this->rest_authentication_status = new WP_Error(
5401
			'rest_invalid_signature',
5402
			__( 'The request is not signed correctly.', 'jetpack' ),
5403
			array( 'status' => 400 )
5404
		);
5405
		return null;
5406
	}
5407
5408
	/**
5409
	 * Report authentication status to the WP REST API.
5410
	 *
5411
	 * @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...
5412
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5413
	 */
5414
	public function wp_rest_authentication_errors( $value ) {
5415
		if ( $value !== null ) {
5416
			return $value;
5417
		}
5418
		return $this->rest_authentication_status;
5419
	}
5420
5421
	function add_nonce( $timestamp, $nonce ) {
5422
		global $wpdb;
5423
		static $nonces_used_this_request = array();
5424
5425
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5426
			return $nonces_used_this_request["$timestamp:$nonce"];
5427
		}
5428
5429
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5430
		$timestamp = (int) $timestamp;
5431
		$nonce     = esc_sql( $nonce );
5432
5433
		// Raw query so we can avoid races: add_option will also update
5434
		$show_errors = $wpdb->show_errors( false );
5435
5436
		$old_nonce = $wpdb->get_row(
5437
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5438
		);
5439
5440
		if ( is_null( $old_nonce ) ) {
5441
			$return = $wpdb->query(
5442
				$wpdb->prepare(
5443
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5444
					"jetpack_nonce_{$timestamp}_{$nonce}",
5445
					time(),
5446
					'no'
5447
				)
5448
			);
5449
		} else {
5450
			$return = false;
5451
		}
5452
5453
		$wpdb->show_errors( $show_errors );
5454
5455
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5456
5457
		return $return;
5458
	}
5459
5460
	/**
5461
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5462
	 * Capture it here so we can verify the signature later.
5463
	 */
5464
	function xmlrpc_methods( $methods ) {
5465
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5466
		return $methods;
5467
	}
5468
5469
	function public_xmlrpc_methods( $methods ) {
5470
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5471
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5472
		}
5473
		return $methods;
5474
	}
5475
5476
	function jetpack_getOptions( $args ) {
5477
		global $wp_xmlrpc_server;
5478
5479
		$wp_xmlrpc_server->escape( $args );
5480
5481
		$username	= $args[1];
5482
		$password	= $args[2];
5483
5484
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5485
			return $wp_xmlrpc_server->error;
5486
		}
5487
5488
		$options = array();
5489
		$user_data = $this->get_connected_user_data();
5490
		if ( is_array( $user_data ) ) {
5491
			$options['jetpack_user_id'] = array(
5492
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5493
				'readonly'      => true,
5494
				'value'         => $user_data['ID'],
5495
			);
5496
			$options['jetpack_user_login'] = array(
5497
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5498
				'readonly'      => true,
5499
				'value'         => $user_data['login'],
5500
			);
5501
			$options['jetpack_user_email'] = array(
5502
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5503
				'readonly'      => true,
5504
				'value'         => $user_data['email'],
5505
			);
5506
			$options['jetpack_user_site_count'] = array(
5507
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5508
				'readonly'      => true,
5509
				'value'         => $user_data['site_count'],
5510
			);
5511
		}
5512
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5513
		$args = stripslashes_deep( $args );
5514
		return $wp_xmlrpc_server->wp_getOptions( $args );
5515
	}
5516
5517
	function xmlrpc_options( $options ) {
5518
		$jetpack_client_id = false;
5519
		if ( self::is_active() ) {
5520
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5521
		}
5522
		$options['jetpack_version'] = array(
5523
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5524
				'readonly'      => true,
5525
				'value'         => JETPACK__VERSION,
5526
		);
5527
5528
		$options['jetpack_client_id'] = array(
5529
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5530
				'readonly'      => true,
5531
				'value'         => $jetpack_client_id,
5532
		);
5533
		return $options;
5534
	}
5535
5536
	public static function clean_nonces( $all = false ) {
5537
		global $wpdb;
5538
5539
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5540
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5541
5542
		if ( true !== $all ) {
5543
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5544
			$sql_args[] = time() - 3600;
5545
		}
5546
5547
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5548
5549
		$sql = $wpdb->prepare( $sql, $sql_args );
5550
5551
		for ( $i = 0; $i < 1000; $i++ ) {
5552
			if ( ! $wpdb->query( $sql ) ) {
5553
				break;
5554
			}
5555
		}
5556
	}
5557
5558
	/**
5559
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5560
	 * SET: state( $key, $value );
5561
	 * GET: $value = state( $key );
5562
	 *
5563
	 * @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...
5564
	 * @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...
5565
	 * @param bool $restate private
5566
	 */
5567
	public static function state( $key = null, $value = null, $restate = false ) {
5568
		static $state = array();
5569
		static $path, $domain;
5570
		if ( ! isset( $path ) ) {
5571
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5572
			$admin_url = Jetpack::admin_url();
5573
			$bits      = wp_parse_url( $admin_url );
5574
5575
			if ( is_array( $bits ) ) {
5576
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5577
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5578
			} else {
5579
				$path = $domain = null;
5580
			}
5581
		}
5582
5583
		// Extract state from cookies and delete cookies
5584
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5585
			$yum = $_COOKIE[ 'jetpackState' ];
5586
			unset( $_COOKIE[ 'jetpackState' ] );
5587
			foreach ( $yum as $k => $v ) {
5588
				if ( strlen( $v ) )
5589
					$state[ $k ] = $v;
5590
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5591
			}
5592
		}
5593
5594
		if ( $restate ) {
5595
			foreach ( $state as $k => $v ) {
5596
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5597
			}
5598
			return;
5599
		}
5600
5601
		// Get a state variable
5602
		if ( isset( $key ) && ! isset( $value ) ) {
5603
			if ( array_key_exists( $key, $state ) )
5604
				return $state[ $key ];
5605
			return null;
5606
		}
5607
5608
		// Set a state variable
5609
		if ( isset ( $key ) && isset( $value ) ) {
5610
			if( is_array( $value ) && isset( $value[0] ) ) {
5611
				$value = $value[0];
5612
			}
5613
			$state[ $key ] = $value;
5614
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5615
		}
5616
	}
5617
5618
	public static function restate() {
5619
		Jetpack::state( null, null, true );
5620
	}
5621
5622
	public static function check_privacy( $file ) {
5623
		static $is_site_publicly_accessible = null;
5624
5625
		if ( is_null( $is_site_publicly_accessible ) ) {
5626
			$is_site_publicly_accessible = false;
5627
5628
			Jetpack::load_xml_rpc_client();
5629
			$rpc = new Jetpack_IXR_Client();
5630
5631
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5632
			if ( $success ) {
5633
				$response = $rpc->getResponse();
5634
				if ( $response ) {
5635
					$is_site_publicly_accessible = true;
5636
				}
5637
			}
5638
5639
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5640
		}
5641
5642
		if ( $is_site_publicly_accessible ) {
5643
			return;
5644
		}
5645
5646
		$module_slug = self::get_module_slug( $file );
5647
5648
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5649
		if ( ! $privacy_checks ) {
5650
			$privacy_checks = $module_slug;
5651
		} else {
5652
			$privacy_checks .= ",$module_slug";
5653
		}
5654
5655
		Jetpack::state( 'privacy_checks', $privacy_checks );
5656
	}
5657
5658
	/**
5659
	 * Helper method for multicall XMLRPC.
5660
	 */
5661
	public static function xmlrpc_async_call() {
5662
		global $blog_id;
5663
		static $clients = array();
5664
5665
		$client_blog_id = is_multisite() ? $blog_id : 0;
5666
5667
		if ( ! isset( $clients[$client_blog_id] ) ) {
5668
			Jetpack::load_xml_rpc_client();
5669
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5670
			if ( function_exists( 'ignore_user_abort' ) ) {
5671
				ignore_user_abort( true );
5672
			}
5673
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5674
		}
5675
5676
		$args = func_get_args();
5677
5678
		if ( ! empty( $args[0] ) ) {
5679
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5680
		} elseif ( is_multisite() ) {
5681
			foreach ( $clients as $client_blog_id => $client ) {
5682
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5683
					continue;
5684
				}
5685
5686
				$switch_success = switch_to_blog( $client_blog_id, true );
5687
				if ( ! $switch_success ) {
5688
					continue;
5689
				}
5690
5691
				flush();
5692
				$client->query();
5693
5694
				restore_current_blog();
5695
			}
5696
		} else {
5697
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5698
				flush();
5699
				$clients[0]->query();
5700
			}
5701
		}
5702
	}
5703
5704
	public static function staticize_subdomain( $url ) {
5705
5706
		// Extract hostname from URL
5707
		$host = parse_url( $url, PHP_URL_HOST );
5708
5709
		// Explode hostname on '.'
5710
		$exploded_host = explode( '.', $host );
5711
5712
		// Retrieve the name and TLD
5713
		if ( count( $exploded_host ) > 1 ) {
5714
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5715
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5716
			// Rebuild domain excluding subdomains
5717
			$domain = $name . '.' . $tld;
5718
		} else {
5719
			$domain = $host;
5720
		}
5721
		// Array of Automattic domains
5722
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5723
5724
		// Return $url if not an Automattic domain
5725
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5726
			return $url;
5727
		}
5728
5729
		if ( is_ssl() ) {
5730
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5731
		}
5732
5733
		srand( crc32( basename( $url ) ) );
5734
		$static_counter = rand( 0, 2 );
5735
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5736
5737
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5738
	}
5739
5740
/* JSON API Authorization */
5741
5742
	/**
5743
	 * Handles the login action for Authorizing the JSON API
5744
	 */
5745
	function login_form_json_api_authorization() {
5746
		$this->verify_json_api_authorization_request();
5747
5748
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5749
5750
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5751
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5752
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5753
	}
5754
5755
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5756
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5757
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5758
			return $url;
5759
		}
5760
5761
		$parsed_url = parse_url( $url );
5762
		$url = strtok( $url, '?' );
5763
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5764
		if ( ! empty( $parsed_url['query'] ) )
5765
			$url .= "&{$parsed_url['query']}";
5766
5767
		return $url;
5768
	}
5769
5770
	// Make sure the POSTed request is handled by the same action
5771
	function preserve_action_in_login_form_for_json_api_authorization() {
5772
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5773
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5774
	}
5775
5776
	// If someone logs in to approve API access, store the Access Code in usermeta
5777
	function store_json_api_authorization_token( $user_login, $user ) {
5778
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5779
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5780
		$token = wp_generate_password( 32, false );
5781
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5782
	}
5783
5784
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5785
	function allow_wpcom_public_api_domain( $domains ) {
5786
		$domains[] = 'public-api.wordpress.com';
5787
		return $domains;
5788
	}
5789
5790
	static function is_redirect_encoded( $redirect_url ) {
5791
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5792
	}
5793
5794
	// Add all wordpress.com environments to the safe redirect whitelist
5795
	function allow_wpcom_environments( $domains ) {
5796
		$domains[] = 'wordpress.com';
5797
		$domains[] = 'wpcalypso.wordpress.com';
5798
		$domains[] = 'horizon.wordpress.com';
5799
		$domains[] = 'calypso.localhost';
5800
		return $domains;
5801
	}
5802
5803
	// Add the Access Code details to the public-api.wordpress.com redirect
5804
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5805
		return add_query_arg(
5806
			urlencode_deep(
5807
				array(
5808
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5809
					'jetpack-user-id' => (int) $user->ID,
5810
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5811
				)
5812
			),
5813
			$redirect_to
5814
		);
5815
	}
5816
5817
5818
	/**
5819
	 * Verifies the request by checking the signature
5820
	 *
5821
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5822
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5823
	 *
5824
	 * @param null|array $environment
5825
	 */
5826
	function verify_json_api_authorization_request( $environment = null ) {
5827
		$environment = is_null( $environment )
5828
			? $_REQUEST
5829
			: $environment;
5830
5831
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

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

Loading history...
5833
		if ( ! $token || empty( $token->secret ) ) {
5834
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5835
		}
5836
5837
		$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' );
5838
5839
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5840
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5841
			JetpackTracking::record_user_event( 'error_double_encode' );
5842
5843
			$die_error = sprintf(
5844
				/* translators: %s is a URL */
5845
				__( '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' ),
5846
				'https://jetpack.com/support/double-encoding/'
5847
			);
5848
		}
5849
5850
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5851
5852
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5853
			$signature = $jetpack_signature->sign_request(
5854
				$environment['token'],
5855
				$environment['timestamp'],
5856
				$environment['nonce'],
5857
				'',
5858
				'GET',
5859
				$environment['jetpack_json_api_original_query'],
5860
				null,
5861
				true
5862
			);
5863
		} else {
5864
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5865
		}
5866
5867
		if ( ! $signature ) {
5868
			wp_die( $die_error );
5869
		} else if ( is_wp_error( $signature ) ) {
5870
			wp_die( $die_error );
5871
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5872
			if ( is_ssl() ) {
5873
				// 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
5874
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5875
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5876
					wp_die( $die_error );
5877
				}
5878
			} else {
5879
				wp_die( $die_error );
5880
			}
5881
		}
5882
5883
		$timestamp = (int) $environment['timestamp'];
5884
		$nonce     = stripslashes( (string) $environment['nonce'] );
5885
5886
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5887
			// De-nonce the nonce, at least for 5 minutes.
5888
			// 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)
5889
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5890
			if ( $old_nonce_time < time() - 300 ) {
5891
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5892
			}
5893
		}
5894
5895
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5896
		$data_filters = array(
5897
			'state'        => 'opaque',
5898
			'client_id'    => 'int',
5899
			'client_title' => 'string',
5900
			'client_image' => 'url',
5901
		);
5902
5903
		foreach ( $data_filters as $key => $sanitation ) {
5904
			if ( ! isset( $data->$key ) ) {
5905
				wp_die( $die_error );
5906
			}
5907
5908
			switch ( $sanitation ) {
5909
			case 'int' :
5910
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5911
				break;
5912
			case 'opaque' :
5913
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5914
				break;
5915
			case 'string' :
5916
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5917
				break;
5918
			case 'url' :
5919
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5920
				break;
5921
			}
5922
		}
5923
5924
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5925
			wp_die( $die_error );
5926
		}
5927
	}
5928
5929
	function login_message_json_api_authorization( $message ) {
5930
		return '<p class="message">' . sprintf(
5931
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5932
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5933
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5934
	}
5935
5936
	/**
5937
	 * Get $content_width, but with a <s>twist</s> filter.
5938
	 */
5939
	public static function get_content_width() {
5940
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5941
			? $GLOBALS['content_width']
5942
			: false;
5943
		/**
5944
		 * Filter the Content Width value.
5945
		 *
5946
		 * @since 2.2.3
5947
		 *
5948
		 * @param string $content_width Content Width value.
5949
		 */
5950
		return apply_filters( 'jetpack_content_width', $content_width );
5951
	}
5952
5953
	/**
5954
	 * Pings the WordPress.com Mirror Site for the specified options.
5955
	 *
5956
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5957
	 *
5958
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5959
	 */
5960
	public function get_cloud_site_options( $option_names ) {
5961
		$option_names = array_filter( (array) $option_names, 'is_string' );
5962
5963
		Jetpack::load_xml_rpc_client();
5964
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5965
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5966
		if ( $xml->isError() ) {
5967
			return array(
5968
				'error_code' => $xml->getErrorCode(),
5969
				'error_msg'  => $xml->getErrorMessage(),
5970
			);
5971
		}
5972
		$cloud_site_options = $xml->getResponse();
5973
5974
		return $cloud_site_options;
5975
	}
5976
5977
	/**
5978
	 * Checks if the site is currently in an identity crisis.
5979
	 *
5980
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5981
	 */
5982
	public static function check_identity_crisis() {
5983
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5984
			return false;
5985
		}
5986
5987
		return Jetpack_Options::get_option( 'sync_error_idc' );
5988
	}
5989
5990
	/**
5991
	 * Checks whether the home and siteurl specifically are whitelisted
5992
	 * Written so that we don't have re-check $key and $value params every time
5993
	 * we want to check if this site is whitelisted, for example in footer.php
5994
	 *
5995
	 * @since  3.8.0
5996
	 * @return bool True = already whitelisted False = not whitelisted
5997
	 */
5998
	public static function is_staging_site() {
5999
		$is_staging = false;
6000
6001
		$known_staging = array(
6002
			'urls' => array(
6003
				'#\.staging\.wpengine\.com$#i', // WP Engine
6004
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6005
				),
6006
			'constants' => array(
6007
				'IS_WPE_SNAPSHOT',      // WP Engine
6008
				'KINSTA_DEV_ENV',       // Kinsta.com
6009
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6010
				'JETPACK_STAGING_MODE', // Generic
6011
				)
6012
			);
6013
		/**
6014
		 * Filters the flags of known staging sites.
6015
		 *
6016
		 * @since 3.9.0
6017
		 *
6018
		 * @param array $known_staging {
6019
		 *     An array of arrays that each are used to check if the current site is staging.
6020
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6021
		 *     @type array $constants PHP constants of known staging/developement environments.
6022
		 *  }
6023
		 */
6024
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6025
6026
		if ( isset( $known_staging['urls'] ) ) {
6027
			foreach ( $known_staging['urls'] as $url ){
6028
				if ( preg_match( $url, site_url() ) ) {
6029
					$is_staging = true;
6030
					break;
6031
				}
6032
			}
6033
		}
6034
6035
		if ( isset( $known_staging['constants'] ) ) {
6036
			foreach ( $known_staging['constants'] as $constant ) {
6037
				if ( defined( $constant ) && constant( $constant ) ) {
6038
					$is_staging = true;
6039
				}
6040
			}
6041
		}
6042
6043
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6044
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6045
			$is_staging = true;
6046
		}
6047
6048
		/**
6049
		 * Filters is_staging_site check.
6050
		 *
6051
		 * @since 3.9.0
6052
		 *
6053
		 * @param bool $is_staging If the current site is a staging site.
6054
		 */
6055
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6056
	}
6057
6058
	/**
6059
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6060
	 *
6061
	 * @since 4.4.0
6062
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6063
	 *
6064
	 * @return bool
6065
	 */
6066
	public static function validate_sync_error_idc_option() {
6067
		$is_valid = false;
6068
6069
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6070
		if ( false === $idc_allowed ) {
6071
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6072
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6073
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6074
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6075
				$transient_duration = HOUR_IN_SECONDS;
6076
			} else {
6077
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6078
				$idc_allowed = '1';
6079
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6080
			}
6081
6082
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6083
		}
6084
6085
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6086
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6087
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6088
			$local_options = self::get_sync_error_idc_option();
6089
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6090
				$is_valid = true;
6091
			}
6092
		}
6093
6094
		/**
6095
		 * Filters whether the sync_error_idc option is valid.
6096
		 *
6097
		 * @since 4.4.0
6098
		 *
6099
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6100
		 */
6101
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6102
6103
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6104
			// Since the option exists, and did not validate, delete it
6105
			Jetpack_Options::delete_option( 'sync_error_idc' );
6106
		}
6107
6108
		return $is_valid;
6109
	}
6110
6111
	/**
6112
	 * Normalizes a url by doing three things:
6113
	 *  - Strips protocol
6114
	 *  - Strips www
6115
	 *  - Adds a trailing slash
6116
	 *
6117
	 * @since 4.4.0
6118
	 * @param string $url
6119
	 * @return WP_Error|string
6120
	 */
6121
	public static function normalize_url_protocol_agnostic( $url ) {
6122
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6123
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6124
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6125
		}
6126
6127
		// Strip www and protocols
6128
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6129
		return $url;
6130
	}
6131
6132
	/**
6133
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6134
	 *
6135
	 * @since 4.4.0
6136
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6137
	 *
6138
	 * @param array $response
6139
	 * @return array Array of the local urls, wpcom urls, and error code
6140
	 */
6141
	public static function get_sync_error_idc_option( $response = array() ) {
6142
		// Since the local options will hit the database directly, store the values
6143
		// in a transient to allow for autoloading and caching on subsequent views.
6144
		$local_options = get_transient( 'jetpack_idc_local' );
6145
		if ( false === $local_options ) {
6146
			$local_options = array(
6147
				'home'    => Jetpack_Sync_Functions::home_url(),
6148
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6149
			);
6150
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6151
		}
6152
6153
		$options = array_merge( $local_options, $response );
6154
6155
		$returned_values = array();
6156
		foreach( $options as $key => $option ) {
6157
			if ( 'error_code' === $key ) {
6158
				$returned_values[ $key ] = $option;
6159
				continue;
6160
			}
6161
6162
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6163
				continue;
6164
			}
6165
6166
			$returned_values[ $key ] = $normalized_url;
6167
		}
6168
6169
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6170
6171
		return $returned_values;
6172
	}
6173
6174
	/**
6175
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6176
	 * If set to true, the site will be put into staging mode.
6177
	 *
6178
	 * @since 4.3.2
6179
	 * @return bool
6180
	 */
6181
	public static function sync_idc_optin() {
6182
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6183
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6184
		} else {
6185
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6186
		}
6187
6188
		/**
6189
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6190
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6191
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6192
		 *
6193
		 * @since 4.3.2
6194
		 *
6195
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6196
		 */
6197
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6198
	}
6199
6200
	/**
6201
	 * Maybe Use a .min.css stylesheet, maybe not.
6202
	 *
6203
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6204
	 */
6205
	public static function maybe_min_asset( $url, $path, $plugin ) {
6206
		// Short out on things trying to find actual paths.
6207
		if ( ! $path || empty( $plugin ) ) {
6208
			return $url;
6209
		}
6210
6211
		$path = ltrim( $path, '/' );
6212
6213
		// Strip out the abspath.
6214
		$base = dirname( plugin_basename( $plugin ) );
6215
6216
		// Short out on non-Jetpack assets.
6217
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6218
			return $url;
6219
		}
6220
6221
		// File name parsing.
6222
		$file              = "{$base}/{$path}";
6223
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6224
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6225
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6226
		$extension         = array_shift( $file_name_parts_r );
6227
6228
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6229
			// Already pointing at the minified version.
6230
			if ( 'min' === $file_name_parts_r[0] ) {
6231
				return $url;
6232
			}
6233
6234
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6235
			if ( file_exists( $min_full_path ) ) {
6236
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6237
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6238
				if ( 'css' === $extension ) {
6239
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6240
					self::$min_assets[ $key ] = $path;
6241
				}
6242
			}
6243
		}
6244
6245
		return $url;
6246
	}
6247
6248
	/**
6249
	 * If the asset is minified, let's flag .min as the suffix.
6250
	 *
6251
	 * Attached to `style_loader_src` filter.
6252
	 *
6253
	 * @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...
6254
	 * @param string $handle The registered handle of the script in question.
6255
	 * @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...
6256
	 */
6257
	public static function set_suffix_on_min( $src, $handle ) {
6258
		if ( false === strpos( $src, '.min.css' ) ) {
6259
			return $src;
6260
		}
6261
6262
		if ( ! empty( self::$min_assets ) ) {
6263
			foreach ( self::$min_assets as $file => $path ) {
6264
				if ( false !== strpos( $src, $file ) ) {
6265
					wp_style_add_data( $handle, 'suffix', '.min' );
6266
					return $src;
6267
				}
6268
			}
6269
		}
6270
6271
		return $src;
6272
	}
6273
6274
	/**
6275
	 * Maybe inlines a stylesheet.
6276
	 *
6277
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6278
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6279
	 *
6280
	 * Attached to `style_loader_tag` filter.
6281
	 *
6282
	 * @param string $tag The tag that would link to the external asset.
6283
	 * @param string $handle The registered handle of the script in question.
6284
	 *
6285
	 * @return string
6286
	 */
6287
	public static function maybe_inline_style( $tag, $handle ) {
6288
		global $wp_styles;
6289
		$item = $wp_styles->registered[ $handle ];
6290
6291
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6292
			return $tag;
6293
		}
6294
6295
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6296
			$href = $matches[1];
6297
			// Strip off query string
6298
			if ( $pos = strpos( $href, '?' ) ) {
6299
				$href = substr( $href, 0, $pos );
6300
			}
6301
			// Strip off fragment
6302
			if ( $pos = strpos( $href, '#' ) ) {
6303
				$href = substr( $href, 0, $pos );
6304
			}
6305
		} else {
6306
			return $tag;
6307
		}
6308
6309
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6310
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6311
			return $tag;
6312
		}
6313
6314
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6315
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6316
			// And this isn't the pass that actually deals with the RTL version...
6317
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6318
				// Short out, as the RTL version will deal with it in a moment.
6319
				return $tag;
6320
			}
6321
		}
6322
6323
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6324
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6325
		if ( $css ) {
6326
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6327
			if ( empty( $item->extra['after'] ) ) {
6328
				wp_add_inline_style( $handle, $css );
6329
			} else {
6330
				array_unshift( $item->extra['after'], $css );
6331
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6332
			}
6333
		}
6334
6335
		return $tag;
6336
	}
6337
6338
	/**
6339
	 * Loads a view file from the views
6340
	 *
6341
	 * Data passed in with the $data parameter will be available in the
6342
	 * template file as $data['value']
6343
	 *
6344
	 * @param string $template - Template file to load
6345
	 * @param array $data - Any data to pass along to the template
6346
	 * @return boolean - If template file was found
6347
	 **/
6348
	public function load_view( $template, $data = array() ) {
6349
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6350
6351
		if( file_exists( $views_dir . $template ) ) {
6352
			require_once( $views_dir . $template );
6353
			return true;
6354
		}
6355
6356
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6357
		return false;
6358
	}
6359
6360
	/**
6361
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6362
	 */
6363
	public function deprecated_hooks() {
6364
		global $wp_filter;
6365
6366
		/*
6367
		 * Format:
6368
		 * deprecated_filter_name => replacement_name
6369
		 *
6370
		 * If there is no replacement, use null for replacement_name
6371
		 */
6372
		$deprecated_list = array(
6373
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6374
			'wpl_sharing_2014_1'                                     => null,
6375
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6376
			'jetpack_identity_crisis_options_to_check'               => null,
6377
			'update_option_jetpack_single_user_site'                 => null,
6378
			'audio_player_default_colors'                            => null,
6379
			'add_option_jetpack_featured_images_enabled'             => null,
6380
			'add_option_jetpack_update_details'                      => null,
6381
			'add_option_jetpack_updates'                             => null,
6382
			'add_option_jetpack_network_name'                        => null,
6383
			'add_option_jetpack_network_allow_new_registrations'     => null,
6384
			'add_option_jetpack_network_add_new_users'               => null,
6385
			'add_option_jetpack_network_site_upload_space'           => null,
6386
			'add_option_jetpack_network_upload_file_types'           => null,
6387
			'add_option_jetpack_network_enable_administration_menus' => null,
6388
			'add_option_jetpack_is_multi_site'                       => null,
6389
			'add_option_jetpack_is_main_network'                     => null,
6390
			'add_option_jetpack_main_network_site'                   => null,
6391
			'jetpack_sync_all_registered_options'                    => null,
6392
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6393
			'jetpack_is_post_mailable'                               => null,
6394
			'jetpack_seo_site_host'                                  => null,
6395
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6396
			'jetpack_holiday_snow_option_name'                       => null,
6397
			'jetpack_holiday_chance_of_snow'                         => null,
6398
			'jetpack_holiday_snow_js_url'                            => null,
6399
			'jetpack_is_holiday_snow_season'                         => null,
6400
			'jetpack_holiday_snow_option_updated'                    => null,
6401
			'jetpack_holiday_snowing'                                => null,
6402
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6403
			'jetpack_cache_plans'                                    => null,
6404
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6405
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6406
			'jetpack_enable_site_verification'                       => null,
6407
			'can_display_jetpack_manage_notice'                      => null,
6408
			// Removed in Jetpack 7.3.0
6409
			'atd_load_scripts'                                       => null,
6410
			'atd_http_post_timeout'                                  => null,
6411
			'atd_http_post_error'                                    => null,
6412
			'atd_service_domain'                                     => null,
6413
		);
6414
6415
		// This is a silly loop depth. Better way?
6416
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6417
			if ( has_action( $hook ) ) {
6418
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6419
					foreach( $values AS $hooked ) {
6420
						if ( is_callable( $hooked['function'] ) ) {
6421
							$function_name = 'an anonymous function';
6422
						} else {
6423
							$function_name = $hooked['function'];
6424
						}
6425
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6426
					}
6427
				}
6428
			}
6429
		}
6430
	}
6431
6432
	/**
6433
	 * Converts any url in a stylesheet, to the correct absolute url.
6434
	 *
6435
	 * Considerations:
6436
	 *  - Normal, relative URLs     `feh.png`
6437
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6438
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6439
	 *  - Absolute URLs             `http://domain.com/feh.png`
6440
	 *  - Domain root relative URLs `/feh.png`
6441
	 *
6442
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6443
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6444
	 *
6445
	 * @return mixed|string
6446
	 */
6447
	public static function absolutize_css_urls( $css, $css_file_url ) {
6448
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6449
		$css_dir = dirname( $css_file_url );
6450
		$p       = parse_url( $css_dir );
6451
		$domain  = sprintf(
6452
					'%1$s//%2$s%3$s%4$s',
6453
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6454
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6455
					$p['host'],
6456
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6457
				);
6458
6459
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6460
			$find = $replace = array();
6461
			foreach ( $matches as $match ) {
6462
				$url = trim( $match['path'], "'\" \t" );
6463
6464
				// If this is a data url, we don't want to mess with it.
6465
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6466
					continue;
6467
				}
6468
6469
				// If this is an absolute or protocol-agnostic url,
6470
				// we don't want to mess with it.
6471
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6472
					continue;
6473
				}
6474
6475
				switch ( substr( $url, 0, 1 ) ) {
6476
					case '/':
6477
						$absolute = $domain . $url;
6478
						break;
6479
					default:
6480
						$absolute = $css_dir . '/' . $url;
6481
				}
6482
6483
				$find[]    = $match[0];
6484
				$replace[] = sprintf( 'url("%s")', $absolute );
6485
			}
6486
			$css = str_replace( $find, $replace, $css );
6487
		}
6488
6489
		return $css;
6490
	}
6491
6492
	/**
6493
	 * This methods removes all of the registered css files on the front end
6494
	 * from Jetpack in favor of using a single file. In effect "imploding"
6495
	 * all the files into one file.
6496
	 *
6497
	 * Pros:
6498
	 * - Uses only ONE css asset connection instead of 15
6499
	 * - Saves a minimum of 56k
6500
	 * - Reduces server load
6501
	 * - Reduces time to first painted byte
6502
	 *
6503
	 * Cons:
6504
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6505
	 *		should not cause any issues with themes.
6506
	 * - Plugins/themes dequeuing styles no longer do anything. See
6507
	 *		jetpack_implode_frontend_css filter for a workaround
6508
	 *
6509
	 * For some situations developers may wish to disable css imploding and
6510
	 * instead operate in legacy mode where each file loads seperately and
6511
	 * can be edited individually or dequeued. This can be accomplished with
6512
	 * the following line:
6513
	 *
6514
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6515
	 *
6516
	 * @since 3.2
6517
	 **/
6518
	public function implode_frontend_css( $travis_test = false ) {
6519
		$do_implode = true;
6520
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6521
			$do_implode = false;
6522
		}
6523
6524
		// Do not implode CSS when the page loads via the AMP plugin.
6525
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6526
			$do_implode = false;
6527
		}
6528
6529
		/**
6530
		 * Allow CSS to be concatenated into a single jetpack.css file.
6531
		 *
6532
		 * @since 3.2.0
6533
		 *
6534
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6535
		 */
6536
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6537
6538
		// Do not use the imploded file when default behavior was altered through the filter
6539
		if ( ! $do_implode ) {
6540
			return;
6541
		}
6542
6543
		// We do not want to use the imploded file in dev mode, or if not connected
6544
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6545
			if ( ! $travis_test ) {
6546
				return;
6547
			}
6548
		}
6549
6550
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6551
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6552
			return;
6553
		}
6554
6555
		/*
6556
		 * Now we assume Jetpack is connected and able to serve the single
6557
		 * file.
6558
		 *
6559
		 * In the future there will be a check here to serve the file locally
6560
		 * or potentially from the Jetpack CDN
6561
		 *
6562
		 * For now:
6563
		 * - Enqueue a single imploded css file
6564
		 * - Zero out the style_loader_tag for the bundled ones
6565
		 * - Be happy, drink scotch
6566
		 */
6567
6568
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6569
6570
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6571
6572
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6573
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6574
	}
6575
6576
	function concat_remove_style_loader_tag( $tag, $handle ) {
6577
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6578
			$tag = '';
6579
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6580
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6581
			}
6582
		}
6583
6584
		return $tag;
6585
	}
6586
6587
	/*
6588
	 * Check the heartbeat data
6589
	 *
6590
	 * Organizes the heartbeat data by severity.  For example, if the site
6591
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6592
	 *
6593
	 * Data will be added to "caution" array, if it either:
6594
	 *  - Out of date Jetpack version
6595
	 *  - Out of date WP version
6596
	 *  - Out of date PHP version
6597
	 *
6598
	 * $return array $filtered_data
6599
	 */
6600
	public static function jetpack_check_heartbeat_data() {
6601
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6602
6603
		$good    = array();
6604
		$caution = array();
6605
		$bad     = array();
6606
6607
		foreach ( $raw_data as $stat => $value ) {
6608
6609
			// Check jetpack version
6610
			if ( 'version' == $stat ) {
6611
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6612
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6613
					continue;
6614
				}
6615
			}
6616
6617
			// Check WP version
6618
			if ( 'wp-version' == $stat ) {
6619
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6620
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6621
					continue;
6622
				}
6623
			}
6624
6625
			// Check PHP version
6626
			if ( 'php-version' == $stat ) {
6627
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6628
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6629
					continue;
6630
				}
6631
			}
6632
6633
			// Check ID crisis
6634
			if ( 'identitycrisis' == $stat ) {
6635
				if ( 'yes' == $value ) {
6636
					$bad[ $stat ] = $value;
6637
					continue;
6638
				}
6639
			}
6640
6641
			// The rest are good :)
6642
			$good[ $stat ] = $value;
6643
		}
6644
6645
		$filtered_data = array(
6646
			'good'    => $good,
6647
			'caution' => $caution,
6648
			'bad'     => $bad
6649
		);
6650
6651
		return $filtered_data;
6652
	}
6653
6654
6655
	/*
6656
	 * This method is used to organize all options that can be reset
6657
	 * without disconnecting Jetpack.
6658
	 *
6659
	 * It is used in class.jetpack-cli.php to reset options
6660
	 *
6661
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6662
	 *
6663
	 * @return array of options to delete.
6664
	 */
6665
	public static function get_jetpack_options_for_reset() {
6666
		return Jetpack_Options::get_options_for_reset();
6667
	}
6668
6669
	/*
6670
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6671
	 * so we can bring them directly to their site in calypso.
6672
	 *
6673
	 * @param string | url
6674
	 * @return string | url without the guff
6675
	 */
6676
	public static function build_raw_urls( $url ) {
6677
		$strip_http = '/.*?:\/\//i';
6678
		$url = preg_replace( $strip_http, '', $url  );
6679
		$url = str_replace( '/', '::', $url );
6680
		return $url;
6681
	}
6682
6683
	/**
6684
	 * Stores and prints out domains to prefetch for page speed optimization.
6685
	 *
6686
	 * @param mixed $new_urls
6687
	 */
6688
	public static function dns_prefetch( $new_urls = null ) {
6689
		static $prefetch_urls = array();
6690
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6691
			echo "\r\n";
6692
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6693
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6694
			}
6695
		} elseif ( ! empty( $new_urls ) ) {
6696
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6697
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6698
			}
6699
			foreach ( (array) $new_urls as $this_new_url ) {
6700
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6701
			}
6702
			$prefetch_urls = array_unique( $prefetch_urls );
6703
		}
6704
	}
6705
6706
	public function wp_dashboard_setup() {
6707
		if ( self::is_active() ) {
6708
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6709
		}
6710
6711
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6712
			$jetpack_logo = new Jetpack_Logo();
6713
			$widget_title = sprintf(
6714
				wp_kses(
6715
					/* translators: Placeholder is a Jetpack logo. */
6716
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6717
					array( 'span' => array() )
6718
				),
6719
				$jetpack_logo->get_jp_emblem( true )
6720
			);
6721
6722
			wp_add_dashboard_widget(
6723
				'jetpack_summary_widget',
6724
				$widget_title,
6725
				array( __CLASS__, 'dashboard_widget' )
6726
			);
6727
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6728
6729
			// If we're inactive and not in development mode, sort our box to the top.
6730
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6731
				global $wp_meta_boxes;
6732
6733
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6734
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6735
6736
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6737
			}
6738
		}
6739
	}
6740
6741
	/**
6742
	 * @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...
6743
	 * @return mixed
6744
	 */
6745
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6746
		if ( ! is_array( $sorted ) ) {
6747
			return $sorted;
6748
		}
6749
6750
		foreach ( $sorted as $box_context => $ids ) {
6751
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6752
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6753
				continue;
6754
			}
6755
6756
			$ids_array = explode( ',', $ids );
6757
			$key = array_search( 'dashboard_stats', $ids_array );
6758
6759
			if ( false !== $key ) {
6760
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6761
				$ids_array[ $key ] = 'jetpack_summary_widget';
6762
				$sorted[ $box_context ] = implode( ',', $ids_array );
6763
				// We've found it, stop searching, and just return.
6764
				break;
6765
			}
6766
		}
6767
6768
		return $sorted;
6769
	}
6770
6771
	public static function dashboard_widget() {
6772
		/**
6773
		 * Fires when the dashboard is loaded.
6774
		 *
6775
		 * @since 3.4.0
6776
		 */
6777
		do_action( 'jetpack_dashboard_widget' );
6778
	}
6779
6780
	public static function dashboard_widget_footer() {
6781
		?>
6782
		<footer>
6783
6784
		<div class="protect">
6785
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6786
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6787
				<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>
6788
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6789
				<a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( array( 'action' => 'activate', 'module' => 'protect' ) ), 'jetpack_activate-protect' ) ); ?>" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6790
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6791
				</a>
6792
			<?php else : ?>
6793
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6794
			<?php endif; ?>
6795
		</div>
6796
6797
		<div class="akismet">
6798
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6799
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6800
				<p><?php echo esc_html_x( 'Spam comments blocked by Akismet.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
6801
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6802
				<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'activate', 'plugin' => 'akismet/akismet.php' ), admin_url( 'plugins.php' ) ), 'activate-plugin_akismet/akismet.php' ) ); ?>" class="button button-jetpack">
6803
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6804
				</a>
6805
			<?php else : ?>
6806
				<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( 'Akismet can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
6807
			<?php endif; ?>
6808
		</div>
6809
6810
		</footer>
6811
		<?php
6812
	}
6813
6814
	/*
6815
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6816
	 */
6817
	function jetpack_icon_user_connected( $columns ) {
6818
		$columns['user_jetpack'] = '';
6819
		return $columns;
6820
	}
6821
6822
	/*
6823
	 * Show Jetpack icon if the user is linked.
6824
	 */
6825
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6826
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6827
			$jetpack_logo = new Jetpack_Logo();
6828
			$emblem_html = sprintf(
6829
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6830
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6831
				$jetpack_logo->get_jp_emblem()
6832
			);
6833
			return $emblem_html;
6834
		}
6835
6836
		return $val;
6837
	}
6838
6839
	/*
6840
	 * Style the Jetpack user column
6841
	 */
6842
	function jetpack_user_col_style() {
6843
		global $current_screen;
6844
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6845
			<style>
6846
				.fixed .column-user_jetpack {
6847
					width: 21px;
6848
				}
6849
				.jp-emblem-user-admin svg {
6850
					width: 20px;
6851
					height: 20px;
6852
				}
6853
				.jp-emblem-user-admin path {
6854
					fill: #00BE28;
6855
				}
6856
			</style>
6857
		<?php }
6858
	}
6859
6860
	/**
6861
	 * Checks if Akismet is active and working.
6862
	 *
6863
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6864
	 * that implied usage of methods present since more recent version.
6865
	 * See https://github.com/Automattic/jetpack/pull/9585
6866
	 *
6867
	 * @since  5.1.0
6868
	 *
6869
	 * @return bool True = Akismet available. False = Aksimet not available.
6870
	 */
6871
	public static function is_akismet_active() {
6872
		static $status = null;
6873
6874
		if ( ! is_null( $status ) ) {
6875
			return $status;
6876
		}
6877
6878
		// Check if a modern version of Akismet is active.
6879
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6880
			$status = false;
6881
			return $status;
6882
		}
6883
6884
		// Make sure there is a key known to Akismet at all before verifying key.
6885
		$akismet_key = Akismet::get_api_key();
6886
		if ( ! $akismet_key ) {
6887
			$status = false;
6888
			return $status;
6889
		}
6890
6891
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6892
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6893
6894
		// 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.
6895
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6896
		// We cache the result of the Akismet key verification for ten minutes.
6897
		if ( ! $akismet_key_state || $recheck ) {
6898
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6899
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6900
		}
6901
6902
		$status = 'valid' === $akismet_key_state;
6903
6904
		return $status;
6905
	}
6906
6907
	/**
6908
	 * Checks if one or more function names is in debug_backtrace
6909
	 *
6910
	 * @param $names Mixed string name of function or array of string names of functions
6911
	 *
6912
	 * @return bool
6913
	 */
6914
	public static function is_function_in_backtrace( $names ) {
6915
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6916
		if ( ! is_array( $names ) ) {
6917
			$names = array( $names );
6918
		}
6919
		$names_as_keys = array_flip( $names );
6920
6921
		//Do check in constant O(1) time for PHP5.5+
6922
		if ( function_exists( 'array_column' ) ) {
6923
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6924
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6925
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6926
			return ! empty ( $intersection );
6927
		}
6928
6929
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6930
		foreach ( $backtrace as $call ) {
6931
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6932
				return true;
6933
			}
6934
		}
6935
		return false;
6936
	}
6937
6938
	/**
6939
	 * Given a minified path, and a non-minified path, will return
6940
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6941
	 *
6942
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6943
	 * root Jetpack directory.
6944
	 *
6945
	 * @since 5.6.0
6946
	 *
6947
	 * @param string $min_path
6948
	 * @param string $non_min_path
6949
	 * @return string The URL to the file
6950
	 */
6951
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6952
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
6953
			? $non_min_path
6954
			: $min_path;
6955
6956
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6957
	}
6958
6959
	/**
6960
	 * Checks for whether Jetpack Backup & Scan is enabled.
6961
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6962
	 * @return bool|int|mixed
6963
	 */
6964
	public static function is_rewind_enabled() {
6965
		if ( ! Jetpack::is_active() ) {
6966
			return false;
6967
		}
6968
6969
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6970
		if ( false === $rewind_enabled ) {
6971
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6972
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6973
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6974
				&& ! empty( $rewind_data['state'] )
6975
				&& 'active' === $rewind_data['state'] )
6976
				? 1
6977
				: 0;
6978
6979
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6980
		}
6981
		return $rewind_enabled;
6982
	}
6983
6984
	/**
6985
	 * Return Calypso environment value; used for developing Jetpack and pairing
6986
	 * it with different Calypso enrionments, such as localhost.
6987
	 *
6988
	 * @since 7.4.0
6989
	 *
6990
	 * @return string Calypso environment
6991
	 */
6992
	public static function get_calypso_env() {
6993
		if ( isset( $_GET['calypso_env'] ) ) {
6994
			return sanitize_key( $_GET['calypso_env'] );
6995
		}
6996
6997
		if ( getenv( 'CALYPSO_ENV' ) ) {
6998
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6999
		}
7000
7001
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7002
			return sanitize_key( CALYPSO_ENV );
7003
		}
7004
7005
		return '';
7006
	}
7007
7008
	/**
7009
	 * Checks whether or not TOS has been agreed upon.
7010
	 * Will return true if a user has clicked to register, or is already connected.
7011
	 */
7012
	public static function jetpack_tos_agreed() {
7013
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7014
	}
7015
7016
	/**
7017
	 * Handles activating default modules as well general cleanup for the new connection.
7018
	 *
7019
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7020
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7021
	 * @param boolean $send_state_messages          Whether to send state messages.
7022
	 * @return void
7023
	 */
7024
	public static function handle_post_authorization_actions(
7025
		$activate_sso = false,
7026
		$redirect_on_activation_error = false,
7027
		$send_state_messages = true
7028
	) {
7029
		$other_modules = $activate_sso
7030
			? array( 'sso' )
7031
			: array();
7032
7033
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7034
			Jetpack::delete_active_modules();
7035
7036
			Jetpack::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...
7037
		} else {
7038
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7039
		}
7040
7041
		// Since this is a fresh connection, be sure to clear out IDC options
7042
		Jetpack_IDC::clear_all_idc_options();
7043
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7044
7045
		// Start nonce cleaner
7046
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7047
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7048
7049
		if ( $send_state_messages ) {
7050
			Jetpack::state( 'message', 'authorized' );
7051
		}
7052
	}
7053
7054
	/**
7055
	 * Returns a boolean for whether backups UI should be displayed or not.
7056
	 *
7057
	 * @return bool Should backups UI be displayed?
7058
	 */
7059
	public static function show_backups_ui() {
7060
		/**
7061
		 * Whether UI for backups should be displayed.
7062
		 *
7063
		 * @since 6.5.0
7064
		 *
7065
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7066
		 */
7067
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7068
	}
7069
7070
	/*
7071
	 * Deprecated manage functions
7072
	 */
7073
	function prepare_manage_jetpack_notice() {
7074
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7075
	}
7076
	function manage_activate_screen() {
7077
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7078
	}
7079
	function admin_jetpack_manage_notice() {
7080
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7081
	}
7082
	function opt_out_jetpack_manage_url() {
7083
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7084
	}
7085
	function opt_in_jetpack_manage_url() {
7086
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7087
	}
7088
	function opt_in_jetpack_manage_notice() {
7089
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7090
	}
7091
	function can_display_jetpack_manage_notice() {
7092
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7093
	}
7094
7095
	/**
7096
	 * Clean leftoveruser meta.
7097
	 *
7098
	 * Delete Jetpack-related user meta when it is no longer needed.
7099
	 *
7100
	 * @since 7.3.0
7101
	 *
7102
	 * @param int $user_id User ID being updated.
7103
	 */
7104
	public static function user_meta_cleanup( $user_id ) {
7105
		$meta_keys = array(
7106
			// AtD removed from Jetpack 7.3
7107
			'AtD_options',
7108
			'AtD_check_when',
7109
			'AtD_guess_lang',
7110
			'AtD_ignored_phrases',
7111
		);
7112
7113
		foreach ( $meta_keys as $meta_key ) {
7114
			if ( get_user_meta( $user_id, $meta_key ) ) {
7115
				delete_user_meta( $user_id, $meta_key );
7116
			}
7117
		}
7118
	}
7119
7120
	function is_active_and_not_development_mode( $maybe ) {
7121
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7122
			return false;
7123
		}
7124
		return true;
7125
	}
7126
}
7127