Completed
Push — try/dummy-deactivate-dialog ( 38cc77 )
by
unknown
16:32 queued 09:31
created

Jetpack::get_site_user_count()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 0
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $xmlrpc_verification = null;
44
	private $rest_authentication_status = null;
45
46
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
47
48
	private $tracking;
49
50
	/**
51
	 * @var array The handles of styles that are concatenated into jetpack.css.
52
	 *
53
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
54
	 */
55
	public $concatenated_style_handles = array(
56
		'jetpack-carousel',
57
		'grunion.css',
58
		'the-neverending-homepage',
59
		'jetpack_likes',
60
		'jetpack_related-posts',
61
		'sharedaddy',
62
		'jetpack-slideshow',
63
		'presentations',
64
		'quiz',
65
		'jetpack-subscriptions',
66
		'jetpack-responsive-videos-style',
67
		'jetpack-social-menu',
68
		'tiled-gallery',
69
		'jetpack_display_posts_widget',
70
		'gravatar-profile-widget',
71
		'goodreads-widget',
72
		'jetpack_social_media_icons_widget',
73
		'jetpack-top-posts-widget',
74
		'jetpack_image_widget',
75
		'jetpack-my-community-widget',
76
		'jetpack-authors-widget',
77
		'wordads',
78
		'eu-cookie-law-style',
79
		'flickr-widget-style',
80
		'jetpack-search-widget',
81
		'jetpack-simple-payments-widget-style',
82
		'jetpack-widget-social-icons-styles',
83
	);
84
85
	/**
86
	 * Contains all assets that have had their URL rewritten to minified versions.
87
	 *
88
	 * @var array
89
	 */
90
	static $min_assets = array();
91
92
	public $plugins_to_deactivate = array(
93
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
94
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
95
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
96
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
97
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
98
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
99
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
100
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
101
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
102
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
103
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
104
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
105
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
106
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
107
	);
108
109
	/**
110
	 * Map of roles we care about, and their corresponding minimum capabilities.
111
	 *
112
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
113
	 *
114
	 * @access public
115
	 * @static
116
	 *
117
	 * @var array
118
	 */
119
	public static $capability_translations = array(
120
		'administrator' => 'manage_options',
121
		'editor'        => 'edit_others_posts',
122
		'author'        => 'publish_posts',
123
		'contributor'   => 'edit_posts',
124
		'subscriber'    => 'read',
125
	);
126
127
	/**
128
	 * Map of modules that have conflicts with plugins and should not be auto-activated
129
	 * if the plugins are active.  Used by filter_default_modules
130
	 *
131
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
132
	 * change `module-slug` and add this to your plugin:
133
	 *
134
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
135
	 * function my_jetpack_get_default_modules( $modules ) {
136
	 *     return array_diff( $modules, array( 'module-slug' ) );
137
	 * }
138
	 *
139
	 * @var array
140
	 */
141
	private $conflicting_plugins = array(
142
		'comments'          => array(
143
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
144
			'Disqus'                               => 'disqus-comment-system/disqus.php',
145
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
146
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
147
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
148
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
149
		),
150
		'comment-likes' => array(
151
			'Epoch'                                => 'epoch/plugincore.php',
152
		),
153
		'contact-form'      => array(
154
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
155
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
156
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
157
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
158
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
159
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
160
		),
161
		'minileven'         => array(
162
			'WPtouch'                              => 'wptouch/wptouch.php',
163
		),
164
		'latex'             => array(
165
			'LaTeX for WordPress'                  => 'latex/latex.php',
166
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
167
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
168
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
169
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
170
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
171
		),
172
		'protect'           => array(
173
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
174
			'Captcha'                              => 'captcha/captcha.php',
175
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
176
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
177
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
178
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
179
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
180
			'Security-protection'                  => 'security-protection/security-protection.php',
181
			'Login Security'                       => 'login-security/login-security.php',
182
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
183
			'Wordfence Security'                   => 'wordfence/wordfence.php',
184
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
185
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
186
		),
187
		'random-redirect'   => array(
188
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
189
		),
190
		'related-posts'     => array(
191
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
192
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
193
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
194
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
195
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
196
			'outbrain'                             => 'outbrain/outbrain.php',
197
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
198
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
199
		),
200
		'sharedaddy'        => array(
201
			'AddThis'                              => 'addthis/addthis_social_widget.php',
202
			'Add To Any'                           => 'add-to-any/add-to-any.php',
203
			'ShareThis'                            => 'share-this/sharethis.php',
204
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
205
		),
206
		'seo-tools' => array(
207
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
208
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
209
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
210
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
211
			'The SEO Framework'                    => 'autodescription/autodescription.php',
212
		),
213
		'verification-tools' => array(
214
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
215
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
216
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
217
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
218
			'The SEO Framework'                    => 'autodescription/autodescription.php',
219
		),
220
		'widget-visibility' => array(
221
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
222
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
223
		),
224
		'sitemaps' => array(
225
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
226
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
227
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
228
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
229
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
230
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
231
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
232
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
233
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
234
			'The SEO Framework'                    => 'autodescription/autodescription.php',
235
			'Sitemap'                              => 'sitemap/sitemap.php',
236
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
237
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
238
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
239
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
240
		),
241
		'lazy-images' => array(
242
			'Lazy Load'              => 'lazy-load/lazy-load.php',
243
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
244
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
245
		),
246
	);
247
248
	/**
249
	 * Plugins for which we turn off our Facebook OG Tags implementation.
250
	 *
251
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
252
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
253
	 *
254
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
255
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
256
	 */
257
	private $open_graph_conflicting_plugins = array(
258
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
259
		                                                         // 2 Click Social Media Buttons
260
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
261
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
262
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
263
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
264
		                                                         // Open Graph Meta Tags by Heateor
265
		'facebook/facebook.php',                                 // Facebook (official plugin)
266
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
267
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
268
		                                                         // Facebook Featured Image & OG Meta Tags
269
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
270
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
271
		                                                         // Facebook Open Graph Meta Tags for WordPress
272
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
273
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
274
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
275
		                                                         // Fedmich's Facebook Open Graph Meta
276
		'network-publisher/networkpub.php',                      // Network Publisher
277
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
278
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
279
		                                                         // NextScripts SNAP
280
		'og-tags/og-tags.php',                                   // OG Tags
281
		'opengraph/opengraph.php',                               // Open Graph
282
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
283
		                                                         // Open Graph Protocol Framework
284
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
285
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
286
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
287
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
288
		'sharepress/sharepress.php',                             // SharePress
289
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
290
		'social-discussions/social-discussions.php',             // Social Discussions
291
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
292
		'socialize/socialize.php',                               // Socialize
293
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
294
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
295
		                                                         // Tweet, Like, Google +1 and Share
296
		'wordbooker/wordbooker.php',                             // Wordbooker
297
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
298
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
299
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
300
		                                                         // WP Facebook Like Send & Open Graph Meta
301
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
302
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
303
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
304
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
305
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
306
	);
307
308
	/**
309
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
310
	 */
311
	private $twitter_cards_conflicting_plugins = array(
312
	//	'twitter/twitter.php',                       // The official one handles this on its own.
313
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
314
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
315
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
316
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
317
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
318
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
319
		'twitter-cards/twitter-cards.php',           // Twitter Cards
320
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
321
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
322
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
323
	);
324
325
	/**
326
	 * Message to display in admin_notice
327
	 * @var string
328
	 */
329
	public $message = '';
330
331
	/**
332
	 * Error to display in admin_notice
333
	 * @var string
334
	 */
335
	public $error = '';
336
337
	/**
338
	 * Modules that need more privacy description.
339
	 * @var string
340
	 */
341
	public $privacy_checks = '';
342
343
	/**
344
	 * Stats to record once the page loads
345
	 *
346
	 * @var array
347
	 */
348
	public $stats = array();
349
350
	/**
351
	 * Jetpack_Sync object
352
	 */
353
	public $sync;
354
355
	/**
356
	 * Verified data for JSON authorization request
357
	 */
358
	public $json_api_authorization_request = array();
359
360
	/**
361
	 * @var \Automattic\Jetpack\Connection\Manager
362
	 */
363
	protected $connection_manager;
364
365
	/**
366
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
367
	 */
368
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
369
370
	/**
371
	 * Holds the singleton instance of this class
372
	 * @since 2.3.3
373
	 * @var Jetpack
374
	 */
375
	static $instance = false;
376
377
	/**
378
	 * Singleton
379
	 * @static
380
	 */
381
	public static function init() {
382
		if ( ! self::$instance ) {
383
			self::$instance = new Jetpack;
384
385
			self::$instance->plugin_upgrade();
386
		}
387
388
		return self::$instance;
389
	}
390
391
	/**
392
	 * Must never be called statically
393
	 */
394
	function plugin_upgrade() {
395
		if ( Jetpack::is_active() ) {
396
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
397
			if ( JETPACK__VERSION != $version ) {
398
				// Prevent multiple upgrades at once - only a single process should trigger
399
				// an upgrade to avoid stampedes
400
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
401
					return;
402
				}
403
404
				// Set a short lock to prevent multiple instances of the upgrade
405
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
406
407
				// check which active modules actually exist and remove others from active_modules list
408
				$unfiltered_modules = Jetpack::get_active_modules();
409
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
410
				if ( array_diff( $unfiltered_modules, $modules ) ) {
411
					Jetpack::update_active_modules( $modules );
412
				}
413
414
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
415
416
				// Upgrade to 4.3.0
417
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
418
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
419
				}
420
421
				// Make sure Markdown for posts gets turned back on
422
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
423
					update_option( 'wpcom_publish_posts_with_markdown', true );
424
				}
425
426
				if ( did_action( 'wp_loaded' ) ) {
427
					self::upgrade_on_load();
428
				} else {
429
					add_action(
430
						'wp_loaded',
431
						array( __CLASS__, 'upgrade_on_load' )
432
					);
433
				}
434
			}
435
		}
436
	}
437
438
	/**
439
	 * Runs upgrade routines that need to have modules loaded.
440
	 */
441
	static function upgrade_on_load() {
442
443
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
444
		// This can happen in case Jetpack has been just upgraded and is
445
		// being initialized late during the page load. In this case we wait
446
		// until the next proper admin page load with Jetpack active.
447
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
448
			delete_transient( self::$plugin_upgrade_lock_key );
449
450
			return;
451
		}
452
453
		Jetpack::maybe_set_version_option();
454
455
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
456
			Jetpack_Widget_Conditions::migrate_post_type_rules();
457
		}
458
459
		if (
460
			class_exists( 'Jetpack_Sitemap_Manager' )
461
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
462
		) {
463
			do_action( 'jetpack_sitemaps_purge_data' );
464
		}
465
466
		delete_transient( self::$plugin_upgrade_lock_key );
467
	}
468
469
	/**
470
	 * Saves all the currently active modules to options.
471
	 * Also fires Action hooks for each newly activated and deactivated module.
472
	 *
473
	 * @param $modules Array Array of active modules to be saved in options.
474
	 *
475
	 * @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...
476
	 */
477
	static function update_active_modules( $modules ) {
478
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
479
		$active_modules       = Jetpack::get_active_modules();
480
		$new_active_modules   = array_diff( $modules, $current_modules );
481
		$new_inactive_modules = array_diff( $active_modules, $modules );
482
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
483
		$reindexed_modules    = array_values( $new_current_modules );
484
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
485
486
		foreach ( $new_active_modules as $module ) {
487
			/**
488
			 * Fires when a specific module is activated.
489
			 *
490
			 * @since 1.9.0
491
			 *
492
			 * @param string $module Module slug.
493
			 * @param boolean $success whether the module was activated. @since 4.2
494
			 */
495
			do_action( 'jetpack_activate_module', $module, $success );
496
			/**
497
			 * Fires when a module is activated.
498
			 * The dynamic part of the filter, $module, is the module slug.
499
			 *
500
			 * @since 1.9.0
501
			 *
502
			 * @param string $module Module slug.
503
			 */
504
			do_action( "jetpack_activate_module_$module", $module );
505
		}
506
507
		foreach ( $new_inactive_modules as $module ) {
508
			/**
509
			 * Fired after a module has been deactivated.
510
			 *
511
			 * @since 4.2.0
512
			 *
513
			 * @param string $module Module slug.
514
			 * @param boolean $success whether the module was deactivated.
515
			 */
516
			do_action( 'jetpack_deactivate_module', $module, $success );
517
			/**
518
			 * Fires when a module is deactivated.
519
			 * The dynamic part of the filter, $module, is the module slug.
520
			 *
521
			 * @since 1.9.0
522
			 *
523
			 * @param string $module Module slug.
524
			 */
525
			do_action( "jetpack_deactivate_module_$module", $module );
526
		}
527
528
		return $success;
529
	}
530
531
	static function delete_active_modules() {
532
		self::update_active_modules( array() );
533
	}
534
535
	/**
536
	 * Constructor.  Initializes WordPress hooks
537
	 */
538
	private function __construct() {
539
		/*
540
		 * Check for and alert any deprecated hooks
541
		 */
542
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
543
544
		/*
545
		 * Enable enhanced handling of previewing sites in Calypso
546
		 */
547
		if ( Jetpack::is_active() ) {
548
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
549
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
550
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
551
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
552
		}
553
554
		if ( self::jetpack_tos_agreed() ) {
555
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
556
			add_action( 'init', array( $tracking, 'init' ) );
557
		}
558
559
		/*
560
		 * Load things that should only be in Network Admin.
561
		 *
562
		 * For now blow away everything else until a more full
563
		 * understanding of what is needed at the network level is
564
		 * available
565
		 */
566
		if ( is_multisite() ) {
567
			Jetpack_Network::init();
568
		}
569
570
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
571
			return function() {
572
				return wp_generate_password( 32, false );
573
			};
574
		} );
575
576
		$this->connection_manager = new Connection_Manager( );
577
578
		/**
579
		 * Prepare Gutenberg Editor functionality
580
		 */
581
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
582
		Jetpack_Gutenberg::init();
583
		Jetpack_Gutenberg::load_independent_blocks();
584
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
585
586
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
587
588
		// Unlink user before deleting the user from .com
589
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
590
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
591
592
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
593
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
594
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
595
				define( 'XMLRPC_REQUEST', true );
596
			}
597
598
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
599
600
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
601
		}
602
603
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
604
			@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...
605
606
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
607
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
608
609
			$this->require_jetpack_authentication();
610
611
			if ( Jetpack::is_active() ) {
612
				// Hack to preserve $HTTP_RAW_POST_DATA
613
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
614
615 View Code Duplication
				if ( $this->verify_xml_rpc_signature() ) {
616
					// The actual API methods.
617
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
618
				} else {
619
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
620
					// active Jetpack connection, so that additional users can link their account.
621
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
622
				}
623 View Code Duplication
			} else {
624
				new XMLRPC_Connector( $this->connection_manager );
625
626
				// The bootstrap API methods.
627
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
628
629
				if ( $this->verify_xml_rpc_signature() ) {
630
					// the jetpack Provision method is available for blog-token-signed requests
631
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
632
				}
633
			}
634
635
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
636
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
637
		} elseif (
638
			is_admin() &&
639
			isset( $_POST['action'] ) && (
640
				'jetpack_upload_file' == $_POST['action'] ||
641
				'jetpack_update_file' == $_POST['action']
642
			)
643
		) {
644
			$this->require_jetpack_authentication();
645
			$this->add_remote_request_handlers();
646
		} else {
647
			if ( Jetpack::is_active() ) {
648
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
649
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
650
			} else {
651
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
652
			}
653
		}
654
655
		if ( Jetpack::is_active() ) {
656
			Jetpack_Heartbeat::init();
657
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
658
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
659
				Jetpack_Search_Performance_Logger::init();
660
			}
661
		}
662
663
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
664
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
665
666
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
667
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
668
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
669
		}
670
671
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
672
673
		add_action( 'admin_init', array( $this, 'admin_init' ) );
674
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
675
676
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
677
678
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
679
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
680
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
681
682
		// returns HTTPS support status
683
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
684
685
		// JITM AJAX callback function
686
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
687
688
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
689
690
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
691
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
692
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
693
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
694
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
695
696
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
697
698
		/**
699
		 * These actions run checks to load additional files.
700
		 * They check for external files or plugins, so they need to run as late as possible.
701
		 */
702
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
703
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
704
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
705
706
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
707
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
708
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
709
710
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
711
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
712
713
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
714
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
715
716
		// A filter to control all just in time messages
717
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
718
719
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
720
721
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
722
		// We should make sure to only do this for front end links.
723
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
724
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
725
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
726
727
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
728
			//so they point moderation links on emails to Calypso
729
			jetpack_require_lib( 'functions.wp-notify' );
730
		}
731
732
		// Hide edit post link if mobile app.
733
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
734
			add_filter( 'edit_post_link', '__return_empty_string' );
735
		}
736
737
		// Update the Jetpack plan from API on heartbeats
738
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
739
740
		/**
741
		 * This is the hack to concatenate all css files into one.
742
		 * For description and reasoning see the implode_frontend_css method
743
		 *
744
		 * Super late priority so we catch all the registered styles
745
		 */
746
		if( !is_admin() ) {
747
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
748
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
749
		}
750
751
752
		/**
753
		 * These are sync actions that we need to keep track of for jitms
754
		 */
755
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
756
757
		// Actually push the stats on shutdown.
758
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
759
			add_action( 'shutdown', array( $this, 'push_stats' ) );
760
		}
761
762
	}
763
764
	function initialize_rest_api_registration_connector() {
765
		new REST_Connector( $this->connection_manager );
766
	}
767
768
	/**
769
	 * This is ported over from the manage module, which has been deprecated and baked in here.
770
	 *
771
	 * @param $domains
772
	 */
773
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
774
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
775
	}
776
777
	/**
778
	 * Return $domains, with 'wordpress.com' appended.
779
	 * This is ported over from the manage module, which has been deprecated and baked in here.
780
	 *
781
	 * @param $domains
782
	 * @return array
783
	 */
784
	function allow_wpcom_domain( $domains ) {
785
		if ( empty( $domains ) ) {
786
			$domains = array();
787
		}
788
		$domains[] = 'wordpress.com';
789
		return array_unique( $domains );
790
	}
791
792
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
793
		$post = get_post( $post_id );
794
795
		if ( empty( $post ) ) {
796
			return $default_url;
797
		}
798
799
		$post_type = $post->post_type;
800
801
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
802
		// https://en.support.wordpress.com/custom-post-types/
803
		$allowed_post_types = array(
804
			'post' => 'post',
805
			'page' => 'page',
806
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
807
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
808
		);
809
810
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
811
			return $default_url;
812
		}
813
814
		$path_prefix = $allowed_post_types[ $post_type ];
815
816
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
817
818
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
819
	}
820
821
	function point_edit_comment_links_to_calypso( $url ) {
822
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
823
		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...
824
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
825
			Jetpack::build_raw_urls( get_home_url() ),
826
			$query_args['amp;c']
827
		) );
828
	}
829
830
	function jetpack_track_last_sync_callback( $params ) {
831
		/**
832
		 * Filter to turn off jitm caching
833
		 *
834
		 * @since 5.4.0
835
		 *
836
		 * @param bool false Whether to cache just in time messages
837
		 */
838
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
839
			return $params;
840
		}
841
842
		if ( is_array( $params ) && isset( $params[0] ) ) {
843
			$option = $params[0];
844
			if ( 'active_plugins' === $option ) {
845
				// use the cache if we can, but not terribly important if it gets evicted
846
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
847
			}
848
		}
849
850
		return $params;
851
	}
852
853
	function jetpack_connection_banner_callback() {
854
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
855
856
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
857
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
858
			wp_send_json_success();
859
		}
860
861
		wp_die();
862
	}
863
864
	/**
865
	 * Removes all XML-RPC methods that are not `jetpack.*`.
866
	 * Only used in our alternate XML-RPC endpoint, where we want to
867
	 * ensure that Core and other plugins' methods are not exposed.
868
	 *
869
	 * @param array $methods
870
	 * @return array filtered $methods
871
	 */
872
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
873
		$jetpack_methods = array();
874
875
		foreach ( $methods as $method => $callback ) {
876
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
877
				$jetpack_methods[ $method ] = $callback;
878
			}
879
		}
880
881
		return $jetpack_methods;
882
	}
883
884
	/**
885
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
886
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
887
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
888
	 * which is accessible via a different URI. Most of the below is copied directly
889
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
890
	 */
891
	function alternate_xmlrpc() {
892
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
893
		global $HTTP_RAW_POST_DATA;
894
895
		// Some browser-embedded clients send cookies. We don't want them.
896
		$_COOKIE = array();
897
898
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
899
		// but we can do it ourself.
900
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
901
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
902
		}
903
904
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
905
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
906
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
907
		}
908
909
		// phpcs:enable
910
911
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
912
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
913
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
914
915
		/**
916
		 * Filters the class used for handling XML-RPC requests.
917
		 *
918
		 * @since 3.1.0
919
		 *
920
		 * @param string $class The name of the XML-RPC server class.
921
		 */
922
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
923
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
924
925
		// Fire off the request
926
		nocache_headers();
927
		$wp_xmlrpc_server->serve_request();
928
929
		exit;
930
	}
931
932
	/**
933
	 * The callback for the JITM ajax requests.
934
	 */
935
	function jetpack_jitm_ajax_callback() {
936
		// Check for nonce
937
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
938
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
939
		}
940
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
941
			$module_slug = $_REQUEST['jitmModule'];
942
			Jetpack::log( 'activate', $module_slug );
943
			Jetpack::activate_module( $module_slug, false, false );
944
			Jetpack::state( 'message', 'no_message' );
945
946
			//A Jetpack module is being activated through a JITM, track it
947
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
948
			$this->do_stats( 'server_side' );
949
950
			wp_send_json_success();
951
		}
952
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
953
			// get the hide_jitm options array
954
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
955
			$module_slug = $_REQUEST['jitmModule'];
956
957
			if( ! $jetpack_hide_jitm ) {
958
				$jetpack_hide_jitm = array(
959
					$module_slug => 'hide'
960
				);
961
			} else {
962
				$jetpack_hide_jitm[$module_slug] = 'hide';
963
			}
964
965
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
966
967
			//jitm is being dismissed forever, track it
968
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
969
			$this->do_stats( 'server_side' );
970
971
			wp_send_json_success();
972
		}
973 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
974
			$module_slug = $_REQUEST['jitmModule'];
975
976
			// User went to WordPress.com, track this
977
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
978
			$this->do_stats( 'server_side' );
979
980
			wp_send_json_success();
981
		}
982 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
983
			$track = $_REQUEST['jitmModule'];
984
985
			// User is viewing JITM, track it.
986
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
987
			$this->do_stats( 'server_side' );
988
989
			wp_send_json_success();
990
		}
991
	}
992
993
	/**
994
	 * If there are any stats that need to be pushed, but haven't been, push them now.
995
	 */
996
	function push_stats() {
997
		if ( ! empty( $this->stats ) ) {
998
			$this->do_stats( 'server_side' );
999
		}
1000
	}
1001
1002
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1003
		switch( $cap ) {
1004
			case 'jetpack_connect' :
1005
			case 'jetpack_reconnect' :
1006
				if ( Jetpack::is_development_mode() ) {
1007
					$caps = array( 'do_not_allow' );
1008
					break;
1009
				}
1010
				/**
1011
				 * Pass through. If it's not development mode, these should match disconnect.
1012
				 * Let users disconnect if it's development mode, just in case things glitch.
1013
				 */
1014
			case 'jetpack_disconnect' :
1015
				/**
1016
				 * In multisite, can individual site admins manage their own connection?
1017
				 *
1018
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1019
				 */
1020
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1021
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1022
						/**
1023
						 * We need to update the option name -- it's terribly unclear which
1024
						 * direction the override goes.
1025
						 *
1026
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1027
						 */
1028
						$caps = array( 'do_not_allow' );
1029
						break;
1030
					}
1031
				}
1032
1033
				$caps = array( 'manage_options' );
1034
				break;
1035
			case 'jetpack_manage_modules' :
1036
			case 'jetpack_activate_modules' :
1037
			case 'jetpack_deactivate_modules' :
1038
				$caps = array( 'manage_options' );
1039
				break;
1040
			case 'jetpack_configure_modules' :
1041
				$caps = array( 'manage_options' );
1042
				break;
1043
			case 'jetpack_manage_autoupdates' :
1044
				$caps = array(
1045
					'manage_options',
1046
					'update_plugins',
1047
				);
1048
				break;
1049
			case 'jetpack_network_admin_page':
1050
			case 'jetpack_network_settings_page':
1051
				$caps = array( 'manage_network_plugins' );
1052
				break;
1053
			case 'jetpack_network_sites_page':
1054
				$caps = array( 'manage_sites' );
1055
				break;
1056
			case 'jetpack_admin_page' :
1057
				if ( Jetpack::is_development_mode() ) {
1058
					$caps = array( 'manage_options' );
1059
					break;
1060
				} else {
1061
					$caps = array( 'read' );
1062
				}
1063
				break;
1064
			case 'jetpack_connect_user' :
1065
				if ( Jetpack::is_development_mode() ) {
1066
					$caps = array( 'do_not_allow' );
1067
					break;
1068
				}
1069
				$caps = array( 'read' );
1070
				break;
1071
		}
1072
		return $caps;
1073
	}
1074
1075
	function require_jetpack_authentication() {
1076
		// Don't let anyone authenticate
1077
		$_COOKIE = array();
1078
		remove_all_filters( 'authenticate' );
1079
		remove_all_actions( 'wp_login_failed' );
1080
1081
		if ( Jetpack::is_active() ) {
1082
			// Allow Jetpack authentication
1083
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1084
		}
1085
	}
1086
1087
	/**
1088
	 * Load language files
1089
	 * @action plugins_loaded
1090
	 */
1091
	public static function plugin_textdomain() {
1092
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1093
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1094
	}
1095
1096
	/**
1097
	 * Register assets for use in various modules and the Jetpack admin page.
1098
	 *
1099
	 * @uses wp_script_is, wp_register_script, plugins_url
1100
	 * @action wp_loaded
1101
	 * @return null
1102
	 */
1103
	public function register_assets() {
1104
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1105
			wp_register_script(
1106
				'spin',
1107
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1108
				false,
1109
				'1.3'
1110
			);
1111
		}
1112
1113 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1114
			wp_register_script(
1115
				'jquery.spin',
1116
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1117
				array( 'jquery', 'spin' ),
1118
				'1.3'
1119
			);
1120
		}
1121
1122 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1123
			wp_register_script(
1124
				'jetpack-gallery-settings',
1125
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1126
				array( 'media-views' ),
1127
				'20121225'
1128
			);
1129
		}
1130
1131 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1132
			wp_register_script(
1133
				'jetpack-twitter-timeline',
1134
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1135
				array( 'jquery' ),
1136
				'4.0.0',
1137
				true
1138
			);
1139
		}
1140
1141
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1142
			wp_register_script(
1143
				'jetpack-facebook-embed',
1144
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1145
				array( 'jquery' ),
1146
				null,
1147
				true
1148
			);
1149
1150
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1151
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1152
			if ( ! is_numeric( $fb_app_id ) ) {
1153
				$fb_app_id = '';
1154
			}
1155
			wp_localize_script(
1156
				'jetpack-facebook-embed',
1157
				'jpfbembed',
1158
				array(
1159
					'appid' => $fb_app_id,
1160
					'locale' => $this->get_locale(),
1161
				)
1162
			);
1163
		}
1164
1165
		/**
1166
		 * As jetpack_register_genericons is by default fired off a hook,
1167
		 * the hook may have already fired by this point.
1168
		 * So, let's just trigger it manually.
1169
		 */
1170
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1171
		jetpack_register_genericons();
1172
1173
		/**
1174
		 * Register the social logos
1175
		 */
1176
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1177
		jetpack_register_social_logos();
1178
1179 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1180
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1181
	}
1182
1183
	/**
1184
	 * Guess locale from language code.
1185
	 *
1186
	 * @param string $lang Language code.
1187
	 * @return string|bool
1188
	 */
1189 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1190
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1191
			return 'en_US';
1192
		}
1193
1194
		if ( ! class_exists( 'GP_Locales' ) ) {
1195
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1196
				return false;
1197
			}
1198
1199
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1200
		}
1201
1202
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1203
			// WP.com: get_locale() returns 'it'
1204
			$locale = GP_Locales::by_slug( $lang );
1205
		} else {
1206
			// Jetpack: get_locale() returns 'it_IT';
1207
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1208
		}
1209
1210
		if ( ! $locale ) {
1211
			return false;
1212
		}
1213
1214
		if ( empty( $locale->facebook_locale ) ) {
1215
			if ( empty( $locale->wp_locale ) ) {
1216
				return false;
1217
			} else {
1218
				// Facebook SDK is smart enough to fall back to en_US if a
1219
				// locale isn't supported. Since supported Facebook locales
1220
				// can fall out of sync, we'll attempt to use the known
1221
				// wp_locale value and rely on said fallback.
1222
				return $locale->wp_locale;
1223
			}
1224
		}
1225
1226
		return $locale->facebook_locale;
1227
	}
1228
1229
	/**
1230
	 * Get the locale.
1231
	 *
1232
	 * @return string|bool
1233
	 */
1234
	function get_locale() {
1235
		$locale = $this->guess_locale_from_lang( get_locale() );
1236
1237
		if ( ! $locale ) {
1238
			$locale = 'en_US';
1239
		}
1240
1241
		return $locale;
1242
	}
1243
1244
	/**
1245
	 * Device Pixels support
1246
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1247
	 */
1248
	function devicepx() {
1249
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1250
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1251
		}
1252
	}
1253
1254
	function deactivate_dialog() {
1255
		if ( Jetpack::is_active() ) {
1256
			wp_enqueue_script(
1257
				'jetpack-deactivate-dialog-js',
1258
				Assets::get_file_url_for_environment(
1259
					'_inc/build/jetpack-deactivate-dialog.min.js',
1260
					'_inc/jetpack-deactivate-dialog.js'
1261
				),
1262
				array( 'jquery' ),
1263
				JETPACK__VERSION,
1264
				true
1265
			);
1266
			// required for modal popup JS and styling.
1267
			add_thickbox();
1268
		}
1269
	}
1270
1271
	/**
1272
	 * Return the network_site_url so that .com knows what network this site is a part of.
1273
	 * @param  bool $option
1274
	 * @return string
1275
	 */
1276
	public function jetpack_main_network_site_option( $option ) {
1277
		return network_site_url();
1278
	}
1279
	/**
1280
	 * Network Name.
1281
	 */
1282
	static function network_name( $option = null ) {
1283
		global $current_site;
1284
		return $current_site->site_name;
1285
	}
1286
	/**
1287
	 * Does the network allow new user and site registrations.
1288
	 * @return string
1289
	 */
1290
	static function network_allow_new_registrations( $option = null ) {
1291
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1292
	}
1293
	/**
1294
	 * Does the network allow admins to add new users.
1295
	 * @return boolian
1296
	 */
1297
	static function network_add_new_users( $option = null ) {
1298
		return (bool) get_site_option( 'add_new_users' );
1299
	}
1300
	/**
1301
	 * File upload psace left per site in MB.
1302
	 *  -1 means NO LIMIT.
1303
	 * @return number
1304
	 */
1305
	static function network_site_upload_space( $option = null ) {
1306
		// value in MB
1307
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1308
	}
1309
1310
	/**
1311
	 * Network allowed file types.
1312
	 * @return string
1313
	 */
1314
	static function network_upload_file_types( $option = null ) {
1315
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1316
	}
1317
1318
	/**
1319
	 * Maximum file upload size set by the network.
1320
	 * @return number
1321
	 */
1322
	static function network_max_upload_file_size( $option = null ) {
1323
		// value in KB
1324
		return get_site_option( 'fileupload_maxk', 300 );
1325
	}
1326
1327
	/**
1328
	 * Lets us know if a site allows admins to manage the network.
1329
	 * @return array
1330
	 */
1331
	static function network_enable_administration_menus( $option = null ) {
1332
		return get_site_option( 'menu_items' );
1333
	}
1334
1335
	/**
1336
	 * If a user has been promoted to or demoted from admin, we need to clear the
1337
	 * jetpack_other_linked_admins transient.
1338
	 *
1339
	 * @since 4.3.2
1340
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1341
	 *
1342
	 * @param int    $user_id   The user ID whose role changed.
1343
	 * @param string $role      The new role.
1344
	 * @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...
1345
	 */
1346
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1347
		if ( 'administrator' == $role
1348
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1349
			|| is_null( $old_roles )
1350
		) {
1351
			delete_transient( 'jetpack_other_linked_admins' );
1352
		}
1353
	}
1354
1355
	/**
1356
	 * Checks to see if there are any other users available to become primary
1357
	 * Users must both:
1358
	 * - Be linked to wpcom
1359
	 * - Be an admin
1360
	 *
1361
	 * @return mixed False if no other users are linked, Int if there are.
1362
	 */
1363
	static function get_other_linked_admins() {
1364
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1365
1366
		if ( false === $other_linked_users ) {
1367
			$admins = get_users( array( 'role' => 'administrator' ) );
1368
			if ( count( $admins ) > 1 ) {
1369
				$available = array();
1370
				foreach ( $admins as $admin ) {
1371
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1372
						$available[] = $admin->ID;
1373
					}
1374
				}
1375
1376
				$count_connected_admins = count( $available );
1377
				if ( count( $available ) > 1 ) {
1378
					$other_linked_users = $count_connected_admins;
1379
				} else {
1380
					$other_linked_users = 0;
1381
				}
1382
			} else {
1383
				$other_linked_users = 0;
1384
			}
1385
1386
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1387
		}
1388
1389
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1390
	}
1391
1392
	/**
1393
	 * Return whether we are dealing with a multi network setup or not.
1394
	 * The reason we are type casting this is because we want to avoid the situation where
1395
	 * the result is false since when is_main_network_option return false it cases
1396
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1397
	 * database which could be set to anything as opposed to what this function returns.
1398
	 * @param  bool  $option
1399
	 *
1400
	 * @return boolean
1401
	 */
1402
	public function is_main_network_option( $option ) {
1403
		// return '1' or ''
1404
		return (string) (bool) Jetpack::is_multi_network();
1405
	}
1406
1407
	/**
1408
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1409
	 *
1410
	 * @param  string  $option
1411
	 * @return boolean
1412
	 */
1413
	public function is_multisite( $option ) {
1414
		return (string) (bool) is_multisite();
1415
	}
1416
1417
	/**
1418
	 * Implemented since there is no core is multi network function
1419
	 * Right now there is no way to tell if we which network is the dominant network on the system
1420
	 *
1421
	 * @since  3.3
1422
	 * @return boolean
1423
	 */
1424 View Code Duplication
	public static function is_multi_network() {
1425
		global  $wpdb;
1426
1427
		// if we don't have a multi site setup no need to do any more
1428
		if ( ! is_multisite() ) {
1429
			return false;
1430
		}
1431
1432
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1433
		if ( $num_sites > 1 ) {
1434
			return true;
1435
		} else {
1436
			return false;
1437
		}
1438
	}
1439
1440
	/**
1441
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1442
	 * @return null
1443
	 */
1444
	function update_jetpack_main_network_site_option() {
1445
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1446
	}
1447
	/**
1448
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1449
	 *
1450
	 */
1451
	function update_jetpack_network_settings() {
1452
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1453
		// Only sync this info for the main network site.
1454
	}
1455
1456
	/**
1457
	 * Get back if the current site is single user site.
1458
	 *
1459
	 * @return bool
1460
	 */
1461 View Code Duplication
	public static function is_single_user_site() {
1462
		global $wpdb;
1463
1464
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1465
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1466
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1467
		}
1468
		return 1 === (int) $some_users;
1469
	}
1470
1471
	/**
1472
	 * Returns true if the site has file write access false otherwise.
1473
	 * @return string ( '1' | '0' )
1474
	 **/
1475
	public static function file_system_write_access() {
1476
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1477
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1478
		}
1479
1480
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1481
1482
		$filesystem_method = get_filesystem_method();
1483
		if ( $filesystem_method === 'direct' ) {
1484
			return 1;
1485
		}
1486
1487
		ob_start();
1488
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1489
		ob_end_clean();
1490
		if ( $filesystem_credentials_are_stored ) {
1491
			return 1;
1492
		}
1493
		return 0;
1494
	}
1495
1496
	/**
1497
	 * Finds out if a site is using a version control system.
1498
	 * @return string ( '1' | '0' )
1499
	 **/
1500
	public static function is_version_controlled() {
1501
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1502
		return (string) (int) Functions::is_version_controlled();
1503
	}
1504
1505
	/**
1506
	 * Determines whether the current theme supports featured images or not.
1507
	 * @return string ( '1' | '0' )
1508
	 */
1509
	public static function featured_images_enabled() {
1510
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1511
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1512
	}
1513
1514
	/**
1515
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1516
	 *
1517
	 * @deprecated 4.7 use get_avatar_url instead.
1518
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1519
	 * @param int $size Size of the avatar image
1520
	 * @param string $default URL to a default image to use if no avatar is available
1521
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1522
	 *
1523
	 * @return array
1524
	 */
1525
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1526
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1527
		return get_avatar_url( $id_or_email, array(
1528
			'size' => $size,
1529
			'default' => $default,
1530
			'force_default' => $force_display,
1531
		) );
1532
	}
1533
1534
	/**
1535
	 * jetpack_updates is saved in the following schema:
1536
	 *
1537
	 * array (
1538
	 *      'plugins'                       => (int) Number of plugin updates available.
1539
	 *      'themes'                        => (int) Number of theme updates available.
1540
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1541
	 *      'translations'                  => (int) Number of translation updates available.
1542
	 *      'total'                         => (int) Total of all available updates.
1543
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1544
	 * )
1545
	 * @return array
1546
	 */
1547
	public static function get_updates() {
1548
		$update_data = wp_get_update_data();
1549
1550
		// Stores the individual update counts as well as the total count.
1551
		if ( isset( $update_data['counts'] ) ) {
1552
			$updates = $update_data['counts'];
1553
		}
1554
1555
		// If we need to update WordPress core, let's find the latest version number.
1556 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1557
			$cur = get_preferred_from_update_core();
1558
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1559
				$updates['wp_update_version'] = $cur->current;
1560
			}
1561
		}
1562
		return isset( $updates ) ? $updates : array();
1563
	}
1564
1565
	public static function get_update_details() {
1566
		$update_details = array(
1567
			'update_core' => get_site_transient( 'update_core' ),
1568
			'update_plugins' => get_site_transient( 'update_plugins' ),
1569
			'update_themes' => get_site_transient( 'update_themes' ),
1570
		);
1571
		return $update_details;
1572
	}
1573
1574
	public static function refresh_update_data() {
1575
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1576
1577
	}
1578
1579
	public static function refresh_theme_data() {
1580
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1581
	}
1582
1583
	/**
1584
	 * Is Jetpack active?
1585
	 */
1586
	public static function is_active() {
1587
		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...
1588
	}
1589
1590
	/**
1591
	 * Make an API call to WordPress.com for plan status
1592
	 *
1593
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1594
	 *
1595
	 * @return bool True if plan is updated, false if no update
1596
	 */
1597
	public static function refresh_active_plan_from_wpcom() {
1598
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1599
		return Jetpack_Plan::refresh_from_wpcom();
1600
	}
1601
1602
	/**
1603
	 * Get the plan that this Jetpack site is currently using
1604
	 *
1605
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1606
	 * @return array Active Jetpack plan details.
1607
	 */
1608
	public static function get_active_plan() {
1609
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1610
		return Jetpack_Plan::get();
1611
	}
1612
1613
	/**
1614
	 * Determine whether the active plan supports a particular feature
1615
	 *
1616
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1617
	 * @return bool True if plan supports feature, false if not.
1618
	 */
1619
	public static function active_plan_supports( $feature ) {
1620
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1621
		return Jetpack_Plan::supports( $feature );
1622
	}
1623
1624
	/**
1625
	 * Is Jetpack in development (offline) mode?
1626
	 */
1627 View Code Duplication
	public static function is_development_mode() {
1628
		$development_mode = false;
1629
1630
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1631
			$development_mode = JETPACK_DEV_DEBUG;
1632
		} elseif ( $site_url = site_url() ) {
1633
			$development_mode = false === strpos( $site_url, '.' );
1634
		}
1635
1636
		/**
1637
		 * Filters Jetpack's development mode.
1638
		 *
1639
		 * @see https://jetpack.com/support/development-mode/
1640
		 *
1641
		 * @since 2.2.1
1642
		 *
1643
		 * @param bool $development_mode Is Jetpack's development mode active.
1644
		 */
1645
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1646
		return $development_mode;
1647
	}
1648
1649
	/**
1650
	 * Whether the site is currently onboarding or not.
1651
	 * A site is considered as being onboarded if it currently has an onboarding token.
1652
	 *
1653
	 * @since 5.8
1654
	 *
1655
	 * @access public
1656
	 * @static
1657
	 *
1658
	 * @return bool True if the site is currently onboarding, false otherwise
1659
	 */
1660
	public static function is_onboarding() {
1661
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1662
	}
1663
1664
	/**
1665
	 * Determines reason for Jetpack development mode.
1666
	 */
1667
	public static function development_mode_trigger_text() {
1668
		if ( ! Jetpack::is_development_mode() ) {
1669
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1670
		}
1671
1672
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1673
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1674
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1675
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1676
		} else {
1677
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1678
		}
1679
1680
		return $notice;
1681
1682
	}
1683
	/**
1684
	* Get Jetpack development mode notice text and notice class.
1685
	*
1686
	* Mirrors the checks made in Jetpack::is_development_mode
1687
	*
1688
	*/
1689
	public static function show_development_mode_notice() {
1690 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1691
			$notice = sprintf(
1692
			/* translators: %s is a URL */
1693
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1694
				'https://jetpack.com/support/development-mode/'
1695
			);
1696
1697
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1698
1699
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1700
		}
1701
1702
		// Throw up a notice if using a development version and as for feedback.
1703
		if ( Jetpack::is_development_version() ) {
1704
			/* translators: %s is a URL */
1705
			$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/' );
1706
1707
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1708
		}
1709
		// Throw up a notice if using staging mode
1710
		if ( Jetpack::is_staging_site() ) {
1711
			/* translators: %s is a URL */
1712
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1713
1714
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1715
		}
1716
	}
1717
1718
	/**
1719
	 * Whether Jetpack's version maps to a public release, or a development version.
1720
	 */
1721
	public static function is_development_version() {
1722
		/**
1723
		 * Allows filtering whether this is a development version of Jetpack.
1724
		 *
1725
		 * This filter is especially useful for tests.
1726
		 *
1727
		 * @since 4.3.0
1728
		 *
1729
		 * @param bool $development_version Is this a develoment version of Jetpack?
1730
		 */
1731
		return (bool) apply_filters(
1732
			'jetpack_development_version',
1733
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1734
		);
1735
	}
1736
1737
	/**
1738
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1739
	 */
1740
	public static function is_user_connected( $user_id = false ) {
1741
		return self::connection()->is_user_connected( $user_id );
1742
	}
1743
1744
	/**
1745
	 * Get the wpcom user data of the current|specified connected user.
1746
	 */
1747 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1748
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1749
		if ( ! $user_id ) {
1750
			$user_id = get_current_user_id();
1751
		}
1752
1753
		$transient_key = "jetpack_connected_user_data_$user_id";
1754
1755
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1756
			return $cached_user_data;
1757
		}
1758
1759
		Jetpack::load_xml_rpc_client();
1760
		$xml = new Jetpack_IXR_Client( array(
1761
			'user_id' => $user_id,
1762
		) );
1763
		$xml->query( 'wpcom.getUser' );
1764
		if ( ! $xml->isError() ) {
1765
			$user_data = $xml->getResponse();
1766
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1767
			return $user_data;
1768
		}
1769
1770
		return false;
1771
	}
1772
1773
	/**
1774
	 * Get the wpcom email of the current|specified connected user.
1775
	 */
1776 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1777
		if ( ! $user_id ) {
1778
			$user_id = get_current_user_id();
1779
		}
1780
		Jetpack::load_xml_rpc_client();
1781
		$xml = new Jetpack_IXR_Client( array(
1782
			'user_id' => $user_id,
1783
		) );
1784
		$xml->query( 'wpcom.getUserEmail' );
1785
		if ( ! $xml->isError() ) {
1786
			return $xml->getResponse();
1787
		}
1788
		return false;
1789
	}
1790
1791
	/**
1792
	 * Get the wpcom email of the master user.
1793
	 */
1794
	public static function get_master_user_email() {
1795
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1796
		if ( $master_user_id ) {
1797
			return self::get_connected_user_email( $master_user_id );
1798
		}
1799
		return '';
1800
	}
1801
1802
	function current_user_is_connection_owner() {
1803
		$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...
1804
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1805
	}
1806
1807
	/**
1808
	 * Gets current user IP address.
1809
	 *
1810
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1811
	 *
1812
	 * @return string                  Current user IP address.
1813
	 */
1814
	public static function current_user_ip( $check_all_headers = false ) {
1815
		if ( $check_all_headers ) {
1816
			foreach ( array(
1817
				'HTTP_CF_CONNECTING_IP',
1818
				'HTTP_CLIENT_IP',
1819
				'HTTP_X_FORWARDED_FOR',
1820
				'HTTP_X_FORWARDED',
1821
				'HTTP_X_CLUSTER_CLIENT_IP',
1822
				'HTTP_FORWARDED_FOR',
1823
				'HTTP_FORWARDED',
1824
				'HTTP_VIA',
1825
			) as $key ) {
1826
				if ( ! empty( $_SERVER[ $key ] ) ) {
1827
					return $_SERVER[ $key ];
1828
				}
1829
			}
1830
		}
1831
1832
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1833
	}
1834
1835
	/**
1836
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1837
	 */
1838
	function extra_oembed_providers() {
1839
		// Cloudup: https://dev.cloudup.com/#oembed
1840
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1841
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1842
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1843
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1844
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1845
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1846
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1847
	}
1848
1849
	/**
1850
	 * Synchronize connected user role changes
1851
	 */
1852
	function user_role_change( $user_id ) {
1853
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1854
		Users::user_role_change( $user_id );
1855
	}
1856
1857
	/**
1858
	 * Loads the currently active modules.
1859
	 */
1860
	public static function load_modules() {
1861
		if (
1862
			! self::is_active()
1863
			&& ! self::is_development_mode()
1864
			&& ! self::is_onboarding()
1865
			&& (
1866
				! is_multisite()
1867
				|| ! get_site_option( 'jetpack_protect_active' )
1868
			)
1869
		) {
1870
			return;
1871
		}
1872
1873
		$version = Jetpack_Options::get_option( 'version' );
1874 View Code Duplication
		if ( ! $version ) {
1875
			$version = $old_version = JETPACK__VERSION . ':' . time();
1876
			/** This action is documented in class.jetpack.php */
1877
			do_action( 'updating_jetpack_version', $version, false );
1878
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1879
		}
1880
		list( $version ) = explode( ':', $version );
1881
1882
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1883
1884
		$modules_data = array();
1885
1886
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1887
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1888
			$updated_modules = array();
1889
			foreach ( $modules as $module ) {
1890
				$modules_data[ $module ] = Jetpack::get_module( $module );
1891
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1892
					continue;
1893
				}
1894
1895
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1896
					continue;
1897
				}
1898
1899
				$updated_modules[] = $module;
1900
			}
1901
1902
			$modules = array_diff( $modules, $updated_modules );
1903
		}
1904
1905
		$is_development_mode = Jetpack::is_development_mode();
1906
1907
		foreach ( $modules as $index => $module ) {
1908
			// If we're in dev mode, disable modules requiring a connection
1909
			if ( $is_development_mode ) {
1910
				// Prime the pump if we need to
1911
				if ( empty( $modules_data[ $module ] ) ) {
1912
					$modules_data[ $module ] = Jetpack::get_module( $module );
1913
				}
1914
				// If the module requires a connection, but we're in local mode, don't include it.
1915
				if ( $modules_data[ $module ]['requires_connection'] ) {
1916
					continue;
1917
				}
1918
			}
1919
1920
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1921
				continue;
1922
			}
1923
1924
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1925
				unset( $modules[ $index ] );
1926
				self::update_active_modules( array_values( $modules ) );
1927
				continue;
1928
			}
1929
1930
			/**
1931
			 * Fires when a specific module is loaded.
1932
			 * The dynamic part of the hook, $module, is the module slug.
1933
			 *
1934
			 * @since 1.1.0
1935
			 */
1936
			do_action( 'jetpack_module_loaded_' . $module );
1937
		}
1938
1939
		/**
1940
		 * Fires when all the modules are loaded.
1941
		 *
1942
		 * @since 1.1.0
1943
		 */
1944
		do_action( 'jetpack_modules_loaded' );
1945
1946
		// 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.
1947
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1948
	}
1949
1950
	/**
1951
	 * Check if Jetpack's REST API compat file should be included
1952
	 * @action plugins_loaded
1953
	 * @return null
1954
	 */
1955
	public function check_rest_api_compat() {
1956
		/**
1957
		 * Filters the list of REST API compat files to be included.
1958
		 *
1959
		 * @since 2.2.5
1960
		 *
1961
		 * @param array $args Array of REST API compat files to include.
1962
		 */
1963
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1964
1965
		if ( function_exists( 'bbpress' ) )
1966
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1967
1968
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1969
			require_once $_jetpack_rest_api_compat_include;
1970
	}
1971
1972
	/**
1973
	 * Gets all plugins currently active in values, regardless of whether they're
1974
	 * traditionally activated or network activated.
1975
	 *
1976
	 * @todo Store the result in core's object cache maybe?
1977
	 */
1978
	public static function get_active_plugins() {
1979
		$active_plugins = (array) get_option( 'active_plugins', array() );
1980
1981
		if ( is_multisite() ) {
1982
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1983
			// whereas active_plugins stores them in the values.
1984
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1985
			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...
1986
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1987
			}
1988
		}
1989
1990
		sort( $active_plugins );
1991
1992
		return array_unique( $active_plugins );
1993
	}
1994
1995
	/**
1996
	 * Gets and parses additional plugin data to send with the heartbeat data
1997
	 *
1998
	 * @since 3.8.1
1999
	 *
2000
	 * @return array Array of plugin data
2001
	 */
2002
	public static function get_parsed_plugin_data() {
2003
		if ( ! function_exists( 'get_plugins' ) ) {
2004
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
2005
		}
2006
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2007
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2008
		$active_plugins = Jetpack::get_active_plugins();
2009
2010
		$plugins = array();
2011
		foreach ( $all_plugins as $path => $plugin_data ) {
2012
			$plugins[ $path ] = array(
2013
					'is_active' => in_array( $path, $active_plugins ),
2014
					'file'      => $path,
2015
					'name'      => $plugin_data['Name'],
2016
					'version'   => $plugin_data['Version'],
2017
					'author'    => $plugin_data['Author'],
2018
			);
2019
		}
2020
2021
		return $plugins;
2022
	}
2023
2024
	/**
2025
	 * Gets and parses theme data to send with the heartbeat data
2026
	 *
2027
	 * @since 3.8.1
2028
	 *
2029
	 * @return array Array of theme data
2030
	 */
2031
	public static function get_parsed_theme_data() {
2032
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2033
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2034
2035
		$themes = array();
2036
		foreach ( $all_themes as $slug => $theme_data ) {
2037
			$theme_headers = array();
2038
			foreach ( $header_keys as $header_key ) {
2039
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2040
			}
2041
2042
			$themes[ $slug ] = array(
2043
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2044
					'slug' => $slug,
2045
					'theme_root' => $theme_data->get_theme_root_uri(),
2046
					'parent' => $theme_data->parent(),
2047
					'headers' => $theme_headers
2048
			);
2049
		}
2050
2051
		return $themes;
2052
	}
2053
2054
	/**
2055
	 * Checks whether a specific plugin is active.
2056
	 *
2057
	 * We don't want to store these in a static variable, in case
2058
	 * there are switch_to_blog() calls involved.
2059
	 */
2060
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2061
		return in_array( $plugin, self::get_active_plugins() );
2062
	}
2063
2064
	/**
2065
	 * Check if Jetpack's Open Graph tags should be used.
2066
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2067
	 *
2068
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2069
	 * @action plugins_loaded
2070
	 * @return null
2071
	 */
2072
	public function check_open_graph() {
2073
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2074
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2075
		}
2076
2077
		$active_plugins = self::get_active_plugins();
2078
2079
		if ( ! empty( $active_plugins ) ) {
2080
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2081
				if ( in_array( $plugin, $active_plugins ) ) {
2082
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2083
					break;
2084
				}
2085
			}
2086
		}
2087
2088
		/**
2089
		 * Allow the addition of Open Graph Meta Tags to all pages.
2090
		 *
2091
		 * @since 2.0.3
2092
		 *
2093
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2094
		 */
2095
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2096
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2097
		}
2098
	}
2099
2100
	/**
2101
	 * Check if Jetpack's Twitter tags should be used.
2102
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2103
	 *
2104
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2105
	 * @action plugins_loaded
2106
	 * @return null
2107
	 */
2108
	public function check_twitter_tags() {
2109
2110
		$active_plugins = self::get_active_plugins();
2111
2112
		if ( ! empty( $active_plugins ) ) {
2113
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2114
				if ( in_array( $plugin, $active_plugins ) ) {
2115
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2116
					break;
2117
				}
2118
			}
2119
		}
2120
2121
		/**
2122
		 * Allow Twitter Card Meta tags to be disabled.
2123
		 *
2124
		 * @since 2.6.0
2125
		 *
2126
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2127
		 */
2128
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2129
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2130
		}
2131
	}
2132
2133
	/**
2134
	 * Allows plugins to submit security reports.
2135
 	 *
2136
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2137
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2138
	 * @param array   $args         See definitions above
2139
	 */
2140
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2141
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2142
	}
2143
2144
/* Jetpack Options API */
2145
2146
	public static function get_option_names( $type = 'compact' ) {
2147
		return Jetpack_Options::get_option_names( $type );
2148
	}
2149
2150
	/**
2151
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2152
 	 *
2153
	 * @param string $name    Option name
2154
	 * @param mixed  $default (optional)
2155
	 */
2156
	public static function get_option( $name, $default = false ) {
2157
		return Jetpack_Options::get_option( $name, $default );
2158
	}
2159
2160
	/**
2161
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2162
 	 *
2163
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2164
	 * @param string $name  Option name
2165
	 * @param mixed  $value Option value
2166
	 */
2167
	public static function update_option( $name, $value ) {
2168
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2169
		return Jetpack_Options::update_option( $name, $value );
2170
	}
2171
2172
	/**
2173
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2174
 	 *
2175
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2176
	 * @param array $array array( option name => option value, ... )
2177
	 */
2178
	public static function update_options( $array ) {
2179
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2180
		return Jetpack_Options::update_options( $array );
2181
	}
2182
2183
	/**
2184
	 * Deletes the given option.  May be passed multiple option names as an array.
2185
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2186
	 *
2187
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2188
	 * @param string|array $names
2189
	 */
2190
	public static function delete_option( $names ) {
2191
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2192
		return Jetpack_Options::delete_option( $names );
2193
	}
2194
2195
	/**
2196
	 * Enters a user token into the user_tokens option
2197
	 *
2198
	 * @param int $user_id
2199
	 * @param string $token
2200
	 * return bool
2201
	 */
2202
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2203
		// not designed for concurrent updates
2204
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2205
		if ( ! is_array( $user_tokens ) )
2206
			$user_tokens = array();
2207
		$user_tokens[$user_id] = $token;
2208
		if ( $is_master_user ) {
2209
			$master_user = $user_id;
2210
			$options     = compact( 'user_tokens', 'master_user' );
2211
		} else {
2212
			$options = compact( 'user_tokens' );
2213
		}
2214
		return Jetpack_Options::update_options( $options );
2215
	}
2216
2217
	/**
2218
	 * Returns an array of all PHP files in the specified absolute path.
2219
	 * Equivalent to glob( "$absolute_path/*.php" ).
2220
	 *
2221
	 * @param string $absolute_path The absolute path of the directory to search.
2222
	 * @return array Array of absolute paths to the PHP files.
2223
	 */
2224
	public static function glob_php( $absolute_path ) {
2225
		if ( function_exists( 'glob' ) ) {
2226
			return glob( "$absolute_path/*.php" );
2227
		}
2228
2229
		$absolute_path = untrailingslashit( $absolute_path );
2230
		$files = array();
2231
		if ( ! $dir = @opendir( $absolute_path ) ) {
2232
			return $files;
2233
		}
2234
2235
		while ( false !== $file = readdir( $dir ) ) {
2236
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2237
				continue;
2238
			}
2239
2240
			$file = "$absolute_path/$file";
2241
2242
			if ( ! is_file( $file ) ) {
2243
				continue;
2244
			}
2245
2246
			$files[] = $file;
2247
		}
2248
2249
		closedir( $dir );
2250
2251
		return $files;
2252
	}
2253
2254
	public static function activate_new_modules( $redirect = false ) {
2255
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2256
			return;
2257
		}
2258
2259
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2260 View Code Duplication
		if ( ! $jetpack_old_version ) {
2261
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2262
			/** This action is documented in class.jetpack.php */
2263
			do_action( 'updating_jetpack_version', $version, false );
2264
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2265
		}
2266
2267
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2268
2269
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2270
			return;
2271
		}
2272
2273
		$active_modules     = Jetpack::get_active_modules();
2274
		$reactivate_modules = array();
2275
		foreach ( $active_modules as $active_module ) {
2276
			$module = Jetpack::get_module( $active_module );
2277
			if ( ! isset( $module['changed'] ) ) {
2278
				continue;
2279
			}
2280
2281
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2282
				continue;
2283
			}
2284
2285
			$reactivate_modules[] = $active_module;
2286
			Jetpack::deactivate_module( $active_module );
2287
		}
2288
2289
		$new_version = JETPACK__VERSION . ':' . time();
2290
		/** This action is documented in class.jetpack.php */
2291
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2292
		Jetpack_Options::update_options(
2293
			array(
2294
				'version'     => $new_version,
2295
				'old_version' => $jetpack_old_version,
2296
			)
2297
		);
2298
2299
		Jetpack::state( 'message', 'modules_activated' );
2300
		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...
2301
2302
		if ( $redirect ) {
2303
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2304
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2305
				$page = $_GET['page'];
2306
			}
2307
2308
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2309
			exit;
2310
		}
2311
	}
2312
2313
	/**
2314
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2315
	 * Make sure to tuck away module "library" files in a sub-directory.
2316
	 */
2317
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2318
		static $modules = null;
2319
2320
		if ( ! isset( $modules ) ) {
2321
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2322
			// Use the cache if we're on the front-end and it's available...
2323
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2324
				$modules = $available_modules_option[ JETPACK__VERSION ];
2325
			} else {
2326
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2327
2328
				$modules = array();
2329
2330
				foreach ( $files as $file ) {
2331
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2332
						continue;
2333
					}
2334
2335
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2336
				}
2337
2338
				Jetpack_Options::update_option( 'available_modules', array(
2339
					JETPACK__VERSION => $modules,
2340
				) );
2341
			}
2342
		}
2343
2344
		/**
2345
		 * Filters the array of modules available to be activated.
2346
		 *
2347
		 * @since 2.4.0
2348
		 *
2349
		 * @param array $modules Array of available modules.
2350
		 * @param string $min_version Minimum version number required to use modules.
2351
		 * @param string $max_version Maximum version number required to use modules.
2352
		 */
2353
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2354
2355
		if ( ! $min_version && ! $max_version ) {
2356
			return array_keys( $mods );
2357
		}
2358
2359
		$r = array();
2360
		foreach ( $mods as $slug => $introduced ) {
2361
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2362
				continue;
2363
			}
2364
2365
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2366
				continue;
2367
			}
2368
2369
			$r[] = $slug;
2370
		}
2371
2372
		return $r;
2373
	}
2374
2375
	/**
2376
	 * Default modules loaded on activation.
2377
	 */
2378
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2379
		$return = array();
2380
2381
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2382
			$module_data = Jetpack::get_module( $module );
2383
2384
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2385
				case 'yes' :
2386
					$return[] = $module;
2387
					break;
2388
				case 'public' :
2389
					if ( Jetpack_Options::get_option( 'public' ) ) {
2390
						$return[] = $module;
2391
					}
2392
					break;
2393
				case 'no' :
2394
				default :
2395
					break;
2396
			}
2397
		}
2398
		/**
2399
		 * Filters the array of default modules.
2400
		 *
2401
		 * @since 2.5.0
2402
		 *
2403
		 * @param array $return Array of default modules.
2404
		 * @param string $min_version Minimum version number required to use modules.
2405
		 * @param string $max_version Maximum version number required to use modules.
2406
		 */
2407
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2408
	}
2409
2410
	/**
2411
	 * Checks activated modules during auto-activation to determine
2412
	 * if any of those modules are being deprecated.  If so, close
2413
	 * them out, and add any replacement modules.
2414
	 *
2415
	 * Runs at priority 99 by default.
2416
	 *
2417
	 * This is run late, so that it can still activate a module if
2418
	 * the new module is a replacement for another that the user
2419
	 * currently has active, even if something at the normal priority
2420
	 * would kibosh everything.
2421
	 *
2422
	 * @since 2.6
2423
	 * @uses jetpack_get_default_modules filter
2424
	 * @param array $modules
2425
	 * @return array
2426
	 */
2427
	function handle_deprecated_modules( $modules ) {
2428
		$deprecated_modules = array(
2429
			'debug'            => null,  // Closed out and moved to the debugger library.
2430
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2431
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2432
		);
2433
2434
		// Don't activate SSO if they never completed activating WPCC.
2435
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2436
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2437
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2438
				$deprecated_modules['wpcc'] = null;
2439
			}
2440
		}
2441
2442
		foreach ( $deprecated_modules as $module => $replacement ) {
2443
			if ( Jetpack::is_module_active( $module ) ) {
2444
				self::deactivate_module( $module );
2445
				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...
2446
					$modules[] = $replacement;
2447
				}
2448
			}
2449
		}
2450
2451
		return array_unique( $modules );
2452
	}
2453
2454
	/**
2455
	 * Checks activated plugins during auto-activation to determine
2456
	 * if any of those plugins are in the list with a corresponding module
2457
	 * that is not compatible with the plugin. The module will not be allowed
2458
	 * to auto-activate.
2459
	 *
2460
	 * @since 2.6
2461
	 * @uses jetpack_get_default_modules filter
2462
	 * @param array $modules
2463
	 * @return array
2464
	 */
2465
	function filter_default_modules( $modules ) {
2466
2467
		$active_plugins = self::get_active_plugins();
2468
2469
		if ( ! empty( $active_plugins ) ) {
2470
2471
			// For each module we'd like to auto-activate...
2472
			foreach ( $modules as $key => $module ) {
2473
				// If there are potential conflicts for it...
2474
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2475
					// For each potential conflict...
2476
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2477
						// If that conflicting plugin is active...
2478
						if ( in_array( $plugin, $active_plugins ) ) {
2479
							// Remove that item from being auto-activated.
2480
							unset( $modules[ $key ] );
2481
						}
2482
					}
2483
				}
2484
			}
2485
		}
2486
2487
		return $modules;
2488
	}
2489
2490
	/**
2491
	 * Extract a module's slug from its full path.
2492
	 */
2493
	public static function get_module_slug( $file ) {
2494
		return str_replace( '.php', '', basename( $file ) );
2495
	}
2496
2497
	/**
2498
	 * Generate a module's path from its slug.
2499
	 */
2500
	public static function get_module_path( $slug ) {
2501
		/**
2502
		 * Filters the path of a modules.
2503
		 *
2504
		 * @since 7.4.0
2505
		 *
2506
		 * @param array $return The absolute path to a module's root php file
2507
		 * @param string $slug The module slug
2508
		 */
2509
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2510
	}
2511
2512
	/**
2513
	 * Load module data from module file. Headers differ from WordPress
2514
	 * plugin headers to avoid them being identified as standalone
2515
	 * plugins on the WordPress plugins page.
2516
	 */
2517
	public static function get_module( $module ) {
2518
		$headers = array(
2519
			'name'                      => 'Module Name',
2520
			'description'               => 'Module Description',
2521
			'sort'                      => 'Sort Order',
2522
			'recommendation_order'      => 'Recommendation Order',
2523
			'introduced'                => 'First Introduced',
2524
			'changed'                   => 'Major Changes In',
2525
			'deactivate'                => 'Deactivate',
2526
			'free'                      => 'Free',
2527
			'requires_connection'       => 'Requires Connection',
2528
			'auto_activate'             => 'Auto Activate',
2529
			'module_tags'               => 'Module Tags',
2530
			'feature'                   => 'Feature',
2531
			'additional_search_queries' => 'Additional Search Queries',
2532
			'plan_classes'              => 'Plans',
2533
		);
2534
2535
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2536
2537
		$mod = Jetpack::get_file_data( $file, $headers );
2538
		if ( empty( $mod['name'] ) ) {
2539
			return false;
2540
		}
2541
2542
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2543
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2544
		$mod['deactivate']              = empty( $mod['deactivate'] );
2545
		$mod['free']                    = empty( $mod['free'] );
2546
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2547
2548
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2549
			$mod['auto_activate'] = 'No';
2550
		} else {
2551
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2552
		}
2553
2554
		if ( $mod['module_tags'] ) {
2555
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2556
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2557
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2558
		} else {
2559
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2560
		}
2561
2562 View Code Duplication
		if ( $mod['plan_classes'] ) {
2563
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2564
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2565
		} else {
2566
			$mod['plan_classes'] = array( 'free' );
2567
		}
2568
2569 View Code Duplication
		if ( $mod['feature'] ) {
2570
			$mod['feature'] = explode( ',', $mod['feature'] );
2571
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2572
		} else {
2573
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2574
		}
2575
2576
		/**
2577
		 * Filters the feature array on a module.
2578
		 *
2579
		 * This filter allows you to control where each module is filtered: Recommended,
2580
		 * and the default "Other" listing.
2581
		 *
2582
		 * @since 3.5.0
2583
		 *
2584
		 * @param array   $mod['feature'] The areas to feature this module:
2585
		 *     'Recommended' shows on the main Jetpack admin screen.
2586
		 *     'Other' should be the default if no other value is in the array.
2587
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2588
		 * @param array   $mod All the currently assembled module data.
2589
		 */
2590
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2591
2592
		/**
2593
		 * Filter the returned data about a module.
2594
		 *
2595
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2596
		 * so please be careful.
2597
		 *
2598
		 * @since 3.6.0
2599
		 *
2600
		 * @param array   $mod    The details of the requested module.
2601
		 * @param string  $module The slug of the module, e.g. sharedaddy
2602
		 * @param string  $file   The path to the module source file.
2603
		 */
2604
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2605
	}
2606
2607
	/**
2608
	 * Like core's get_file_data implementation, but caches the result.
2609
	 */
2610
	public static function get_file_data( $file, $headers ) {
2611
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2612
		$file_name = basename( $file );
2613
2614
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2615
2616
		$file_data_option = get_transient( $cache_key );
2617
2618
		if ( false === $file_data_option ) {
2619
			$file_data_option = array();
2620
		}
2621
2622
		$key           = md5( $file_name . serialize( $headers ) );
2623
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2624
2625
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2626
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2627
			return $file_data_option[ $key ];
2628
		}
2629
2630
		$data = get_file_data( $file, $headers );
2631
2632
		$file_data_option[ $key ] = $data;
2633
2634
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2635
2636
		return $data;
2637
	}
2638
2639
2640
	/**
2641
	 * Return translated module tag.
2642
	 *
2643
	 * @param string $tag Tag as it appears in each module heading.
2644
	 *
2645
	 * @return mixed
2646
	 */
2647
	public static function translate_module_tag( $tag ) {
2648
		return jetpack_get_module_i18n_tag( $tag );
2649
	}
2650
2651
	/**
2652
	 * Get i18n strings as a JSON-encoded string
2653
	 *
2654
	 * @return string The locale as JSON
2655
	 */
2656
	public static function get_i18n_data_json() {
2657
2658
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2659
		// JSON files with the file they should be included for. This is an md5
2660
		// of '_inc/build/admin.js'.
2661
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2662
2663
		$i18n_json =
2664
				   JETPACK__PLUGIN_DIR
2665
				   . 'languages/json/jetpack-'
2666
				   . get_user_locale()
2667
				   . '-'
2668
				   . $path_md5
2669
				   . '.json';
2670
2671
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2672
			$locale_data = @file_get_contents( $i18n_json );
2673
			if ( $locale_data ) {
2674
				return $locale_data;
2675
			}
2676
		}
2677
2678
		// Return valid empty Jed locale
2679
		return '{ "locale_data": { "messages": { "": {} } } }';
2680
	}
2681
2682
	/**
2683
	 * Add locale data setup to wp-i18n
2684
	 *
2685
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2686
	 *
2687
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2688
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2689
	 *
2690
	 * This method provides a safe way to request the setup multiple times but add the script at
2691
	 * most once.
2692
	 *
2693
	 * @since 6.7.0
2694
	 *
2695
	 * @return void
2696
	 */
2697
	public static function setup_wp_i18n_locale_data() {
2698
		static $script_added = false;
2699
		if ( ! $script_added ) {
2700
			$script_added = true;
2701
			wp_add_inline_script(
2702
				'wp-i18n',
2703
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2704
			);
2705
		}
2706
	}
2707
2708
	/**
2709
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2710
	 *
2711
	 * @since 3.9.2
2712
	 *
2713
	 * @param array $modules
2714
	 *
2715
	 * @return string|void
2716
	 */
2717
	public static function get_translated_modules( $modules ) {
2718
		foreach ( $modules as $index => $module ) {
2719
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2720
			if ( isset( $module['name'] ) ) {
2721
				$modules[ $index ]['name'] = $i18n_module['name'];
2722
			}
2723
			if ( isset( $module['description'] ) ) {
2724
				$modules[ $index ]['description'] = $i18n_module['description'];
2725
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2726
			}
2727
		}
2728
		return $modules;
2729
	}
2730
2731
	/**
2732
	 * Get a list of activated modules as an array of module slugs.
2733
	 */
2734
	public static function get_active_modules() {
2735
		$active = Jetpack_Options::get_option( 'active_modules' );
2736
2737
		if ( ! is_array( $active ) ) {
2738
			$active = array();
2739
		}
2740
2741
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2742
			$active[] = 'vaultpress';
2743
		} else {
2744
			$active = array_diff( $active, array( 'vaultpress' ) );
2745
		}
2746
2747
		//If protect is active on the main site of a multisite, it should be active on all sites.
2748
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2749
			$active[] = 'protect';
2750
		}
2751
2752
		/**
2753
		 * Allow filtering of the active modules.
2754
		 *
2755
		 * Gives theme and plugin developers the power to alter the modules that
2756
		 * are activated on the fly.
2757
		 *
2758
		 * @since 5.8.0
2759
		 *
2760
		 * @param array $active Array of active module slugs.
2761
		 */
2762
		$active = apply_filters( 'jetpack_active_modules', $active );
2763
2764
		return array_unique( $active );
2765
	}
2766
2767
	/**
2768
	 * Check whether or not a Jetpack module is active.
2769
	 *
2770
	 * @param string $module The slug of a Jetpack module.
2771
	 * @return bool
2772
	 *
2773
	 * @static
2774
	 */
2775
	public static function is_module_active( $module ) {
2776
		return in_array( $module, self::get_active_modules() );
2777
	}
2778
2779
	public static function is_module( $module ) {
2780
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2781
	}
2782
2783
	/**
2784
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2785
	 *
2786
	 * @param bool $catch True to start catching, False to stop.
2787
	 *
2788
	 * @static
2789
	 */
2790
	public static function catch_errors( $catch ) {
2791
		static $display_errors, $error_reporting;
2792
2793
		if ( $catch ) {
2794
			$display_errors  = @ini_set( 'display_errors', 1 );
2795
			$error_reporting = @error_reporting( E_ALL );
2796
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2797
		} else {
2798
			@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...
2799
			@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...
2800
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2801
		}
2802
	}
2803
2804
	/**
2805
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2806
	 */
2807
	public static function catch_errors_on_shutdown() {
2808
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2809
	}
2810
2811
	/**
2812
	 * Rewrite any string to make paths easier to read.
2813
	 *
2814
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2815
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2816
	 *
2817
	 * @param $string
2818
	 * @return mixed
2819
	 */
2820
	public static function alias_directories( $string ) {
2821
		// ABSPATH has a trailing slash.
2822
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2823
		// WP_CONTENT_DIR does not have a trailing slash.
2824
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2825
2826
		return $string;
2827
	}
2828
2829
	public static function activate_default_modules(
2830
		$min_version = false,
2831
		$max_version = false,
2832
		$other_modules = array(),
2833
		$redirect = true,
2834
		$send_state_messages = true
2835
	) {
2836
		$jetpack = Jetpack::init();
2837
2838
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2839
		$modules = array_merge( $other_modules, $modules );
2840
2841
		// Look for standalone plugins and disable if active.
2842
2843
		$to_deactivate = array();
2844
		foreach ( $modules as $module ) {
2845
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2846
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2847
			}
2848
		}
2849
2850
		$deactivated = array();
2851
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2852
			list( $probable_file, $probable_title ) = $deactivate_me;
2853
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2854
				$deactivated[] = $module;
2855
			}
2856
		}
2857
2858
		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...
2859
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2860
2861
			$url = add_query_arg(
2862
				array(
2863
					'action'   => 'activate_default_modules',
2864
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2865
				),
2866
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2867
			);
2868
			wp_safe_redirect( $url );
2869
			exit;
2870
		}
2871
2872
		/**
2873
		 * Fires before default modules are activated.
2874
		 *
2875
		 * @since 1.9.0
2876
		 *
2877
		 * @param string $min_version Minimum version number required to use modules.
2878
		 * @param string $max_version Maximum version number required to use modules.
2879
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2880
		 */
2881
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2882
2883
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2884
		if ( $send_state_messages ) {
2885
			Jetpack::restate();
2886
			Jetpack::catch_errors( true );
2887
		}
2888
2889
		$active = Jetpack::get_active_modules();
2890
2891
		foreach ( $modules as $module ) {
2892
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2893
				$active[] = $module;
2894
				self::update_active_modules( $active );
2895
				continue;
2896
			}
2897
2898
			if ( $send_state_messages && in_array( $module, $active ) ) {
2899
				$module_info = Jetpack::get_module( $module );
2900 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2901
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2902
					if ( $active_state = Jetpack::state( $state ) ) {
2903
						$active_state = explode( ',', $active_state );
2904
					} else {
2905
						$active_state = array();
2906
					}
2907
					$active_state[] = $module;
2908
					Jetpack::state( $state, implode( ',', $active_state ) );
2909
				}
2910
				continue;
2911
			}
2912
2913
			$file = Jetpack::get_module_path( $module );
2914
			if ( ! file_exists( $file ) ) {
2915
				continue;
2916
			}
2917
2918
			// we'll override this later if the plugin can be included without fatal error
2919
			if ( $redirect ) {
2920
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2921
			}
2922
2923
			if ( $send_state_messages ) {
2924
				Jetpack::state( 'error', 'module_activation_failed' );
2925
				Jetpack::state( 'module', $module );
2926
			}
2927
2928
			ob_start();
2929
			require_once $file;
2930
2931
			$active[] = $module;
2932
2933 View Code Duplication
			if ( $send_state_messages ) {
2934
2935
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2936
				if ( $active_state = Jetpack::state( $state ) ) {
2937
					$active_state = explode( ',', $active_state );
2938
				} else {
2939
					$active_state = array();
2940
				}
2941
				$active_state[] = $module;
2942
				Jetpack::state( $state, implode( ',', $active_state ) );
2943
			}
2944
2945
			Jetpack::update_active_modules( $active );
2946
2947
			ob_end_clean();
2948
		}
2949
2950
		if ( $send_state_messages ) {
2951
			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...
2952
			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...
2953
		}
2954
2955
		Jetpack::catch_errors( false );
2956
		/**
2957
		 * Fires when default modules are activated.
2958
		 *
2959
		 * @since 1.9.0
2960
		 *
2961
		 * @param string $min_version Minimum version number required to use modules.
2962
		 * @param string $max_version Maximum version number required to use modules.
2963
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2964
		 */
2965
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2966
	}
2967
2968
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2969
		/**
2970
		 * Fires before a module is activated.
2971
		 *
2972
		 * @since 2.6.0
2973
		 *
2974
		 * @param string $module Module slug.
2975
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2976
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2977
		 */
2978
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2979
2980
		$jetpack = Jetpack::init();
2981
2982
		if ( ! strlen( $module ) )
2983
			return false;
2984
2985
		if ( ! Jetpack::is_module( $module ) )
2986
			return false;
2987
2988
		// If it's already active, then don't do it again
2989
		$active = Jetpack::get_active_modules();
2990
		foreach ( $active as $act ) {
2991
			if ( $act == $module )
2992
				return true;
2993
		}
2994
2995
		$module_data = Jetpack::get_module( $module );
2996
2997
		if ( ! Jetpack::is_active() ) {
2998
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2999
				return false;
3000
3001
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3002
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
3003
				return false;
3004
		}
3005
3006
		// Check and see if the old plugin is active
3007
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3008
			// Deactivate the old plugin
3009
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3010
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3011
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3012
				Jetpack::state( 'deactivated_plugins', $module );
3013
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3014
				exit;
3015
			}
3016
		}
3017
3018
		// Protect won't work with mis-configured IPs
3019
		if ( 'protect' === $module ) {
3020
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3021
			if ( ! jetpack_protect_get_ip() ) {
3022
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3023
				return false;
3024
			}
3025
		}
3026
3027
		if ( ! Jetpack_Plan::supports( $module ) ) {
3028
			return false;
3029
		}
3030
3031
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3032
		Jetpack::state( 'module', $module );
3033
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3034
3035
		Jetpack::catch_errors( true );
3036
		ob_start();
3037
		require Jetpack::get_module_path( $module );
3038
		/** This action is documented in class.jetpack.php */
3039
		do_action( 'jetpack_activate_module', $module );
3040
		$active[] = $module;
3041
		Jetpack::update_active_modules( $active );
3042
3043
		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...
3044
		ob_end_clean();
3045
		Jetpack::catch_errors( false );
3046
3047
		if ( $redirect ) {
3048
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3049
		}
3050
		if ( $exit ) {
3051
			exit;
3052
		}
3053
		return true;
3054
	}
3055
3056
	function activate_module_actions( $module ) {
3057
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3058
	}
3059
3060
	public static function deactivate_module( $module ) {
3061
		/**
3062
		 * Fires when a module is deactivated.
3063
		 *
3064
		 * @since 1.9.0
3065
		 *
3066
		 * @param string $module Module slug.
3067
		 */
3068
		do_action( 'jetpack_pre_deactivate_module', $module );
3069
3070
		$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...
3071
3072
		$active = Jetpack::get_active_modules();
3073
		$new    = array_filter( array_diff( $active, (array) $module ) );
3074
3075
		return self::update_active_modules( $new );
3076
	}
3077
3078
	public static function enable_module_configurable( $module ) {
3079
		$module = Jetpack::get_module_slug( $module );
3080
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3081
	}
3082
3083
	/**
3084
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3085
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3086
	 *
3087
	 * @param string $module Module slug
3088
	 * @return string $url module configuration URL
3089
	 */
3090
	public static function module_configuration_url( $module ) {
3091
		$module = Jetpack::get_module_slug( $module );
3092
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3093
		/**
3094
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3095
		 *
3096
		 * @since 6.9.0
3097
		 *
3098
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3099
		 */
3100
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3101
3102
		return $url;
3103
	}
3104
3105
/* Installation */
3106
	public static function bail_on_activation( $message, $deactivate = true ) {
3107
?>
3108
<!doctype html>
3109
<html>
3110
<head>
3111
<meta charset="<?php bloginfo( 'charset' ); ?>">
3112
<style>
3113
* {
3114
	text-align: center;
3115
	margin: 0;
3116
	padding: 0;
3117
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3118
}
3119
p {
3120
	margin-top: 1em;
3121
	font-size: 18px;
3122
}
3123
</style>
3124
<body>
3125
<p><?php echo esc_html( $message ); ?></p>
3126
</body>
3127
</html>
3128
<?php
3129
		if ( $deactivate ) {
3130
			$plugins = get_option( 'active_plugins' );
3131
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3132
			$update  = false;
3133
			foreach ( $plugins as $i => $plugin ) {
3134
				if ( $plugin === $jetpack ) {
3135
					$plugins[$i] = false;
3136
					$update = true;
3137
				}
3138
			}
3139
3140
			if ( $update ) {
3141
				update_option( 'active_plugins', array_filter( $plugins ) );
3142
			}
3143
		}
3144
		exit;
3145
	}
3146
3147
	/**
3148
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3149
	 * @static
3150
	 */
3151
	public static function plugin_activation( $network_wide ) {
3152
		Jetpack_Options::update_option( 'activated', 1 );
3153
3154
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3155
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3156
		}
3157
3158
		if ( $network_wide )
3159
			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...
3160
3161
		// For firing one-off events (notices) immediately after activation
3162
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3163
3164
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3165
3166
		Jetpack::plugin_initialize();
3167
	}
3168
3169
	public static function get_activation_source( $referer_url ) {
3170
3171
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3172
			return array( 'wp-cli', null );
3173
		}
3174
3175
		$referer = parse_url( $referer_url );
3176
3177
		$source_type = 'unknown';
3178
		$source_query = null;
3179
3180
		if ( ! is_array( $referer ) ) {
3181
			return array( $source_type, $source_query );
3182
		}
3183
3184
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3185
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3186
3187
		if ( isset( $referer['query'] ) ) {
3188
			parse_str( $referer['query'], $query_parts );
3189
		} else {
3190
			$query_parts = array();
3191
		}
3192
3193
		if ( $plugins_path === $referer['path'] ) {
3194
			$source_type = 'list';
3195
		} elseif ( $plugins_install_path === $referer['path'] ) {
3196
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3197
			switch( $tab ) {
3198
				case 'popular':
3199
					$source_type = 'popular';
3200
					break;
3201
				case 'recommended':
3202
					$source_type = 'recommended';
3203
					break;
3204
				case 'favorites':
3205
					$source_type = 'favorites';
3206
					break;
3207
				case 'search':
3208
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3209
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3210
					break;
3211
				default:
3212
					$source_type = 'featured';
3213
			}
3214
		}
3215
3216
		return array( $source_type, $source_query );
3217
	}
3218
3219
	/**
3220
	 * Runs before bumping version numbers up to a new version
3221
	 * @param  string $version    Version:timestamp
3222
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3223
	 * @return null              [description]
3224
	 */
3225
	public static function do_version_bump( $version, $old_version ) {
3226
		if ( ! $old_version ) { // For new sites
3227
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3228
		}
3229
	}
3230
3231
	/**
3232
	 * Sets the internal version number and activation state.
3233
	 * @static
3234
	 */
3235
	public static function plugin_initialize() {
3236
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3237
			Jetpack_Options::update_option( 'activated', 2 );
3238
		}
3239
3240 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3241
			$version = $old_version = JETPACK__VERSION . ':' . time();
3242
			/** This action is documented in class.jetpack.php */
3243
			do_action( 'updating_jetpack_version', $version, false );
3244
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3245
		}
3246
3247
		Jetpack::load_modules();
3248
3249
		Jetpack_Options::delete_option( 'do_activate' );
3250
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3251
	}
3252
3253
	/**
3254
	 * Removes all connection options
3255
	 * @static
3256
	 */
3257
	public static function plugin_deactivation( ) {
3258
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3259
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3260
			Jetpack_Network::init()->deactivate();
3261
		} else {
3262
			Jetpack::disconnect( false );
3263
			//Jetpack_Heartbeat::init()->deactivate();
3264
		}
3265
	}
3266
3267
	/**
3268
	 * Disconnects from the Jetpack servers.
3269
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3270
	 * @static
3271
	 */
3272
	public static function disconnect( $update_activated_state = true ) {
3273
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3274
		Jetpack::clean_nonces( true );
3275
3276
		// If the site is in an IDC because sync is not allowed,
3277
		// let's make sure to not disconnect the production site.
3278
		if ( ! self::validate_sync_error_idc_option() ) {
3279
			$tracking = new Tracking();
3280
			$tracking->record_user_event( 'disconnect_site', array() );
3281
			Jetpack::load_xml_rpc_client();
3282
			$xml = new Jetpack_IXR_Client();
3283
			$xml->query( 'jetpack.deregister' );
3284
		}
3285
3286
		Jetpack_Options::delete_option(
3287
			array(
3288
				'blog_token',
3289
				'user_token',
3290
				'user_tokens',
3291
				'master_user',
3292
				'time_diff',
3293
				'fallback_no_verify_ssl_certs',
3294
			)
3295
		);
3296
3297
		Jetpack_IDC::clear_all_idc_options();
3298
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3299
3300
		if ( $update_activated_state ) {
3301
			Jetpack_Options::update_option( 'activated', 4 );
3302
		}
3303
3304
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3305
			// Check then record unique disconnection if site has never been disconnected previously
3306
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3307
				$jetpack_unique_connection['disconnected'] = 1;
3308
			} else {
3309
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3310
					//track unique disconnect
3311
					$jetpack = Jetpack::init();
3312
3313
					$jetpack->stat( 'connections', 'unique-disconnect' );
3314
					$jetpack->do_stats( 'server_side' );
3315
				}
3316
				// increment number of times disconnected
3317
				$jetpack_unique_connection['disconnected'] += 1;
3318
			}
3319
3320
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3321
		}
3322
3323
		// Delete cached connected user data
3324
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3325
		delete_transient( $transient_key );
3326
3327
		// Delete all the sync related data. Since it could be taking up space.
3328
		Sender::get_instance()->uninstall();
3329
3330
		// Disable the Heartbeat cron
3331
		Jetpack_Heartbeat::init()->deactivate();
3332
	}
3333
3334
	/**
3335
	 * Unlinks the current user from the linked WordPress.com user
3336
	 */
3337
	public static function unlink_user( $user_id = null ) {
3338
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3339
			return false;
3340
3341
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3342
3343
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3344
			return false;
3345
3346
		if ( ! isset( $tokens[ $user_id ] ) )
3347
			return false;
3348
3349
		Jetpack::load_xml_rpc_client();
3350
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3351
		$xml->query( 'jetpack.unlink_user', $user_id );
3352
3353
		unset( $tokens[ $user_id ] );
3354
3355
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3356
3357
		/**
3358
		 * Fires after the current user has been unlinked from WordPress.com.
3359
		 *
3360
		 * @since 4.1.0
3361
		 *
3362
		 * @param int $user_id The current user's ID.
3363
		 */
3364
		do_action( 'jetpack_unlinked_user', $user_id );
3365
3366
		return true;
3367
	}
3368
3369
	/**
3370
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3371
	 */
3372
	public static function try_registration() {
3373
		// The user has agreed to the TOS at some point by now.
3374
		Jetpack_Options::update_option( 'tos_agreed', true );
3375
3376
		// Let's get some testing in beta versions and such.
3377
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3378
			// Before attempting to connect, let's make sure that the domains are viable.
3379
			$domains_to_check = array_unique( array(
3380
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3381
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3382
			) );
3383
			foreach ( $domains_to_check as $domain ) {
3384
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3383 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...
3385
				if ( is_wp_error( $result ) ) {
3386
					return $result;
3387
				}
3388
			}
3389
		}
3390
3391
		$result = Jetpack::register();
3392
3393
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3394
		if ( ! $result || is_wp_error( $result ) ) {
3395
			return $result;
3396
		} else {
3397
			return true;
3398
		}
3399
	}
3400
3401
	/**
3402
	 * Tracking an internal event log. Try not to put too much chaff in here.
3403
	 *
3404
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3405
	 */
3406
	public static function log( $code, $data = null ) {
3407
		// only grab the latest 200 entries
3408
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3409
3410
		// Append our event to the log
3411
		$log_entry = array(
3412
			'time'    => time(),
3413
			'user_id' => get_current_user_id(),
3414
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3415
			'code'    => $code,
3416
		);
3417
		// Don't bother storing it unless we've got some.
3418
		if ( ! is_null( $data ) ) {
3419
			$log_entry['data'] = $data;
3420
		}
3421
		$log[] = $log_entry;
3422
3423
		// Try add_option first, to make sure it's not autoloaded.
3424
		// @todo: Add an add_option method to Jetpack_Options
3425
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3426
			Jetpack_Options::update_option( 'log', $log );
3427
		}
3428
3429
		/**
3430
		 * Fires when Jetpack logs an internal event.
3431
		 *
3432
		 * @since 3.0.0
3433
		 *
3434
		 * @param array $log_entry {
3435
		 *	Array of details about the log entry.
3436
		 *
3437
		 *	@param string time Time of the event.
3438
		 *	@param int user_id ID of the user who trigerred the event.
3439
		 *	@param int blog_id Jetpack Blog ID.
3440
		 *	@param string code Unique name for the event.
3441
		 *	@param string data Data about the event.
3442
		 * }
3443
		 */
3444
		do_action( 'jetpack_log_entry', $log_entry );
3445
	}
3446
3447
	/**
3448
	 * Get the internal event log.
3449
	 *
3450
	 * @param $event (string) - only return the specific log events
3451
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3452
	 *
3453
	 * @return array of log events || WP_Error for invalid params
3454
	 */
3455
	public static function get_log( $event = false, $num = false ) {
3456
		if ( $event && ! is_string( $event ) ) {
3457
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

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

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

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

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

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

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

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

Loading history...
3462
		}
3463
3464
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3465
3466
		// If nothing set - act as it did before, otherwise let's start customizing the output
3467
		if ( ! $num && ! $event ) {
3468
			return $entire_log;
3469
		} else {
3470
			$entire_log = array_reverse( $entire_log );
3471
		}
3472
3473
		$custom_log_output = array();
3474
3475
		if ( $event ) {
3476
			foreach ( $entire_log as $log_event ) {
3477
				if ( $event == $log_event[ 'code' ] ) {
3478
					$custom_log_output[] = $log_event;
3479
				}
3480
			}
3481
		} else {
3482
			$custom_log_output = $entire_log;
3483
		}
3484
3485
		if ( $num ) {
3486
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3487
		}
3488
3489
		return $custom_log_output;
3490
	}
3491
3492
	/**
3493
	 * Log modification of important settings.
3494
	 */
3495
	public static function log_settings_change( $option, $old_value, $value ) {
3496
		switch( $option ) {
3497
			case 'jetpack_sync_non_public_post_stati':
3498
				self::log( $option, $value );
3499
				break;
3500
		}
3501
	}
3502
3503
	/**
3504
	 * Return stat data for WPCOM sync
3505
	 */
3506
	public static function get_stat_data( $encode = true, $extended = true ) {
3507
		$data = Jetpack_Heartbeat::generate_stats_array();
3508
3509
		if ( $extended ) {
3510
			$additional_data = self::get_additional_stat_data();
3511
			$data = array_merge( $data, $additional_data );
3512
		}
3513
3514
		if ( $encode ) {
3515
			return json_encode( $data );
3516
		}
3517
3518
		return $data;
3519
	}
3520
3521
	/**
3522
	 * Get additional stat data to sync to WPCOM
3523
	 */
3524
	public static function get_additional_stat_data( $prefix = '' ) {
3525
		$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...
3526
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3527
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3528
		$return["{$prefix}site-count"]     = 0;
3529
3530
		if ( function_exists( 'get_blog_count' ) ) {
3531
			$return["{$prefix}site-count"] = get_blog_count();
3532
		}
3533
		return $return;
3534
	}
3535
3536
	private static function get_site_user_count() {
3537
		global $wpdb;
3538
3539
		if ( function_exists( 'wp_is_large_network' ) ) {
3540
			if ( wp_is_large_network( 'users' ) ) {
3541
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3542
			}
3543
		}
3544
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3545
			// It wasn't there, so regenerate the data and save the transient
3546
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3547
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3548
		}
3549
		return $user_count;
3550
	}
3551
3552
	/* Admin Pages */
3553
3554
	function admin_init() {
3555
		// If the plugin is not connected, display a connect message.
3556
		if (
3557
			// the plugin was auto-activated and needs its candy
3558
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3559
		||
3560
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3561
			! Jetpack_Options::get_option( 'activated' )
3562
		) {
3563
			Jetpack::plugin_initialize();
3564
		}
3565
3566
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3567
			Jetpack_Connection_Banner::init();
3568
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3569
			// Upgrade: 1.1 -> 1.1.1
3570
			// Check and see if host can verify the Jetpack servers' SSL certificate
3571
			$args = array();
3572
			Client::_wp_remote_request(
3573
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3574
				$args,
3575
				true
3576
			);
3577
		}
3578
3579
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3580
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3581
		}
3582
3583
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3584
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3585
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3586
3587
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3588
			// Artificially throw errors in certain whitelisted cases during plugin activation
3589
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3590
		}
3591
3592
		// Add custom column in wp-admin/users.php to show whether user is linked.
3593
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3594
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3595
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3596
	}
3597
3598
	function admin_body_class( $admin_body_class = '' ) {
3599
		$classes = explode( ' ', trim( $admin_body_class ) );
3600
3601
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3602
3603
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3604
		return " $admin_body_class ";
3605
	}
3606
3607
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3608
		return $admin_body_class . ' jetpack-pagestyles ';
3609
	}
3610
3611
	/**
3612
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3613
	 * This function artificially throws errors for such cases (whitelisted).
3614
	 *
3615
	 * @param string $plugin The activated plugin.
3616
	 */
3617
	function throw_error_on_activate_plugin( $plugin ) {
3618
		$active_modules = Jetpack::get_active_modules();
3619
3620
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3621
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3622
			$throw = false;
3623
3624
			// Try and make sure it really was the stats plugin
3625
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3626
				if ( 'stats.php' == basename( $plugin ) ) {
3627
					$throw = true;
3628
				}
3629
			} else {
3630
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3631
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3632
					$throw = true;
3633
				}
3634
			}
3635
3636
			if ( $throw ) {
3637
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3638
			}
3639
		}
3640
	}
3641
3642
	function intercept_plugin_error_scrape_init() {
3643
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3644
	}
3645
3646
	function intercept_plugin_error_scrape( $action, $result ) {
3647
		if ( ! $result ) {
3648
			return;
3649
		}
3650
3651
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3652
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3653
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3654
			}
3655
		}
3656
	}
3657
3658
	function add_remote_request_handlers() {
3659
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3660
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3661
	}
3662
3663
	function remote_request_handlers() {
3664
		$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...
3665
3666
		switch ( current_filter() ) {
3667
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3668
			$response = $this->upload_handler();
3669
			break;
3670
3671
		case 'wp_ajax_nopriv_jetpack_update_file' :
3672
			$response = $this->upload_handler( true );
3673
			break;
3674
		default :
3675
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_handler'.

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

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

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

Loading history...
3676
			break;
3677
		}
3678
3679
		if ( ! $response ) {
3680
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_error'.

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

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

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

Loading history...
3681
		}
3682
3683
		if ( is_wp_error( $response ) ) {
3684
			$status_code       = $response->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<Jetpack_Error>.

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

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

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

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

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

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

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

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

Loading history...
3687
3688
			if ( ! is_int( $status_code ) ) {
3689
				$status_code = 400;
3690
			}
3691
3692
			status_header( $status_code );
3693
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3694
		}
3695
3696
		status_header( 200 );
3697
		if ( true === $response ) {
3698
			exit;
3699
		}
3700
3701
		die( json_encode( (object) $response ) );
3702
	}
3703
3704
	/**
3705
	 * Uploads a file gotten from the global $_FILES.
3706
	 * If `$update_media_item` is true and `post_id` is defined
3707
	 * the attachment file of the media item (gotten through of the post_id)
3708
	 * will be updated instead of add a new one.
3709
	 *
3710
	 * @param  boolean $update_media_item - update media attachment
3711
	 * @return array - An array describing the uploadind files process
3712
	 */
3713
	function upload_handler( $update_media_item = false ) {
3714
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3715
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 405.

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

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

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

Loading history...
3716
		}
3717
3718
		$user = wp_authenticate( '', '' );
3719
		if ( ! $user || is_wp_error( $user ) ) {
3720
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 403.

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

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

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

Loading history...
3721
		}
3722
3723
		wp_set_current_user( $user->ID );
3724
3725
		if ( ! current_user_can( 'upload_files' ) ) {
3726
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

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

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

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

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

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

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

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

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

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

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

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

Loading history...
3736
			}
3737
		}
3738
3739
		$media_keys = array_keys( $_FILES['media'] );
3740
3741
		$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...
3742
		if ( ! $token || is_wp_error( $token ) ) {
3743
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
3744
		}
3745
3746
		$uploaded_files = array();
3747
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3748
		unset( $GLOBALS['post'] );
3749
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3750
			$file = array();
3751
			foreach ( $media_keys as $media_key ) {
3752
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3753
			}
3754
3755
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3756
3757
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3758
			if ( $hmac_provided !== $hmac_file ) {
3759
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3760
				continue;
3761
			}
3762
3763
			$_FILES['.jetpack.upload.'] = $file;
3764
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3765
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3766
				$post_id = 0;
3767
			}
3768
3769
			if ( $update_media_item ) {
3770
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3771
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'invalid_input'.

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

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

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

Loading history...
3772
				}
3773
3774
				$media_array = $_FILES['media'];
3775
3776
				$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...
3777
				$file_array['type'] = $media_array['type'][0];
3778
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3779
				$file_array['error'] = $media_array['error'][0];
3780
				$file_array['size'] = $media_array['size'][0];
3781
3782
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3783
3784
				if ( is_wp_error( $edited_media_item ) ) {
3785
					return $edited_media_item;
3786
				}
3787
3788
				$response = (object) array(
3789
					'id'   => (string) $post_id,
3790
					'file' => (string) $edited_media_item->post_title,
3791
					'url'  => (string) wp_get_attachment_url( $post_id ),
3792
					'type' => (string) $edited_media_item->post_mime_type,
3793
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3794
				);
3795
3796
				return (array) array( $response );
3797
			}
3798
3799
			$attachment_id = media_handle_upload(
3800
				'.jetpack.upload.',
3801
				$post_id,
3802
				array(),
3803
				array(
3804
					'action' => 'jetpack_upload_file',
3805
				)
3806
			);
3807
3808
			if ( ! $attachment_id ) {
3809
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3810
			} elseif ( is_wp_error( $attachment_id ) ) {
3811
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3812
			} else {
3813
				$attachment = get_post( $attachment_id );
3814
				$uploaded_files[$index] = (object) array(
3815
					'id'   => (string) $attachment_id,
3816
					'file' => $attachment->post_title,
3817
					'url'  => wp_get_attachment_url( $attachment_id ),
3818
					'type' => $attachment->post_mime_type,
3819
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3820
				);
3821
				// Zip files uploads are not supported unless they are done for installation purposed
3822
				// lets delete them in case something goes wrong in this whole process
3823
				if ( 'application/zip' === $attachment->post_mime_type ) {
3824
					// Schedule a cleanup for 2 hours from now in case of failed install.
3825
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3826
				}
3827
			}
3828
		}
3829
		if ( ! is_null( $global_post ) ) {
3830
			$GLOBALS['post'] = $global_post;
3831
		}
3832
3833
		return $uploaded_files;
3834
	}
3835
3836
	/**
3837
	 * Add help to the Jetpack page
3838
	 *
3839
	 * @since Jetpack (1.2.3)
3840
	 * @return false if not the Jetpack page
3841
	 */
3842
	function admin_help() {
3843
		$current_screen = get_current_screen();
3844
3845
		// Overview
3846
		$current_screen->add_help_tab(
3847
			array(
3848
				'id'		=> 'home',
3849
				'title'		=> __( 'Home', 'jetpack' ),
3850
				'content'	=>
3851
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3852
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3853
					'<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>',
3854
			)
3855
		);
3856
3857
		// Screen Content
3858
		if ( current_user_can( 'manage_options' ) ) {
3859
			$current_screen->add_help_tab(
3860
				array(
3861
					'id'		=> 'settings',
3862
					'title'		=> __( 'Settings', 'jetpack' ),
3863
					'content'	=>
3864
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3865
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3866
						'<ol>' .
3867
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3868
							'<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>' .
3869
						'</ol>' .
3870
						'<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>'
3871
				)
3872
			);
3873
		}
3874
3875
		// Help Sidebar
3876
		$current_screen->set_help_sidebar(
3877
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3878
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3879
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3880
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3881
		);
3882
	}
3883
3884
	function admin_menu_css() {
3885
		wp_enqueue_style( 'jetpack-icons' );
3886
	}
3887
3888
	function admin_menu_order() {
3889
		return true;
3890
	}
3891
3892 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3893
		$jp_menu_order = array();
3894
3895
		foreach ( $menu_order as $index => $item ) {
3896
			if ( $item != 'jetpack' ) {
3897
				$jp_menu_order[] = $item;
3898
			}
3899
3900
			if ( $index == 0 ) {
3901
				$jp_menu_order[] = 'jetpack';
3902
			}
3903
		}
3904
3905
		return $jp_menu_order;
3906
	}
3907
3908
	function admin_banner_styles() {
3909
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3910
3911
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3912
			wp_register_style(
3913
				'jetpack-dops-style',
3914
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3915
				array(),
3916
				JETPACK__VERSION
3917
			);
3918
		}
3919
3920
		wp_enqueue_style(
3921
			'jetpack',
3922
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3923
			array( 'jetpack-dops-style' ),
3924
			 JETPACK__VERSION . '-20121016'
3925
		);
3926
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3927
		wp_style_add_data( 'jetpack', 'suffix', $min );
3928
	}
3929
3930
	function plugin_action_links( $actions ) {
3931
3932
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3933
3934
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3935
			return array_merge(
3936
				$jetpack_home,
3937
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3938
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3939
				$actions
3940
				);
3941
			}
3942
3943
		return array_merge( $jetpack_home, $actions );
3944
	}
3945
3946
	/*
3947
	 * Registration flow:
3948
	 * 1 - ::admin_page_load() action=register
3949
	 * 2 - ::try_registration()
3950
	 * 3 - ::register()
3951
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3952
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3953
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3954
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3955
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3956
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3957
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3958
	 *       jetpack_id, jetpack_secret, jetpack_public
3959
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3960
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3961
	 * 5 - user logs in with WP.com account
3962
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3963
	 *		- Jetpack_Client_Server::authorize()
3964
	 *		- Jetpack_Client_Server::get_token()
3965
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3966
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3967
	 *			- which responds with access_token, token_type, scope
3968
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3969
	 *		- Jetpack::activate_default_modules()
3970
	 *     		- Deactivates deprecated plugins
3971
	 *     		- Activates all default modules
3972
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3973
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3974
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3975
	 *     Done!
3976
	 */
3977
3978
	/**
3979
	 * Handles the page load events for the Jetpack admin page
3980
	 */
3981
	function admin_page_load() {
3982
		$error = false;
3983
3984
		// Make sure we have the right body class to hook stylings for subpages off of.
3985
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3986
3987
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3988
			// Should only be used in intermediate redirects to preserve state across redirects
3989
			Jetpack::restate();
3990
		}
3991
3992
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3993
			// @todo: Add validation against a known whitelist
3994
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3995
			// User clicked in the iframe to link their accounts
3996
			if ( ! Jetpack::is_user_connected() ) {
3997
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3998
3999
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4000
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4001
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4002
4003
				if ( isset( $_GET['notes_iframe'] ) )
4004
					$connect_url .= '&notes_iframe';
4005
				wp_redirect( $connect_url );
4006
				exit;
4007
			} else {
4008
				if ( ! isset( $_GET['calypso_env'] ) ) {
4009
					Jetpack::state( 'message', 'already_authorized' );
4010
					wp_safe_redirect( Jetpack::admin_url() );
4011
					exit;
4012
				} else {
4013
					$connect_url = $this->build_connect_url( true, false, $from );
4014
					$connect_url .= '&already_authorized=true';
4015
					wp_redirect( $connect_url );
4016
					exit;
4017
				}
4018
			}
4019
		}
4020
4021
4022
		if ( isset( $_GET['action'] ) ) {
4023
			switch ( $_GET['action'] ) {
4024
			case 'authorize':
4025
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4026
					Jetpack::state( 'message', 'already_authorized' );
4027
					wp_safe_redirect( Jetpack::admin_url() );
4028
					exit;
4029
				}
4030
				Jetpack::log( 'authorize' );
4031
				$client_server = new Jetpack_Client_Server;
4032
				$client_server->client_authorize();
4033
				exit;
4034
			case 'register' :
4035
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4036
					$error = 'cheatin';
4037
					break;
4038
				}
4039
				check_admin_referer( 'jetpack-register' );
4040
				Jetpack::log( 'register' );
4041
				Jetpack::maybe_set_version_option();
4042
				$registered = Jetpack::try_registration();
4043
				if ( is_wp_error( $registered ) ) {
4044
					$error = $registered->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

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

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

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

Loading history...
4047
4048
					/**
4049
					 * Jetpack registration Error.
4050
					 *
4051
					 * @since 7.5.0
4052
					 *
4053
					 * @param string|int $error The error code.
4054
					 * @param \WP_Error $registered The error object.
4055
					 */
4056
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4057
					break;
4058
				}
4059
4060
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4061
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4062
4063
				/**
4064
				 * Jetpack registration Success.
4065
				 *
4066
				 * @since 7.5.0
4067
				 *
4068
				 * @param string $from 'from' GET parameter;
4069
				 */
4070
				do_action( 'jetpack_connection_register_success', $from );
4071
4072
				$url = $this->build_connect_url( true, $redirect, $from );
4073
4074
				if ( ! empty( $_GET['onboarding'] ) ) {
4075
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4076
				}
4077
4078
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4079
					$url = add_query_arg( 'auth_approved', 'true', $url );
4080
				}
4081
4082
				wp_redirect( $url );
4083
				exit;
4084
			case 'activate' :
4085
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4086
					$error = 'cheatin';
4087
					break;
4088
				}
4089
4090
				$module = stripslashes( $_GET['module'] );
4091
				check_admin_referer( "jetpack_activate-$module" );
4092
				Jetpack::log( 'activate', $module );
4093
				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...
4094
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4095
				}
4096
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4097
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4098
				exit;
4099
			case 'activate_default_modules' :
4100
				check_admin_referer( 'activate_default_modules' );
4101
				Jetpack::log( 'activate_default_modules' );
4102
				Jetpack::restate();
4103
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4104
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4105
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4106
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4107
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4108
				exit;
4109
			case 'disconnect' :
4110
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4111
					$error = 'cheatin';
4112
					break;
4113
				}
4114
4115
				check_admin_referer( 'jetpack-disconnect' );
4116
				Jetpack::log( 'disconnect' );
4117
				Jetpack::disconnect();
4118
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4119
				exit;
4120
			case 'reconnect' :
4121
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4122
					$error = 'cheatin';
4123
					break;
4124
				}
4125
4126
				check_admin_referer( 'jetpack-reconnect' );
4127
				Jetpack::log( 'reconnect' );
4128
				$this->disconnect();
4129
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4130
				exit;
4131 View Code Duplication
			case 'deactivate' :
4132
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4133
					$error = 'cheatin';
4134
					break;
4135
				}
4136
4137
				$modules = stripslashes( $_GET['module'] );
4138
				check_admin_referer( "jetpack_deactivate-$modules" );
4139
				foreach ( explode( ',', $modules ) as $module ) {
4140
					Jetpack::log( 'deactivate', $module );
4141
					Jetpack::deactivate_module( $module );
4142
					Jetpack::state( 'message', 'module_deactivated' );
4143
				}
4144
				Jetpack::state( 'module', $modules );
4145
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4146
				exit;
4147
			case 'unlink' :
4148
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4149
				check_admin_referer( 'jetpack-unlink' );
4150
				Jetpack::log( 'unlink' );
4151
				$this->unlink_user();
4152
				Jetpack::state( 'message', 'unlinked' );
4153
				if ( 'sub-unlink' == $redirect ) {
4154
					wp_safe_redirect( admin_url() );
4155
				} else {
4156
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4157
				}
4158
				exit;
4159
			case 'onboard' :
4160
				if ( ! current_user_can( 'manage_options' ) ) {
4161
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4162
				} else {
4163
					Jetpack::create_onboarding_token();
4164
					$url = $this->build_connect_url( true );
4165
4166
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4167
						$url = add_query_arg( 'onboarding', $token, $url );
4168
					}
4169
4170
					$calypso_env = $this->get_calypso_env();
4171
					if ( ! empty( $calypso_env ) ) {
4172
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4173
					}
4174
4175
					wp_redirect( $url );
4176
					exit;
4177
				}
4178
				exit;
4179
			default:
4180
				/**
4181
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4182
				 *
4183
				 * @since 2.6.0
4184
				 *
4185
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4186
				 */
4187
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4188
			}
4189
		}
4190
4191
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4192
			self::activate_new_modules( true );
4193
		}
4194
4195
		$message_code = Jetpack::state( 'message' );
4196
		if ( Jetpack::state( 'optin-manage' ) ) {
4197
			$activated_manage = $message_code;
4198
			$message_code = 'jetpack-manage';
4199
		}
4200
4201
		switch ( $message_code ) {
4202
		case 'jetpack-manage':
4203
			$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>';
4204
			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...
4205
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4206
			}
4207
			break;
4208
4209
		}
4210
4211
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4212
4213
		if ( ! empty( $deactivated_plugins ) ) {
4214
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4215
			$deactivated_titles  = array();
4216
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4217
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4218
					continue;
4219
				}
4220
4221
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4222
			}
4223
4224
			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...
4225
				if ( $this->message ) {
4226
					$this->message .= "<br /><br />\n";
4227
				}
4228
4229
				$this->message .= wp_sprintf(
4230
					_n(
4231
						'Jetpack contains the most recent version of the old %l plugin.',
4232
						'Jetpack contains the most recent versions of the old %l plugins.',
4233
						count( $deactivated_titles ),
4234
						'jetpack'
4235
					),
4236
					$deactivated_titles
4237
				);
4238
4239
				$this->message .= "<br />\n";
4240
4241
				$this->message .= _n(
4242
					'The old version has been deactivated and can be removed from your site.',
4243
					'The old versions have been deactivated and can be removed from your site.',
4244
					count( $deactivated_titles ),
4245
					'jetpack'
4246
				);
4247
			}
4248
		}
4249
4250
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4251
4252
		if ( $this->message || $this->error || $this->privacy_checks ) {
4253
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4254
		}
4255
4256
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4257
	}
4258
4259
	function admin_notices() {
4260
4261
		if ( $this->error ) {
4262
?>
4263
<div id="message" class="jetpack-message jetpack-err">
4264
	<div class="squeezer">
4265
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4266
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4267
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4268
<?php	endif; ?>
4269
	</div>
4270
</div>
4271
<?php
4272
		}
4273
4274
		if ( $this->message ) {
4275
?>
4276
<div id="message" class="jetpack-message">
4277
	<div class="squeezer">
4278
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4279
	</div>
4280
</div>
4281
<?php
4282
		}
4283
4284
		if ( $this->privacy_checks ) :
4285
			$module_names = $module_slugs = array();
4286
4287
			$privacy_checks = explode( ',', $this->privacy_checks );
4288
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4289
			foreach ( $privacy_checks as $module_slug ) {
4290
				$module = Jetpack::get_module( $module_slug );
4291
				if ( ! $module ) {
4292
					continue;
4293
				}
4294
4295
				$module_slugs[] = $module_slug;
4296
				$module_names[] = "<strong>{$module['name']}</strong>";
4297
			}
4298
4299
			$module_slugs = join( ',', $module_slugs );
4300
?>
4301
<div id="message" class="jetpack-message jetpack-err">
4302
	<div class="squeezer">
4303
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4304
		<p><?php
4305
			echo wp_kses(
4306
				wptexturize(
4307
					wp_sprintf(
4308
						_nx(
4309
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4310
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4311
							count( $privacy_checks ),
4312
							'%l = list of Jetpack module/feature names',
4313
							'jetpack'
4314
						),
4315
						$module_names
4316
					)
4317
				),
4318
				array( 'strong' => true )
4319
			);
4320
4321
			echo "\n<br />\n";
4322
4323
			echo wp_kses(
4324
				sprintf(
4325
					_nx(
4326
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4327
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4328
						count( $privacy_checks ),
4329
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4330
						'jetpack'
4331
					),
4332
					wp_nonce_url(
4333
						Jetpack::admin_url(
4334
							array(
4335
								'page'   => 'jetpack',
4336
								'action' => 'deactivate',
4337
								'module' => urlencode( $module_slugs ),
4338
							)
4339
						),
4340
						"jetpack_deactivate-$module_slugs"
4341
					),
4342
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4343
				),
4344
				array( 'a' => array( 'href' => true, 'title' => true ) )
4345
			);
4346
		?></p>
4347
	</div>
4348
</div>
4349
<?php endif;
4350
	}
4351
4352
	/**
4353
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4354
	 */
4355
	function stat( $group, $detail ) {
4356
		if ( ! isset( $this->stats[ $group ] ) )
4357
			$this->stats[ $group ] = array();
4358
		$this->stats[ $group ][] = $detail;
4359
	}
4360
4361
	/**
4362
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4363
	 */
4364
	function do_stats( $method = '' ) {
4365
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4366
			foreach ( $this->stats as $group => $stats ) {
4367
				if ( is_array( $stats ) && count( $stats ) ) {
4368
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4369
					if ( 'server_side' === $method ) {
4370
						self::do_server_side_stat( $args );
4371
					} else {
4372
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4373
					}
4374
				}
4375
				unset( $this->stats[ $group ] );
4376
			}
4377
		}
4378
	}
4379
4380
	/**
4381
	 * Runs stats code for a one-off, server-side.
4382
	 *
4383
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4384
	 *
4385
	 * @return bool If it worked.
4386
	 */
4387
	static function do_server_side_stat( $args ) {
4388
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4389
		if ( is_wp_error( $response ) )
4390
			return false;
4391
4392
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4393
			return false;
4394
4395
		return true;
4396
	}
4397
4398
	/**
4399
	 * Builds the stats url.
4400
	 *
4401
	 * @param $args array|string The arguments to append to the URL.
4402
	 *
4403
	 * @return string The URL to be pinged.
4404
	 */
4405
	static function build_stats_url( $args ) {
4406
		$defaults = array(
4407
			'v'    => 'wpcom2',
4408
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4409
		);
4410
		$args     = wp_parse_args( $args, $defaults );
4411
		/**
4412
		 * Filter the URL used as the Stats tracking pixel.
4413
		 *
4414
		 * @since 2.3.2
4415
		 *
4416
		 * @param string $url Base URL used as the Stats tracking pixel.
4417
		 */
4418
		$base_url = apply_filters(
4419
			'jetpack_stats_base_url',
4420
			'https://pixel.wp.com/g.gif'
4421
		);
4422
		$url      = add_query_arg( $args, $base_url );
4423
		return $url;
4424
	}
4425
4426
	/**
4427
	 * Get the role of the current user.
4428
	 *
4429
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4430
	 *
4431
	 * @access public
4432
	 * @static
4433
	 *
4434
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4435
	 */
4436
	public static function translate_current_user_to_role() {
4437
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4438
4439
		$roles = new Roles();
4440
		return $roles->translate_current_user_to_role();
4441
	}
4442
4443
	/**
4444
	 * Get the role of a particular user.
4445
	 *
4446
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4447
	 *
4448
	 * @access public
4449
	 * @static
4450
	 *
4451
	 * @param \WP_User $user User object.
4452
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4453
	 */
4454
	public static function translate_user_to_role( $user ) {
4455
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4456
4457
		$roles = new Roles();
4458
		return $roles->translate_user_to_role( $user );
4459
	}
4460
4461
	/**
4462
	 * Get the minimum capability for a role.
4463
	 *
4464
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4465
	 *
4466
	 * @access public
4467
	 * @static
4468
	 *
4469
	 * @param string $role Role name.
4470
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4471
	 */
4472
	public static function translate_role_to_cap( $role ) {
4473
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4474
4475
		$roles = new Roles();
4476
		return $roles->translate_role_to_cap( $role );
4477
	}
4478
4479
	static function sign_role( $role, $user_id = null ) {
4480
		if ( empty( $user_id ) ) {
4481
			$user_id = (int) get_current_user_id();
4482
		}
4483
4484
		if ( ! $user_id  ) {
4485
			return false;
4486
		}
4487
4488
		$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...
4489
		if ( ! $token || is_wp_error( $token ) ) {
4490
			return false;
4491
		}
4492
4493
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4494
	}
4495
4496
4497
	/**
4498
	 * Builds a URL to the Jetpack connection auth page
4499
	 *
4500
	 * @since 3.9.5
4501
	 *
4502
	 * @param bool $raw If true, URL will not be escaped.
4503
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4504
	 *                              If string, will be a custom redirect.
4505
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4506
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4507
	 *
4508
	 * @return string Connect URL
4509
	 */
4510
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4511
		$site_id = Jetpack_Options::get_option( 'id' );
4512
		$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...
4513
4514
		if ( $register || ! $blog_token || ! $site_id ) {
4515
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4516
4517
			if ( ! empty( $redirect ) ) {
4518
				$url = add_query_arg(
4519
					'redirect',
4520
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4521
					$url
4522
				);
4523
			}
4524
4525
			if( is_network_admin() ) {
4526
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4527
			}
4528
		} else {
4529
4530
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4531
			// because otherwise this logic can get us in to a loop.
4532
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4533
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4534
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4535
4536
				$response = Client::wpcom_json_api_request_as_blog(
4537
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4538
					'1.1'
4539
				);
4540
4541
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4542
4543
					// Generating a register URL instead to refresh the existing token
4544
					return $this->build_connect_url( $raw, $redirect, $from, true );
4545
				}
4546
			}
4547
4548
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4549
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4550
			}
4551
4552
			$roles       = new Roles();
4553
			$role        = $roles->translate_current_user_to_role();
4554
			$signed_role = self::sign_role( $role );
4555
4556
			$user = wp_get_current_user();
4557
4558
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4559
			$redirect = $redirect
4560
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4561
				: $jetpack_admin_page;
4562
4563
			if( isset( $_REQUEST['is_multisite'] ) ) {
4564
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4565
			}
4566
4567
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4568
4569
			/**
4570
			 * Filter the type of authorization.
4571
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4572
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4573
			 *
4574
			 * @since 4.3.3
4575
			 *
4576
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4577
			 */
4578
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4579
4580
4581
			$tracks = new Tracking();
4582
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4583
4584
			$args = urlencode_deep(
4585
				array(
4586
					'response_type' => 'code',
4587
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4588
					'redirect_uri'  => add_query_arg(
4589
						array(
4590
							'action'   => 'authorize',
4591
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4592
							'redirect' => urlencode( $redirect ),
4593
						),
4594
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4595
					),
4596
					'state'         => $user->ID,
4597
					'scope'         => $signed_role,
4598
					'user_email'    => $user->user_email,
4599
					'user_login'    => $user->user_login,
4600
					'is_active'     => Jetpack::is_active(),
4601
					'jp_version'    => JETPACK__VERSION,
4602
					'auth_type'     => $auth_type,
4603
					'secret'        => $secrets['secret_1'],
4604
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4605
					'blogname'      => get_option( 'blogname' ),
4606
					'site_url'      => site_url(),
4607
					'home_url'      => home_url(),
4608
					'site_icon'     => get_site_icon_url(),
4609
					'site_lang'     => get_locale(),
4610
					'_ui'           => $tracks_identity['_ui'],
4611
					'_ut'           => $tracks_identity['_ut'],
4612
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4613
				)
4614
			);
4615
4616
			self::apply_activation_source_to_args( $args );
4617
4618
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4619
		}
4620
4621
		if ( $from ) {
4622
			$url = add_query_arg( 'from', $from, $url );
4623
		}
4624
4625
		// Ensure that class to get the affiliate code is loaded
4626
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4627
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4628
		}
4629
		// Get affiliate code and add it to the URL
4630
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4631
4632
		$calypso_env = $this->get_calypso_env();
4633
4634
		if ( ! empty( $calypso_env ) ) {
4635
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4636
		}
4637
4638
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4639
	}
4640
4641
	/**
4642
	 * Get our assumed site creation date.
4643
	 * Calculated based on the earlier date of either:
4644
	 * - Earliest admin user registration date.
4645
	 * - Earliest date of post of any post type.
4646
	 *
4647
	 * @since 7.2.0
4648
	 *
4649
	 * @return string Assumed site creation date and time.
4650
	 */
4651
	public static function get_assumed_site_creation_date() {
4652
		$earliest_registered_users = get_users( array(
4653
			'role'    => 'administrator',
4654
			'orderby' => 'user_registered',
4655
			'order'   => 'ASC',
4656
			'fields'  => array( 'user_registered' ),
4657
			'number'  => 1,
4658
		) );
4659
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4660
4661
		$earliest_posts = get_posts( array(
4662
			'posts_per_page' => 1,
4663
			'post_type'      => 'any',
4664
			'post_status'    => 'any',
4665
			'orderby'        => 'date',
4666
			'order'          => 'ASC',
4667
		) );
4668
4669
		// If there are no posts at all, we'll count only on user registration date.
4670
		if ( $earliest_posts ) {
4671
			$earliest_post_date = $earliest_posts[0]->post_date;
4672
		} else {
4673
			$earliest_post_date = PHP_INT_MAX;
4674
		}
4675
4676
		return min( $earliest_registration_date, $earliest_post_date );
4677
	}
4678
4679
	public static function apply_activation_source_to_args( &$args ) {
4680
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4681
4682
		if ( $activation_source_name ) {
4683
			$args['_as'] = urlencode( $activation_source_name );
4684
		}
4685
4686
		if ( $activation_source_keyword ) {
4687
			$args['_ak'] = urlencode( $activation_source_keyword );
4688
		}
4689
	}
4690
4691
	function build_reconnect_url( $raw = false ) {
4692
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4693
		return $raw ? $url : esc_url( $url );
4694
	}
4695
4696
	public static function admin_url( $args = null ) {
4697
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4698
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4699
		return $url;
4700
	}
4701
4702
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4703
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4704
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4705
	}
4706
4707
	function dismiss_jetpack_notice() {
4708
4709
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4710
			return;
4711
		}
4712
4713
		switch( $_GET['jetpack-notice'] ) {
4714
			case 'dismiss':
4715
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4716
4717
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4718
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4719
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4720
				}
4721
				break;
4722
			case 'jetpack-protect-multisite-opt-out':
4723
4724
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4725
					// Don't show the banner again
4726
4727
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4728
					// redirect back to the page that had the notice
4729
					if ( wp_get_referer() ) {
4730
						wp_safe_redirect( wp_get_referer() );
4731
					} else {
4732
						// Take me to Jetpack
4733
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4734
					}
4735
				}
4736
				break;
4737
		}
4738
	}
4739
4740
	public static function sort_modules( $a, $b ) {
4741
		if ( $a['sort'] == $b['sort'] )
4742
			return 0;
4743
4744
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4745
	}
4746
4747
	function ajax_recheck_ssl() {
4748
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4749
		$result = Jetpack::permit_ssl( true );
4750
		wp_send_json( array(
4751
			'enabled' => $result,
4752
			'message' => get_transient( 'jetpack_https_test_message' )
4753
		) );
4754
	}
4755
4756
/* Client API */
4757
4758
	/**
4759
	 * Returns the requested Jetpack API URL
4760
	 *
4761
	 * @return string
4762
	 */
4763
	public static function api_url( $relative_url ) {
4764
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4765
	}
4766
4767
	/**
4768
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4769
	 */
4770
	public static function fix_url_for_bad_hosts( $url ) {
4771
		if ( 0 !== strpos( $url, 'https://' ) ) {
4772
			return $url;
4773
		}
4774
4775
		switch ( JETPACK_CLIENT__HTTPS ) {
4776
			case 'ALWAYS' :
4777
				return $url;
4778
			case 'NEVER' :
4779
				return set_url_scheme( $url, 'http' );
4780
			// default : case 'AUTO' :
4781
		}
4782
4783
		// we now return the unmodified SSL URL by default, as a security precaution
4784
		return $url;
4785
	}
4786
4787
	/**
4788
	 * Create a random secret for validating onboarding payload
4789
	 *
4790
	 * @return string Secret token
4791
	 */
4792
	public static function create_onboarding_token() {
4793
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4794
			$token = wp_generate_password( 32, false );
4795
			Jetpack_Options::update_option( 'onboarding', $token );
4796
		}
4797
4798
		return $token;
4799
	}
4800
4801
	/**
4802
	 * Remove the onboarding token
4803
	 *
4804
	 * @return bool True on success, false on failure
4805
	 */
4806
	public static function invalidate_onboarding_token() {
4807
		return Jetpack_Options::delete_option( 'onboarding' );
4808
	}
4809
4810
	/**
4811
	 * Validate an onboarding token for a specific action
4812
	 *
4813
	 * @return boolean True if token/action pair is accepted, false if not
4814
	 */
4815
	public static function validate_onboarding_token_action( $token, $action ) {
4816
		// Compare tokens, bail if tokens do not match
4817
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4818
			return false;
4819
		}
4820
4821
		// List of valid actions we can take
4822
		$valid_actions = array(
4823
			'/jetpack/v4/settings',
4824
		);
4825
4826
		// Whitelist the action
4827
		if ( ! in_array( $action, $valid_actions ) ) {
4828
			return false;
4829
		}
4830
4831
		return true;
4832
	}
4833
4834
	/**
4835
	 * Checks to see if the URL is using SSL to connect with Jetpack
4836
	 *
4837
	 * @since 2.3.3
4838
	 * @return boolean
4839
	 */
4840
	public static function permit_ssl( $force_recheck = false ) {
4841
		// Do some fancy tests to see if ssl is being supported
4842
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4843
			$message = '';
4844
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4845
				$ssl = 0;
4846
			} else {
4847
				switch ( JETPACK_CLIENT__HTTPS ) {
4848
					case 'NEVER':
4849
						$ssl = 0;
4850
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4851
						break;
4852
					case 'ALWAYS':
4853
					case 'AUTO':
4854
					default:
4855
						$ssl = 1;
4856
						break;
4857
				}
4858
4859
				// If it's not 'NEVER', test to see
4860
				if ( $ssl ) {
4861
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4862
						$ssl = 0;
4863
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4864
					} else {
4865
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4866
						if ( is_wp_error( $response ) ) {
4867
							$ssl = 0;
4868
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4869
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4870
							$ssl = 0;
4871
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4872
						}
4873
					}
4874
				}
4875
			}
4876
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4877
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4878
		}
4879
4880
		return (bool) $ssl;
4881
	}
4882
4883
	/*
4884
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4885
	 */
4886
	public function alert_auto_ssl_fail() {
4887
		if ( ! current_user_can( 'manage_options' ) )
4888
			return;
4889
4890
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4891
		?>
4892
4893
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4894
			<div class="jp-banner__content">
4895
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4896
				<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>
4897
				<p>
4898
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4899
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4900
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4901
				</p>
4902
				<p>
4903
					<?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' ),
4904
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4905
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4906
				</p>
4907
			</div>
4908
		</div>
4909
		<style>
4910
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4911
		</style>
4912
		<script type="text/javascript">
4913
			jQuery( document ).ready( function( $ ) {
4914
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4915
					var $this = $( this );
4916
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4917
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4918
					e.preventDefault();
4919
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4920
					$.post( ajaxurl, data )
4921
					  .done( function( response ) {
4922
					  	if ( response.enabled ) {
4923
					  		$( '#jetpack-ssl-warning' ).hide();
4924
					  	} else {
4925
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4926
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4927
					  	}
4928
					  }.bind( $this ) );
4929
				} );
4930
			} );
4931
		</script>
4932
4933
		<?php
4934
	}
4935
4936
	/**
4937
	 * Returns the Jetpack XML-RPC API
4938
	 *
4939
	 * @return string
4940
	 */
4941
	public static function xmlrpc_api_url() {
4942
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4943
		return untrailingslashit( $base ) . '/xmlrpc.php';
4944
	}
4945
4946
	public static function connection() {
4947
		return self::init()->connection_manager;
4948
	}
4949
4950
	/**
4951
	 * Creates two secret tokens and the end of life timestamp for them.
4952
	 *
4953
	 * Note these tokens are unique per call, NOT static per site for connecting.
4954
	 *
4955
	 * @since 2.6
4956
	 * @return array
4957
	 */
4958
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4959
		if ( false === $user_id ) {
4960
			$user_id = get_current_user_id();
4961
		}
4962
4963
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4964
	}
4965
4966
	public static function get_secrets( $action, $user_id ) {
4967
		$secrets = self::connection()->get_secrets( $action, $user_id );
4968
4969
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4970
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

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

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

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

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

Loading history...
4975
		}
4976
4977
		return $secrets;
4978
	}
4979
4980
	/**
4981
	 * @deprecated 7.5 Use Connection_Manager instead.
4982
	 *
4983
	 * @param $action
4984
	 * @param $user_id
4985
	 */
4986
	public static function delete_secrets( $action, $user_id ) {
4987
		return self::connection()->delete_secrets( $action, $user_id );
4988
	}
4989
4990
	/**
4991
	 * Builds the timeout limit for queries talking with the wpcom servers.
4992
	 *
4993
	 * Based on local php max_execution_time in php.ini
4994
	 *
4995
	 * @since 2.6
4996
	 * @return int
4997
	 * @deprecated
4998
	 **/
4999
	public function get_remote_query_timeout_limit() {
5000
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5001
		return Jetpack::get_max_execution_time();
5002
	}
5003
5004
	/**
5005
	 * Builds the timeout limit for queries talking with the wpcom servers.
5006
	 *
5007
	 * Based on local php max_execution_time in php.ini
5008
	 *
5009
	 * @since 5.4
5010
	 * @return int
5011
	 **/
5012
	public static function get_max_execution_time() {
5013
		$timeout = (int) ini_get( 'max_execution_time' );
5014
5015
		// Ensure exec time set in php.ini
5016
		if ( ! $timeout ) {
5017
			$timeout = 30;
5018
		}
5019
		return $timeout;
5020
	}
5021
5022
	/**
5023
	 * Sets a minimum request timeout, and returns the current timeout
5024
	 *
5025
	 * @since 5.4
5026
	 **/
5027
	public static function set_min_time_limit( $min_timeout ) {
5028
		$timeout = self::get_max_execution_time();
5029
		if ( $timeout < $min_timeout ) {
5030
			$timeout = $min_timeout;
5031
			set_time_limit( $timeout );
5032
		}
5033
		return $timeout;
5034
	}
5035
5036
5037
	/**
5038
	 * Takes the response from the Jetpack register new site endpoint and
5039
	 * verifies it worked properly.
5040
	 *
5041
	 * @since 2.6
5042
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5043
	 **/
5044
	public function validate_remote_register_response( $response ) {
5045
	  if ( is_wp_error( $response ) ) {
5046
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'register_http_request_failed'.

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

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

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

Loading history...
5047
		}
5048
5049
		$code   = wp_remote_retrieve_response_code( $response );
5050
		$entity = wp_remote_retrieve_body( $response );
5051
		if ( $entity )
5052
			$registration_response = json_decode( $entity );
5053
		else
5054
			$registration_response = false;
5055
5056
		$code_type = intval( $code / 100 );
5057
		if ( 5 == $code_type ) {
5058
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_5??'.

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

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

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

Loading history...
5059
		} elseif ( 408 == $code ) {
5060
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_408'.

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

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

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

Loading history...
5061
		} elseif ( ! empty( $registration_response->error ) ) {
5062
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5063
				$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' );
5064
			} else {
5065
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5066
			}
5067
5068
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with (string) $registration_response->error.

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

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

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

Loading history...
5069
		} elseif ( 200 != $code ) {
5070
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_bad_response'.

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

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

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

Loading history...
5071
		}
5072
5073
		// Jetpack ID error block
5074
		if ( empty( $registration_response->jetpack_id ) ) {
5075
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

Loading history...
5076
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5077
			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 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

Loading history...
5078
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5079
			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 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

Loading history...
5080
		}
5081
5082
	    return $registration_response;
5083
	}
5084
	/**
5085
	 * @return bool|WP_Error
5086
	 */
5087
	public static function register() {
5088
		$tracking = new Tracking();
5089
		$tracking->record_user_event( 'jpc_register_begin' );
5090
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5091
		$secrets = Jetpack::generate_secrets( 'register' );
5092
5093 View Code Duplication
		if (
5094
			empty( $secrets['secret_1'] ) ||
5095
			empty( $secrets['secret_2'] ) ||
5096
			empty( $secrets['exp'] )
5097
		) {
5098
			return new Jetpack_Error( 'missing_secrets' );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_secrets'.

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

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

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

Loading history...
5099
		}
5100
5101
		// better to try (and fail) to set a higher timeout than this system
5102
		// supports than to have register fail for more users than it should
5103
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5104
5105
		$gmt_offset = get_option( 'gmt_offset' );
5106
		if ( ! $gmt_offset ) {
5107
			$gmt_offset = 0;
5108
		}
5109
5110
		$stats_options = get_option( 'stats_options' );
5111
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5112
5113
		$tracks = new Tracking();
5114
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5115
5116
		$args = array(
5117
			'method'  => 'POST',
5118
			'body'    => array(
5119
				'siteurl'         => site_url(),
5120
				'home'            => home_url(),
5121
				'gmt_offset'      => $gmt_offset,
5122
				'timezone_string' => (string) get_option( 'timezone_string' ),
5123
				'site_name'       => (string) get_option( 'blogname' ),
5124
				'secret_1'        => $secrets['secret_1'],
5125
				'secret_2'        => $secrets['secret_2'],
5126
				'site_lang'       => get_locale(),
5127
				'timeout'         => $timeout,
5128
				'stats_id'        => $stats_id,
5129
				'state'           => get_current_user_id(),
5130
				'_ui'             => $tracks_identity['_ui'],
5131
				'_ut'             => $tracks_identity['_ut'],
5132
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5133
				'jetpack_version' => JETPACK__VERSION,
5134
				'ABSPATH'         => defined( 'ABSPATH' ) ? ABSPATH : '',
5135
			),
5136
			'headers' => array(
5137
				'Accept' => 'application/json',
5138
			),
5139
			'timeout' => $timeout,
5140
		);
5141
5142
		self::apply_activation_source_to_args( $args['body'] );
5143
5144
		$response = Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5145
5146
		// Make sure the response is valid and does not contain any Jetpack errors
5147
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5148
		if ( is_wp_error( $registration_details ) ) {
5149
			return $registration_details;
5150
		} elseif ( ! $registration_details ) {
5151
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_error'.

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

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

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

Loading history...
5152
		}
5153
5154 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5155
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_secret'.

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

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

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

Loading history...
5156
		}
5157
5158
		if ( isset( $registration_details->jetpack_public ) ) {
5159
			$jetpack_public = (int) $registration_details->jetpack_public;
5160
		} else {
5161
			$jetpack_public = false;
5162
		}
5163
5164
		Jetpack_Options::update_options(
5165
			array(
5166
				'id'         => (int)    $registration_details->jetpack_id,
5167
				'blog_token' => (string) $registration_details->jetpack_secret,
5168
				'public'     => $jetpack_public,
5169
			)
5170
		);
5171
5172
		/**
5173
		 * Fires when a site is registered on WordPress.com.
5174
		 *
5175
		 * @since 3.7.0
5176
		 *
5177
		 * @param int $json->jetpack_id Jetpack Blog ID.
5178
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5179
		 * @param int|bool $jetpack_public Is the site public.
5180
		 */
5181
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5182
5183
		$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...
5184
5185
		return true;
5186
	}
5187
5188
	/**
5189
	 * If the db version is showing something other that what we've got now, bump it to current.
5190
	 *
5191
	 * @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...
5192
	 */
5193
	public static function maybe_set_version_option() {
5194
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5195
		if ( JETPACK__VERSION != $version ) {
5196
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5197
5198
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5199
				/** This action is documented in class.jetpack.php */
5200
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5201
			}
5202
5203
			return true;
5204
		}
5205
		return false;
5206
	}
5207
5208
/* Client Server API */
5209
5210
	/**
5211
	 * Loads the Jetpack XML-RPC client
5212
	 */
5213
	public static function load_xml_rpc_client() {
5214
		require_once ABSPATH . WPINC . '/class-IXR.php';
5215
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5216
	}
5217
5218
	/**
5219
	 * Resets the saved authentication state in between testing requests.
5220
	 */
5221
	public function reset_saved_auth_state() {
5222
		$this->xmlrpc_verification = null;
5223
		$this->rest_authentication_status = null;
5224
	}
5225
5226
	/**
5227
	 * Verifies the signature of the current request.
5228
	 *
5229
	 * @return false|array
5230
	 */
5231
	function verify_xml_rpc_signature() {
5232
		if ( is_null( $this->xmlrpc_verification ) ) {
5233
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
5234
5235
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
5236
				/**
5237
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
5238
				 *
5239
				 * Error codes:
5240
				 * - malformed_token
5241
				 * - malformed_user_id
5242
				 * - unknown_token
5243
				 * - could_not_sign
5244
				 * - invalid_nonce
5245
				 * - signature_mismatch
5246
				 *
5247
				 * @since 7.5.0
5248
				 *
5249
				 * @param WP_Error $signature_verification_error The verification error
5250
				 */
5251
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
5252
			}
5253
		}
5254
5255
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
5256
	}
5257
5258
	/**
5259
	 * Verifies the signature of the current request.
5260
	 *
5261
	 * This function has side effects and should not be used. Instead,
5262
	 * use the memoized version `->verify_xml_rpc_signature()`.
5263
	 *
5264
	 * @internal
5265
	 */
5266
	private function internal_verify_xml_rpc_signature() {
5267
		// It's not for us
5268
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5269
			return false;
5270
		}
5271
5272
		$signature_details = array(
5273
			'token'     => isset( $_GET['token'] )     ? wp_unslash( $_GET['token'] )     : '',
5274
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
5275
			'nonce'     => isset( $_GET['nonce'] )     ? wp_unslash( $_GET['nonce'] )     : '',
5276
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
5277
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
5278
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
5279
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
5280
		);
5281
5282
		@list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_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...
5283
		if (
5284
			empty( $token_key )
5285
		||
5286
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5287
		) {
5288
			return new WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_token'.

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

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

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

Loading history...
5289
		}
5290
5291
		if ( '0' === $user_id ) {
5292
			$token_type = 'blog';
5293
			$user_id = 0;
5294
		} else {
5295
			$token_type = 'user';
5296
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5297
				return new WP_Error( 'malformed_user_id', 'Malformed user_id in request', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_user_id'.

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

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

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

Loading history...
5298
			}
5299
			$user_id = (int) $user_id;
5300
5301
			$user = new WP_User( $user_id );
5302
			if ( ! $user || ! $user->exists() ) {
5303
				return new WP_Error( 'unknown_user', sprintf( 'User %d does not exist', $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_user'.

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

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

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

Loading history...
5304
			}
5305
		}
5306
5307
		$token = Jetpack_Data::get_access_token( $user_id, $token_key, false );
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...
5308
		if ( is_wp_error( $token ) ) {
5309
			$token->add_data( compact( 'signature_details' ) );
5310
			return $token;
5311
		} elseif ( ! $token ) {
5312
			return new WP_Error( 'unknown_token', sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
5313
		}
5314
5315
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5316
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5317
			$post_data   = $_POST;
5318
			$file_hashes = array();
5319
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5320
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5321
					continue;
5322
				}
5323
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5324
				$file_hashes[$post_data_key] = $post_data_value;
5325
			}
5326
5327
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5328
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5329
				$post_data[$post_data_key] = $post_data_value;
5330
			}
5331
5332
			ksort( $post_data );
5333
5334
			$body = http_build_query( stripslashes_deep( $post_data ) );
5335
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5336
			$body = file_get_contents( 'php://input' );
5337
		} else {
5338
			$body = null;
5339
		}
5340
5341
		$signature = $jetpack_signature->sign_current_request(
5342
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5343
		);
5344
5345
		$signature_details['url'] = $jetpack_signature->current_request_url;
5346
5347
		if ( ! $signature ) {
5348
			return new WP_Error( 'could_not_sign', 'Unknown signature error', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'could_not_sign'.

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

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

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

Loading history...
5349
		} else if ( is_wp_error( $signature ) ) {
5350
			return $signature;
5351
		}
5352
5353
		$timestamp = (int) $_GET['timestamp'];
5354
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5355
5356
		// Use up the nonce regardless of whether the signature matches.
5357
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5358
			return new WP_Error( 'invalid_nonce', 'Could not add nonce', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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

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

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

Loading history...
5359
		}
5360
5361
		// Be careful about what you do with this debugging data.
5362
		// If a malicious requester has access to the expected signature,
5363
		// bad things might be possible.
5364
		$signature_details['expected'] = $signature;
5365
5366
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5367
			return new WP_Error( 'signature_mismatch', 'Signature mismatch', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'signature_mismatch'.

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

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

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

Loading history...
5368
		}
5369
5370
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5371
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5372
			if ( ! empty( $_GET['onboarding'] ) ) {
5373
				$jpo = $_GET;
5374
			} else {
5375
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5376
			}
5377
5378
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5379
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5380
5381
			if (
5382
				isset( $jpo_user ) && isset( $jpo_token ) &&
5383
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5384
				isset( $_GET['rest_route'] ) &&
5385
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5386
			) {
5387
				$jpUser = get_user_by( 'email', $jpo_user );
5388
				if ( is_a( $jpUser, 'WP_User' ) ) {
5389
					wp_set_current_user( $jpUser->ID );
5390
					$user_can = is_multisite()
5391
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5392
						: current_user_can( 'manage_options' );
5393
					if ( $user_can ) {
5394
						$token_type = 'user';
5395
						$token->external_user_id = $jpUser->ID;
5396
					}
5397
				}
5398
			}
5399
		}
5400
5401
		return array(
5402
			'type'      => $token_type,
5403
			'token_key' => $token_key,
5404
			'user_id'   => $token->external_user_id,
5405
		);
5406
	}
5407
5408
	/**
5409
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5410
	 */
5411
	function authenticate_jetpack( $user, $username, $password ) {
5412
		if ( is_a( $user, 'WP_User' ) ) {
5413
			return $user;
5414
		}
5415
5416
		$token_details = $this->verify_xml_rpc_signature();
5417
5418
		if ( ! $token_details ) {
5419
			return $user;
5420
		}
5421
5422
		if ( 'user' !== $token_details['type'] ) {
5423
			return $user;
5424
		}
5425
5426
		if ( ! $token_details['user_id'] ) {
5427
			return $user;
5428
		}
5429
5430
		nocache_headers();
5431
5432
		return new WP_User( $token_details['user_id'] );
5433
	}
5434
5435
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5436
	// Uses the existing XMLRPC request signing implementation.
5437
	function wp_rest_authenticate( $user ) {
5438
		if ( ! empty( $user ) ) {
5439
			// Another authentication method is in effect.
5440
			return $user;
5441
		}
5442
5443
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5444
			// Nothing to do for this authentication method.
5445
			return null;
5446
		}
5447
5448
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5449
			// Nothing to do for this authentication method.
5450
			return null;
5451
		}
5452
5453
		// Ensure that we always have the request body available.  At this
5454
		// point, the WP REST API code to determine the request body has not
5455
		// run yet.  That code may try to read from 'php://input' later, but
5456
		// this can only be done once per request in PHP versions prior to 5.6.
5457
		// So we will go ahead and perform this read now if needed, and save
5458
		// the request body where both the Jetpack signature verification code
5459
		// and the WP REST API code can see it.
5460
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5461
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5462
		}
5463
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5464
5465
		// Only support specific request parameters that have been tested and
5466
		// are known to work with signature verification.  A different method
5467
		// can be passed to the WP REST API via the '?_method=' parameter if
5468
		// needed.
5469
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5470
			$this->rest_authentication_status = new WP_Error(
5471
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5472
				__( 'This request method is not supported.', 'jetpack' ),
5473
				array( 'status' => 400 )
5474
			);
5475
			return null;
5476
		}
5477
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5478
			$this->rest_authentication_status = new WP_Error(
5479
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5480
				__( 'This request method does not support body parameters.', 'jetpack' ),
5481
				array( 'status' => 400 )
5482
			);
5483
			return null;
5484
		}
5485
5486
		$verified = $this->verify_xml_rpc_signature();
5487
5488
		if (
5489
			$verified &&
5490
			isset( $verified['type'] ) &&
5491
			'user' === $verified['type'] &&
5492
			! empty( $verified['user_id'] )
5493
		) {
5494
			// Authentication successful.
5495
			$this->rest_authentication_status = true;
5496
			return $verified['user_id'];
5497
		}
5498
5499
		// Something else went wrong.  Probably a signature error.
5500
		$this->rest_authentication_status = new WP_Error(
5501
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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

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

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

Loading history...
5502
			__( 'The request is not signed correctly.', 'jetpack' ),
5503
			array( 'status' => 400 )
5504
		);
5505
		return null;
5506
	}
5507
5508
	/**
5509
	 * Report authentication status to the WP REST API.
5510
	 *
5511
	 * @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...
5512
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5513
	 */
5514
	public function wp_rest_authentication_errors( $value ) {
5515
		if ( $value !== null ) {
5516
			return $value;
5517
		}
5518
		return $this->rest_authentication_status;
5519
	}
5520
5521
	function add_nonce( $timestamp, $nonce ) {
5522
		global $wpdb;
5523
		static $nonces_used_this_request = array();
5524
5525
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5526
			return $nonces_used_this_request["$timestamp:$nonce"];
5527
		}
5528
5529
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5530
		$timestamp = (int) $timestamp;
5531
		$nonce     = esc_sql( $nonce );
5532
5533
		// Raw query so we can avoid races: add_option will also update
5534
		$show_errors = $wpdb->show_errors( false );
5535
5536
		$old_nonce = $wpdb->get_row(
5537
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5538
		);
5539
5540
		if ( is_null( $old_nonce ) ) {
5541
			$return = $wpdb->query(
5542
				$wpdb->prepare(
5543
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5544
					"jetpack_nonce_{$timestamp}_{$nonce}",
5545
					time(),
5546
					'no'
5547
				)
5548
			);
5549
		} else {
5550
			$return = false;
5551
		}
5552
5553
		$wpdb->show_errors( $show_errors );
5554
5555
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5556
5557
		return $return;
5558
	}
5559
5560
	/**
5561
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5562
	 * Capture it here so we can verify the signature later.
5563
	 */
5564
	function xmlrpc_methods( $methods ) {
5565
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5566
		return $methods;
5567
	}
5568
5569
	function public_xmlrpc_methods( $methods ) {
5570
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5571
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5572
		}
5573
		return $methods;
5574
	}
5575
5576
	function jetpack_getOptions( $args ) {
5577
		global $wp_xmlrpc_server;
5578
5579
		$wp_xmlrpc_server->escape( $args );
5580
5581
		$username	= $args[1];
5582
		$password	= $args[2];
5583
5584
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5585
			return $wp_xmlrpc_server->error;
5586
		}
5587
5588
		$options = array();
5589
		$user_data = $this->get_connected_user_data();
5590
		if ( is_array( $user_data ) ) {
5591
			$options['jetpack_user_id'] = array(
5592
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5593
				'readonly'      => true,
5594
				'value'         => $user_data['ID'],
5595
			);
5596
			$options['jetpack_user_login'] = array(
5597
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5598
				'readonly'      => true,
5599
				'value'         => $user_data['login'],
5600
			);
5601
			$options['jetpack_user_email'] = array(
5602
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5603
				'readonly'      => true,
5604
				'value'         => $user_data['email'],
5605
			);
5606
			$options['jetpack_user_site_count'] = array(
5607
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5608
				'readonly'      => true,
5609
				'value'         => $user_data['site_count'],
5610
			);
5611
		}
5612
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5613
		$args = stripslashes_deep( $args );
5614
		return $wp_xmlrpc_server->wp_getOptions( $args );
5615
	}
5616
5617
	function xmlrpc_options( $options ) {
5618
		$jetpack_client_id = false;
5619
		if ( self::is_active() ) {
5620
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5621
		}
5622
		$options['jetpack_version'] = array(
5623
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5624
				'readonly'      => true,
5625
				'value'         => JETPACK__VERSION,
5626
		);
5627
5628
		$options['jetpack_client_id'] = array(
5629
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5630
				'readonly'      => true,
5631
				'value'         => $jetpack_client_id,
5632
		);
5633
		return $options;
5634
	}
5635
5636
	public static function clean_nonces( $all = false ) {
5637
		global $wpdb;
5638
5639
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5640
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5641
5642
		if ( true !== $all ) {
5643
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5644
			$sql_args[] = time() - 3600;
5645
		}
5646
5647
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5648
5649
		$sql = $wpdb->prepare( $sql, $sql_args );
5650
5651
		for ( $i = 0; $i < 1000; $i++ ) {
5652
			if ( ! $wpdb->query( $sql ) ) {
5653
				break;
5654
			}
5655
		}
5656
	}
5657
5658
	/**
5659
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5660
	 * SET: state( $key, $value );
5661
	 * GET: $value = state( $key );
5662
	 *
5663
	 * @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...
5664
	 * @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...
5665
	 * @param bool $restate private
5666
	 */
5667
	public static function state( $key = null, $value = null, $restate = false ) {
5668
		static $state = array();
5669
		static $path, $domain;
5670
		if ( ! isset( $path ) ) {
5671
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5672
			$admin_url = Jetpack::admin_url();
5673
			$bits      = wp_parse_url( $admin_url );
5674
5675
			if ( is_array( $bits ) ) {
5676
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5677
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5678
			} else {
5679
				$path = $domain = null;
5680
			}
5681
		}
5682
5683
		// Extract state from cookies and delete cookies
5684
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5685
			$yum = $_COOKIE[ 'jetpackState' ];
5686
			unset( $_COOKIE[ 'jetpackState' ] );
5687
			foreach ( $yum as $k => $v ) {
5688
				if ( strlen( $v ) )
5689
					$state[ $k ] = $v;
5690
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5691
			}
5692
		}
5693
5694
		if ( $restate ) {
5695
			foreach ( $state as $k => $v ) {
5696
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5697
			}
5698
			return;
5699
		}
5700
5701
		// Get a state variable
5702
		if ( isset( $key ) && ! isset( $value ) ) {
5703
			if ( array_key_exists( $key, $state ) )
5704
				return $state[ $key ];
5705
			return null;
5706
		}
5707
5708
		// Set a state variable
5709
		if ( isset ( $key ) && isset( $value ) ) {
5710
			if( is_array( $value ) && isset( $value[0] ) ) {
5711
				$value = $value[0];
5712
			}
5713
			$state[ $key ] = $value;
5714
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5715
		}
5716
	}
5717
5718
	public static function restate() {
5719
		Jetpack::state( null, null, true );
5720
	}
5721
5722
	public static function check_privacy( $file ) {
5723
		static $is_site_publicly_accessible = null;
5724
5725
		if ( is_null( $is_site_publicly_accessible ) ) {
5726
			$is_site_publicly_accessible = false;
5727
5728
			Jetpack::load_xml_rpc_client();
5729
			$rpc = new Jetpack_IXR_Client();
5730
5731
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5732
			if ( $success ) {
5733
				$response = $rpc->getResponse();
5734
				if ( $response ) {
5735
					$is_site_publicly_accessible = true;
5736
				}
5737
			}
5738
5739
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5740
		}
5741
5742
		if ( $is_site_publicly_accessible ) {
5743
			return;
5744
		}
5745
5746
		$module_slug = self::get_module_slug( $file );
5747
5748
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5749
		if ( ! $privacy_checks ) {
5750
			$privacy_checks = $module_slug;
5751
		} else {
5752
			$privacy_checks .= ",$module_slug";
5753
		}
5754
5755
		Jetpack::state( 'privacy_checks', $privacy_checks );
5756
	}
5757
5758
	/**
5759
	 * Helper method for multicall XMLRPC.
5760
	 */
5761
	public static function xmlrpc_async_call() {
5762
		global $blog_id;
5763
		static $clients = array();
5764
5765
		$client_blog_id = is_multisite() ? $blog_id : 0;
5766
5767
		if ( ! isset( $clients[$client_blog_id] ) ) {
5768
			Jetpack::load_xml_rpc_client();
5769
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5770
			if ( function_exists( 'ignore_user_abort' ) ) {
5771
				ignore_user_abort( true );
5772
			}
5773
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5774
		}
5775
5776
		$args = func_get_args();
5777
5778
		if ( ! empty( $args[0] ) ) {
5779
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5780
		} elseif ( is_multisite() ) {
5781
			foreach ( $clients as $client_blog_id => $client ) {
5782
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5783
					continue;
5784
				}
5785
5786
				$switch_success = switch_to_blog( $client_blog_id, true );
5787
				if ( ! $switch_success ) {
5788
					continue;
5789
				}
5790
5791
				flush();
5792
				$client->query();
5793
5794
				restore_current_blog();
5795
			}
5796
		} else {
5797
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5798
				flush();
5799
				$clients[0]->query();
5800
			}
5801
		}
5802
	}
5803
5804
	public static function staticize_subdomain( $url ) {
5805
5806
		// Extract hostname from URL
5807
		$host = parse_url( $url, PHP_URL_HOST );
5808
5809
		// Explode hostname on '.'
5810
		$exploded_host = explode( '.', $host );
5811
5812
		// Retrieve the name and TLD
5813
		if ( count( $exploded_host ) > 1 ) {
5814
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5815
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5816
			// Rebuild domain excluding subdomains
5817
			$domain = $name . '.' . $tld;
5818
		} else {
5819
			$domain = $host;
5820
		}
5821
		// Array of Automattic domains
5822
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5823
5824
		// Return $url if not an Automattic domain
5825
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5826
			return $url;
5827
		}
5828
5829
		if ( is_ssl() ) {
5830
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5831
		}
5832
5833
		srand( crc32( basename( $url ) ) );
5834
		$static_counter = rand( 0, 2 );
5835
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5836
5837
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5838
	}
5839
5840
/* JSON API Authorization */
5841
5842
	/**
5843
	 * Handles the login action for Authorizing the JSON API
5844
	 */
5845
	function login_form_json_api_authorization() {
5846
		$this->verify_json_api_authorization_request();
5847
5848
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5849
5850
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5851
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5852
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5853
	}
5854
5855
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5856
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5857
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5858
			return $url;
5859
		}
5860
5861
		$parsed_url = parse_url( $url );
5862
		$url = strtok( $url, '?' );
5863
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5864
		if ( ! empty( $parsed_url['query'] ) )
5865
			$url .= "&{$parsed_url['query']}";
5866
5867
		return $url;
5868
	}
5869
5870
	// Make sure the POSTed request is handled by the same action
5871
	function preserve_action_in_login_form_for_json_api_authorization() {
5872
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5873
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5874
	}
5875
5876
	// If someone logs in to approve API access, store the Access Code in usermeta
5877
	function store_json_api_authorization_token( $user_login, $user ) {
5878
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5879
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5880
		$token = wp_generate_password( 32, false );
5881
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5882
	}
5883
5884
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5885
	function allow_wpcom_public_api_domain( $domains ) {
5886
		$domains[] = 'public-api.wordpress.com';
5887
		return $domains;
5888
	}
5889
5890
	static function is_redirect_encoded( $redirect_url ) {
5891
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5892
	}
5893
5894
	// Add all wordpress.com environments to the safe redirect whitelist
5895
	function allow_wpcom_environments( $domains ) {
5896
		$domains[] = 'wordpress.com';
5897
		$domains[] = 'wpcalypso.wordpress.com';
5898
		$domains[] = 'horizon.wordpress.com';
5899
		$domains[] = 'calypso.localhost';
5900
		return $domains;
5901
	}
5902
5903
	// Add the Access Code details to the public-api.wordpress.com redirect
5904
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5905
		return add_query_arg(
5906
			urlencode_deep(
5907
				array(
5908
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5909
					'jetpack-user-id' => (int) $user->ID,
5910
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5911
				)
5912
			),
5913
			$redirect_to
5914
		);
5915
	}
5916
5917
5918
	/**
5919
	 * Verifies the request by checking the signature
5920
	 *
5921
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5922
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5923
	 *
5924
	 * @param null|array $environment
5925
	 */
5926
	function verify_json_api_authorization_request( $environment = null ) {
5927
		$environment = is_null( $environment )
5928
			? $_REQUEST
5929
			: $environment;
5930
5931
		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...
5932
		$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...
5933
		if ( ! $token || empty( $token->secret ) ) {
5934
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5935
		}
5936
5937
		$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' );
5938
5939
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5940
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5941
			/**
5942
			 * Jetpack authorisation request Error.
5943
			 *
5944
			 * @since 7.5.0
5945
			 *
5946
			 */
5947
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5948
			$die_error = sprintf(
5949
				/* translators: %s is a URL */
5950
				__( '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' ),
5951
				'https://jetpack.com/support/double-encoding/'
5952
			);
5953
		}
5954
5955
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5956
5957
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5958
			$signature = $jetpack_signature->sign_request(
5959
				$environment['token'],
5960
				$environment['timestamp'],
5961
				$environment['nonce'],
5962
				'',
5963
				'GET',
5964
				$environment['jetpack_json_api_original_query'],
5965
				null,
5966
				true
5967
			);
5968
		} else {
5969
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5970
		}
5971
5972
		if ( ! $signature ) {
5973
			wp_die( $die_error );
5974
		} else if ( is_wp_error( $signature ) ) {
5975
			wp_die( $die_error );
5976
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5977
			if ( is_ssl() ) {
5978
				// 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
5979
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5980
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5981
					wp_die( $die_error );
5982
				}
5983
			} else {
5984
				wp_die( $die_error );
5985
			}
5986
		}
5987
5988
		$timestamp = (int) $environment['timestamp'];
5989
		$nonce     = stripslashes( (string) $environment['nonce'] );
5990
5991
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5992
			// De-nonce the nonce, at least for 5 minutes.
5993
			// 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)
5994
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5995
			if ( $old_nonce_time < time() - 300 ) {
5996
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5997
			}
5998
		}
5999
6000
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6001
		$data_filters = array(
6002
			'state'        => 'opaque',
6003
			'client_id'    => 'int',
6004
			'client_title' => 'string',
6005
			'client_image' => 'url',
6006
		);
6007
6008
		foreach ( $data_filters as $key => $sanitation ) {
6009
			if ( ! isset( $data->$key ) ) {
6010
				wp_die( $die_error );
6011
			}
6012
6013
			switch ( $sanitation ) {
6014
			case 'int' :
6015
				$this->json_api_authorization_request[$key] = (int) $data->$key;
6016
				break;
6017
			case 'opaque' :
6018
				$this->json_api_authorization_request[$key] = (string) $data->$key;
6019
				break;
6020
			case 'string' :
6021
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
6022
				break;
6023
			case 'url' :
6024
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
6025
				break;
6026
			}
6027
		}
6028
6029
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6030
			wp_die( $die_error );
6031
		}
6032
	}
6033
6034
	function login_message_json_api_authorization( $message ) {
6035
		return '<p class="message">' . sprintf(
6036
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
6037
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6038
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6039
	}
6040
6041
	/**
6042
	 * Get $content_width, but with a <s>twist</s> filter.
6043
	 */
6044
	public static function get_content_width() {
6045
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6046
			? $GLOBALS['content_width']
6047
			: false;
6048
		/**
6049
		 * Filter the Content Width value.
6050
		 *
6051
		 * @since 2.2.3
6052
		 *
6053
		 * @param string $content_width Content Width value.
6054
		 */
6055
		return apply_filters( 'jetpack_content_width', $content_width );
6056
	}
6057
6058
	/**
6059
	 * Pings the WordPress.com Mirror Site for the specified options.
6060
	 *
6061
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6062
	 *
6063
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6064
	 */
6065
	public function get_cloud_site_options( $option_names ) {
6066
		$option_names = array_filter( (array) $option_names, 'is_string' );
6067
6068
		Jetpack::load_xml_rpc_client();
6069
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6070
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6071
		if ( $xml->isError() ) {
6072
			return array(
6073
				'error_code' => $xml->getErrorCode(),
6074
				'error_msg'  => $xml->getErrorMessage(),
6075
			);
6076
		}
6077
		$cloud_site_options = $xml->getResponse();
6078
6079
		return $cloud_site_options;
6080
	}
6081
6082
	/**
6083
	 * Checks if the site is currently in an identity crisis.
6084
	 *
6085
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6086
	 */
6087
	public static function check_identity_crisis() {
6088
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6089
			return false;
6090
		}
6091
6092
		return Jetpack_Options::get_option( 'sync_error_idc' );
6093
	}
6094
6095
	/**
6096
	 * Checks whether the home and siteurl specifically are whitelisted
6097
	 * Written so that we don't have re-check $key and $value params every time
6098
	 * we want to check if this site is whitelisted, for example in footer.php
6099
	 *
6100
	 * @since  3.8.0
6101
	 * @return bool True = already whitelisted False = not whitelisted
6102
	 */
6103
	public static function is_staging_site() {
6104
		$is_staging = false;
6105
6106
		$known_staging = array(
6107
			'urls' => array(
6108
				'#\.staging\.wpengine\.com$#i', // WP Engine
6109
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6110
				'#\.stage\.site$#i'             // DreamPress
6111
			),
6112
			'constants' => array(
6113
				'IS_WPE_SNAPSHOT',      // WP Engine
6114
				'KINSTA_DEV_ENV',       // Kinsta.com
6115
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6116
				'JETPACK_STAGING_MODE', // Generic
6117
			)
6118
		);
6119
		/**
6120
		 * Filters the flags of known staging sites.
6121
		 *
6122
		 * @since 3.9.0
6123
		 *
6124
		 * @param array $known_staging {
6125
		 *     An array of arrays that each are used to check if the current site is staging.
6126
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6127
		 *     @type array $constants PHP constants of known staging/developement environments.
6128
		 *  }
6129
		 */
6130
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6131
6132
		if ( isset( $known_staging['urls'] ) ) {
6133
			foreach ( $known_staging['urls'] as $url ){
6134
				if ( preg_match( $url, site_url() ) ) {
6135
					$is_staging = true;
6136
					break;
6137
				}
6138
			}
6139
		}
6140
6141
		if ( isset( $known_staging['constants'] ) ) {
6142
			foreach ( $known_staging['constants'] as $constant ) {
6143
				if ( defined( $constant ) && constant( $constant ) ) {
6144
					$is_staging = true;
6145
				}
6146
			}
6147
		}
6148
6149
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6150
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6151
			$is_staging = true;
6152
		}
6153
6154
		/**
6155
		 * Filters is_staging_site check.
6156
		 *
6157
		 * @since 3.9.0
6158
		 *
6159
		 * @param bool $is_staging If the current site is a staging site.
6160
		 */
6161
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6162
	}
6163
6164
	/**
6165
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6166
	 *
6167
	 * @since 4.4.0
6168
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6169
	 *
6170
	 * @return bool
6171
	 */
6172
	public static function validate_sync_error_idc_option() {
6173
		$is_valid = false;
6174
6175
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6176
		if ( false === $idc_allowed ) {
6177
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6178
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6179
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6180
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6181
				$transient_duration = HOUR_IN_SECONDS;
6182
			} else {
6183
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6184
				$idc_allowed = '1';
6185
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6186
			}
6187
6188
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6189
		}
6190
6191
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6192
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6193
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6194
			$local_options = self::get_sync_error_idc_option();
6195
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6196
				$is_valid = true;
6197
			}
6198
		}
6199
6200
		/**
6201
		 * Filters whether the sync_error_idc option is valid.
6202
		 *
6203
		 * @since 4.4.0
6204
		 *
6205
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6206
		 */
6207
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6208
6209
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6210
			// Since the option exists, and did not validate, delete it
6211
			Jetpack_Options::delete_option( 'sync_error_idc' );
6212
		}
6213
6214
		return $is_valid;
6215
	}
6216
6217
	/**
6218
	 * Normalizes a url by doing three things:
6219
	 *  - Strips protocol
6220
	 *  - Strips www
6221
	 *  - Adds a trailing slash
6222
	 *
6223
	 * @since 4.4.0
6224
	 * @param string $url
6225
	 * @return WP_Error|string
6226
	 */
6227
	public static function normalize_url_protocol_agnostic( $url ) {
6228
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6229
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6230
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

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

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

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

Loading history...
6231
		}
6232
6233
		// Strip www and protocols
6234
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6235
		return $url;
6236
	}
6237
6238
	/**
6239
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6240
	 *
6241
	 * @since 4.4.0
6242
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6243
	 *
6244
	 * @param array $response
6245
	 * @return array Array of the local urls, wpcom urls, and error code
6246
	 */
6247
	public static function get_sync_error_idc_option( $response = array() ) {
6248
		// Since the local options will hit the database directly, store the values
6249
		// in a transient to allow for autoloading and caching on subsequent views.
6250
		$local_options = get_transient( 'jetpack_idc_local' );
6251
		if ( false === $local_options ) {
6252
			$local_options = array(
6253
				'home'    => Functions::home_url(),
6254
				'siteurl' => Functions::site_url(),
6255
			);
6256
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6257
		}
6258
6259
		$options = array_merge( $local_options, $response );
6260
6261
		$returned_values = array();
6262
		foreach( $options as $key => $option ) {
6263
			if ( 'error_code' === $key ) {
6264
				$returned_values[ $key ] = $option;
6265
				continue;
6266
			}
6267
6268
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6269
				continue;
6270
			}
6271
6272
			$returned_values[ $key ] = $normalized_url;
6273
		}
6274
6275
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6276
6277
		return $returned_values;
6278
	}
6279
6280
	/**
6281
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6282
	 * If set to true, the site will be put into staging mode.
6283
	 *
6284
	 * @since 4.3.2
6285
	 * @return bool
6286
	 */
6287
	public static function sync_idc_optin() {
6288
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6289
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6290
		} else {
6291
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6292
		}
6293
6294
		/**
6295
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6296
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6297
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6298
		 *
6299
		 * @since 4.3.2
6300
		 *
6301
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6302
		 */
6303
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6304
	}
6305
6306
	/**
6307
	 * Maybe Use a .min.css stylesheet, maybe not.
6308
	 *
6309
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6310
	 */
6311
	public static function maybe_min_asset( $url, $path, $plugin ) {
6312
		// Short out on things trying to find actual paths.
6313
		if ( ! $path || empty( $plugin ) ) {
6314
			return $url;
6315
		}
6316
6317
		$path = ltrim( $path, '/' );
6318
6319
		// Strip out the abspath.
6320
		$base = dirname( plugin_basename( $plugin ) );
6321
6322
		// Short out on non-Jetpack assets.
6323
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6324
			return $url;
6325
		}
6326
6327
		// File name parsing.
6328
		$file              = "{$base}/{$path}";
6329
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6330
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6331
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6332
		$extension         = array_shift( $file_name_parts_r );
6333
6334
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6335
			// Already pointing at the minified version.
6336
			if ( 'min' === $file_name_parts_r[0] ) {
6337
				return $url;
6338
			}
6339
6340
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6341
			if ( file_exists( $min_full_path ) ) {
6342
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6343
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6344
				if ( 'css' === $extension ) {
6345
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6346
					self::$min_assets[ $key ] = $path;
6347
				}
6348
			}
6349
		}
6350
6351
		return $url;
6352
	}
6353
6354
	/**
6355
	 * If the asset is minified, let's flag .min as the suffix.
6356
	 *
6357
	 * Attached to `style_loader_src` filter.
6358
	 *
6359
	 * @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...
6360
	 * @param string $handle The registered handle of the script in question.
6361
	 * @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...
6362
	 */
6363
	public static function set_suffix_on_min( $src, $handle ) {
6364
		if ( false === strpos( $src, '.min.css' ) ) {
6365
			return $src;
6366
		}
6367
6368
		if ( ! empty( self::$min_assets ) ) {
6369
			foreach ( self::$min_assets as $file => $path ) {
6370
				if ( false !== strpos( $src, $file ) ) {
6371
					wp_style_add_data( $handle, 'suffix', '.min' );
6372
					return $src;
6373
				}
6374
			}
6375
		}
6376
6377
		return $src;
6378
	}
6379
6380
	/**
6381
	 * Maybe inlines a stylesheet.
6382
	 *
6383
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6384
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6385
	 *
6386
	 * Attached to `style_loader_tag` filter.
6387
	 *
6388
	 * @param string $tag The tag that would link to the external asset.
6389
	 * @param string $handle The registered handle of the script in question.
6390
	 *
6391
	 * @return string
6392
	 */
6393
	public static function maybe_inline_style( $tag, $handle ) {
6394
		global $wp_styles;
6395
		$item = $wp_styles->registered[ $handle ];
6396
6397
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6398
			return $tag;
6399
		}
6400
6401
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6402
			$href = $matches[1];
6403
			// Strip off query string
6404
			if ( $pos = strpos( $href, '?' ) ) {
6405
				$href = substr( $href, 0, $pos );
6406
			}
6407
			// Strip off fragment
6408
			if ( $pos = strpos( $href, '#' ) ) {
6409
				$href = substr( $href, 0, $pos );
6410
			}
6411
		} else {
6412
			return $tag;
6413
		}
6414
6415
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6416
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6417
			return $tag;
6418
		}
6419
6420
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6421
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6422
			// And this isn't the pass that actually deals with the RTL version...
6423
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6424
				// Short out, as the RTL version will deal with it in a moment.
6425
				return $tag;
6426
			}
6427
		}
6428
6429
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6430
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6431
		if ( $css ) {
6432
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6433
			if ( empty( $item->extra['after'] ) ) {
6434
				wp_add_inline_style( $handle, $css );
6435
			} else {
6436
				array_unshift( $item->extra['after'], $css );
6437
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6438
			}
6439
		}
6440
6441
		return $tag;
6442
	}
6443
6444
	/**
6445
	 * Loads a view file from the views
6446
	 *
6447
	 * Data passed in with the $data parameter will be available in the
6448
	 * template file as $data['value']
6449
	 *
6450
	 * @param string $template - Template file to load
6451
	 * @param array $data - Any data to pass along to the template
6452
	 * @return boolean - If template file was found
6453
	 **/
6454
	public function load_view( $template, $data = array() ) {
6455
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6456
6457
		if( file_exists( $views_dir . $template ) ) {
6458
			require_once( $views_dir . $template );
6459
			return true;
6460
		}
6461
6462
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6463
		return false;
6464
	}
6465
6466
	/**
6467
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6468
	 */
6469
	public function deprecated_hooks() {
6470
		global $wp_filter;
6471
6472
		/*
6473
		 * Format:
6474
		 * deprecated_filter_name => replacement_name
6475
		 *
6476
		 * If there is no replacement, use null for replacement_name
6477
		 */
6478
		$deprecated_list = array(
6479
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6480
			'wpl_sharing_2014_1'                                     => null,
6481
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6482
			'jetpack_identity_crisis_options_to_check'               => null,
6483
			'update_option_jetpack_single_user_site'                 => null,
6484
			'audio_player_default_colors'                            => null,
6485
			'add_option_jetpack_featured_images_enabled'             => null,
6486
			'add_option_jetpack_update_details'                      => null,
6487
			'add_option_jetpack_updates'                             => null,
6488
			'add_option_jetpack_network_name'                        => null,
6489
			'add_option_jetpack_network_allow_new_registrations'     => null,
6490
			'add_option_jetpack_network_add_new_users'               => null,
6491
			'add_option_jetpack_network_site_upload_space'           => null,
6492
			'add_option_jetpack_network_upload_file_types'           => null,
6493
			'add_option_jetpack_network_enable_administration_menus' => null,
6494
			'add_option_jetpack_is_multi_site'                       => null,
6495
			'add_option_jetpack_is_main_network'                     => null,
6496
			'add_option_jetpack_main_network_site'                   => null,
6497
			'jetpack_sync_all_registered_options'                    => null,
6498
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6499
			'jetpack_is_post_mailable'                               => null,
6500
			'jetpack_seo_site_host'                                  => null,
6501
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6502
			'jetpack_holiday_snow_option_name'                       => null,
6503
			'jetpack_holiday_chance_of_snow'                         => null,
6504
			'jetpack_holiday_snow_js_url'                            => null,
6505
			'jetpack_is_holiday_snow_season'                         => null,
6506
			'jetpack_holiday_snow_option_updated'                    => null,
6507
			'jetpack_holiday_snowing'                                => null,
6508
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6509
			'jetpack_cache_plans'                                    => null,
6510
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6511
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6512
			'jetpack_enable_site_verification'                       => null,
6513
			'can_display_jetpack_manage_notice'                      => null,
6514
			// Removed in Jetpack 7.3.0
6515
			'atd_load_scripts'                                       => null,
6516
			'atd_http_post_timeout'                                  => null,
6517
			'atd_http_post_error'                                    => null,
6518
			'atd_service_domain'                                     => null,
6519
		);
6520
6521
		// This is a silly loop depth. Better way?
6522
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6523
			if ( has_action( $hook ) ) {
6524
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6525
					foreach( $values AS $hooked ) {
6526
						if ( is_callable( $hooked['function'] ) ) {
6527
							$function_name = 'an anonymous function';
6528
						} else {
6529
							$function_name = $hooked['function'];
6530
						}
6531
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6532
					}
6533
				}
6534
			}
6535
		}
6536
	}
6537
6538
	/**
6539
	 * Converts any url in a stylesheet, to the correct absolute url.
6540
	 *
6541
	 * Considerations:
6542
	 *  - Normal, relative URLs     `feh.png`
6543
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6544
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6545
	 *  - Absolute URLs             `http://domain.com/feh.png`
6546
	 *  - Domain root relative URLs `/feh.png`
6547
	 *
6548
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6549
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6550
	 *
6551
	 * @return mixed|string
6552
	 */
6553
	public static function absolutize_css_urls( $css, $css_file_url ) {
6554
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6555
		$css_dir = dirname( $css_file_url );
6556
		$p       = parse_url( $css_dir );
6557
		$domain  = sprintf(
6558
					'%1$s//%2$s%3$s%4$s',
6559
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6560
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6561
					$p['host'],
6562
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6563
				);
6564
6565
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6566
			$find = $replace = array();
6567
			foreach ( $matches as $match ) {
6568
				$url = trim( $match['path'], "'\" \t" );
6569
6570
				// If this is a data url, we don't want to mess with it.
6571
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6572
					continue;
6573
				}
6574
6575
				// If this is an absolute or protocol-agnostic url,
6576
				// we don't want to mess with it.
6577
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6578
					continue;
6579
				}
6580
6581
				switch ( substr( $url, 0, 1 ) ) {
6582
					case '/':
6583
						$absolute = $domain . $url;
6584
						break;
6585
					default:
6586
						$absolute = $css_dir . '/' . $url;
6587
				}
6588
6589
				$find[]    = $match[0];
6590
				$replace[] = sprintf( 'url("%s")', $absolute );
6591
			}
6592
			$css = str_replace( $find, $replace, $css );
6593
		}
6594
6595
		return $css;
6596
	}
6597
6598
	/**
6599
	 * This methods removes all of the registered css files on the front end
6600
	 * from Jetpack in favor of using a single file. In effect "imploding"
6601
	 * all the files into one file.
6602
	 *
6603
	 * Pros:
6604
	 * - Uses only ONE css asset connection instead of 15
6605
	 * - Saves a minimum of 56k
6606
	 * - Reduces server load
6607
	 * - Reduces time to first painted byte
6608
	 *
6609
	 * Cons:
6610
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6611
	 *		should not cause any issues with themes.
6612
	 * - Plugins/themes dequeuing styles no longer do anything. See
6613
	 *		jetpack_implode_frontend_css filter for a workaround
6614
	 *
6615
	 * For some situations developers may wish to disable css imploding and
6616
	 * instead operate in legacy mode where each file loads seperately and
6617
	 * can be edited individually or dequeued. This can be accomplished with
6618
	 * the following line:
6619
	 *
6620
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6621
	 *
6622
	 * @since 3.2
6623
	 **/
6624
	public function implode_frontend_css( $travis_test = false ) {
6625
		$do_implode = true;
6626
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6627
			$do_implode = false;
6628
		}
6629
6630
		// Do not implode CSS when the page loads via the AMP plugin.
6631
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6632
			$do_implode = false;
6633
		}
6634
6635
		/**
6636
		 * Allow CSS to be concatenated into a single jetpack.css file.
6637
		 *
6638
		 * @since 3.2.0
6639
		 *
6640
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6641
		 */
6642
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6643
6644
		// Do not use the imploded file when default behavior was altered through the filter
6645
		if ( ! $do_implode ) {
6646
			return;
6647
		}
6648
6649
		// We do not want to use the imploded file in dev mode, or if not connected
6650
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6651
			if ( ! $travis_test ) {
6652
				return;
6653
			}
6654
		}
6655
6656
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6657
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6658
			return;
6659
		}
6660
6661
		/*
6662
		 * Now we assume Jetpack is connected and able to serve the single
6663
		 * file.
6664
		 *
6665
		 * In the future there will be a check here to serve the file locally
6666
		 * or potentially from the Jetpack CDN
6667
		 *
6668
		 * For now:
6669
		 * - Enqueue a single imploded css file
6670
		 * - Zero out the style_loader_tag for the bundled ones
6671
		 * - Be happy, drink scotch
6672
		 */
6673
6674
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6675
6676
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6677
6678
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6679
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6680
	}
6681
6682
	function concat_remove_style_loader_tag( $tag, $handle ) {
6683
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6684
			$tag = '';
6685
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6686
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6687
			}
6688
		}
6689
6690
		return $tag;
6691
	}
6692
6693
	/*
6694
	 * Check the heartbeat data
6695
	 *
6696
	 * Organizes the heartbeat data by severity.  For example, if the site
6697
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6698
	 *
6699
	 * Data will be added to "caution" array, if it either:
6700
	 *  - Out of date Jetpack version
6701
	 *  - Out of date WP version
6702
	 *  - Out of date PHP version
6703
	 *
6704
	 * $return array $filtered_data
6705
	 */
6706
	public static function jetpack_check_heartbeat_data() {
6707
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6708
6709
		$good    = array();
6710
		$caution = array();
6711
		$bad     = array();
6712
6713
		foreach ( $raw_data as $stat => $value ) {
6714
6715
			// Check jetpack version
6716
			if ( 'version' == $stat ) {
6717
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6718
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6719
					continue;
6720
				}
6721
			}
6722
6723
			// Check WP version
6724
			if ( 'wp-version' == $stat ) {
6725
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6726
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6727
					continue;
6728
				}
6729
			}
6730
6731
			// Check PHP version
6732
			if ( 'php-version' == $stat ) {
6733
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6734
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6735
					continue;
6736
				}
6737
			}
6738
6739
			// Check ID crisis
6740
			if ( 'identitycrisis' == $stat ) {
6741
				if ( 'yes' == $value ) {
6742
					$bad[ $stat ] = $value;
6743
					continue;
6744
				}
6745
			}
6746
6747
			// The rest are good :)
6748
			$good[ $stat ] = $value;
6749
		}
6750
6751
		$filtered_data = array(
6752
			'good'    => $good,
6753
			'caution' => $caution,
6754
			'bad'     => $bad
6755
		);
6756
6757
		return $filtered_data;
6758
	}
6759
6760
6761
	/*
6762
	 * This method is used to organize all options that can be reset
6763
	 * without disconnecting Jetpack.
6764
	 *
6765
	 * It is used in class.jetpack-cli.php to reset options
6766
	 *
6767
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6768
	 *
6769
	 * @return array of options to delete.
6770
	 */
6771
	public static function get_jetpack_options_for_reset() {
6772
		return Jetpack_Options::get_options_for_reset();
6773
	}
6774
6775
	/*
6776
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6777
	 * so we can bring them directly to their site in calypso.
6778
	 *
6779
	 * @param string | url
6780
	 * @return string | url without the guff
6781
	 */
6782
	public static function build_raw_urls( $url ) {
6783
		$strip_http = '/.*?:\/\//i';
6784
		$url = preg_replace( $strip_http, '', $url  );
6785
		$url = str_replace( '/', '::', $url );
6786
		return $url;
6787
	}
6788
6789
	/**
6790
	 * Stores and prints out domains to prefetch for page speed optimization.
6791
	 *
6792
	 * @param mixed $new_urls
6793
	 */
6794
	public static function dns_prefetch( $new_urls = null ) {
6795
		static $prefetch_urls = array();
6796
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6797
			echo "\r\n";
6798
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6799
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6800
			}
6801
		} elseif ( ! empty( $new_urls ) ) {
6802
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6803
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6804
			}
6805
			foreach ( (array) $new_urls as $this_new_url ) {
6806
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6807
			}
6808
			$prefetch_urls = array_unique( $prefetch_urls );
6809
		}
6810
	}
6811
6812
	public function wp_dashboard_setup() {
6813
		if ( self::is_active() ) {
6814
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6815
		}
6816
6817
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6818
			$jetpack_logo = new Jetpack_Logo();
6819
			$widget_title = sprintf(
6820
				wp_kses(
6821
					/* translators: Placeholder is a Jetpack logo. */
6822
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6823
					array( 'span' => array() )
6824
				),
6825
				$jetpack_logo->get_jp_emblem( true )
6826
			);
6827
6828
			wp_add_dashboard_widget(
6829
				'jetpack_summary_widget',
6830
				$widget_title,
6831
				array( __CLASS__, 'dashboard_widget' )
6832
			);
6833
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6834
6835
			// If we're inactive and not in development mode, sort our box to the top.
6836
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6837
				global $wp_meta_boxes;
6838
6839
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6840
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6841
6842
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6843
			}
6844
		}
6845
	}
6846
6847
	/**
6848
	 * @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...
6849
	 * @return mixed
6850
	 */
6851
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6852
		if ( ! is_array( $sorted ) ) {
6853
			return $sorted;
6854
		}
6855
6856
		foreach ( $sorted as $box_context => $ids ) {
6857
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6858
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6859
				continue;
6860
			}
6861
6862
			$ids_array = explode( ',', $ids );
6863
			$key = array_search( 'dashboard_stats', $ids_array );
6864
6865
			if ( false !== $key ) {
6866
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6867
				$ids_array[ $key ] = 'jetpack_summary_widget';
6868
				$sorted[ $box_context ] = implode( ',', $ids_array );
6869
				// We've found it, stop searching, and just return.
6870
				break;
6871
			}
6872
		}
6873
6874
		return $sorted;
6875
	}
6876
6877
	public static function dashboard_widget() {
6878
		/**
6879
		 * Fires when the dashboard is loaded.
6880
		 *
6881
		 * @since 3.4.0
6882
		 */
6883
		do_action( 'jetpack_dashboard_widget' );
6884
	}
6885
6886
	public static function dashboard_widget_footer() {
6887
		?>
6888
		<footer>
6889
6890
		<div class="protect">
6891
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6892
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6893
				<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>
6894
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6895
				<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' ); ?>">
6896
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6897
				</a>
6898
			<?php else : ?>
6899
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6900
			<?php endif; ?>
6901
		</div>
6902
6903
		<div class="akismet">
6904
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6905
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6906
				<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>
6907
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6908
				<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">
6909
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6910
				</a>
6911
			<?php else : ?>
6912
				<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>
6913
			<?php endif; ?>
6914
		</div>
6915
6916
		</footer>
6917
		<?php
6918
	}
6919
6920
	/*
6921
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6922
	 */
6923
	function jetpack_icon_user_connected( $columns ) {
6924
		$columns['user_jetpack'] = '';
6925
		return $columns;
6926
	}
6927
6928
	/*
6929
	 * Show Jetpack icon if the user is linked.
6930
	 */
6931
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6932
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6933
			$jetpack_logo = new Jetpack_Logo();
6934
			$emblem_html = sprintf(
6935
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6936
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6937
				$jetpack_logo->get_jp_emblem()
6938
			);
6939
			return $emblem_html;
6940
		}
6941
6942
		return $val;
6943
	}
6944
6945
	/*
6946
	 * Style the Jetpack user column
6947
	 */
6948
	function jetpack_user_col_style() {
6949
		global $current_screen;
6950
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6951
			<style>
6952
				.fixed .column-user_jetpack {
6953
					width: 21px;
6954
				}
6955
				.jp-emblem-user-admin svg {
6956
					width: 20px;
6957
					height: 20px;
6958
				}
6959
				.jp-emblem-user-admin path {
6960
					fill: #00BE28;
6961
				}
6962
			</style>
6963
		<?php }
6964
	}
6965
6966
	/**
6967
	 * Checks if Akismet is active and working.
6968
	 *
6969
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6970
	 * that implied usage of methods present since more recent version.
6971
	 * See https://github.com/Automattic/jetpack/pull/9585
6972
	 *
6973
	 * @since  5.1.0
6974
	 *
6975
	 * @return bool True = Akismet available. False = Aksimet not available.
6976
	 */
6977
	public static function is_akismet_active() {
6978
		static $status = null;
6979
6980
		if ( ! is_null( $status ) ) {
6981
			return $status;
6982
		}
6983
6984
		// Check if a modern version of Akismet is active.
6985
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6986
			$status = false;
6987
			return $status;
6988
		}
6989
6990
		// Make sure there is a key known to Akismet at all before verifying key.
6991
		$akismet_key = Akismet::get_api_key();
6992
		if ( ! $akismet_key ) {
6993
			$status = false;
6994
			return $status;
6995
		}
6996
6997
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6998
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6999
7000
		// 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.
7001
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7002
		// We cache the result of the Akismet key verification for ten minutes.
7003
		if ( ! $akismet_key_state || $recheck ) {
7004
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7005
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7006
		}
7007
7008
		$status = 'valid' === $akismet_key_state;
7009
7010
		return $status;
7011
	}
7012
7013
	/**
7014
	 * @deprecated
7015
	 *
7016
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7017
	 */
7018
	public static function is_function_in_backtrace() {
7019
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7020
	}
7021
7022
	/**
7023
	 * Given a minified path, and a non-minified path, will return
7024
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7025
	 *
7026
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7027
	 * root Jetpack directory.
7028
	 *
7029
	 * @since 5.6.0
7030
	 *
7031
	 * @param string $min_path
7032
	 * @param string $non_min_path
7033
	 * @return string The URL to the file
7034
	 */
7035
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7036
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7037
	}
7038
7039
	/**
7040
	 * Checks for whether Jetpack Backup & Scan is enabled.
7041
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7042
	 * @return bool|int|mixed
7043
	 */
7044
	public static function is_rewind_enabled() {
7045
		if ( ! Jetpack::is_active() ) {
7046
			return false;
7047
		}
7048
7049
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7050
		if ( false === $rewind_enabled ) {
7051
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7052
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7053
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7054
				&& ! empty( $rewind_data['state'] )
7055
				&& 'active' === $rewind_data['state'] )
7056
				? 1
7057
				: 0;
7058
7059
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7060
		}
7061
		return $rewind_enabled;
7062
	}
7063
7064
	/**
7065
	 * Return Calypso environment value; used for developing Jetpack and pairing
7066
	 * it with different Calypso enrionments, such as localhost.
7067
	 *
7068
	 * @since 7.4.0
7069
	 *
7070
	 * @return string Calypso environment
7071
	 */
7072
	public static function get_calypso_env() {
7073
		if ( isset( $_GET['calypso_env'] ) ) {
7074
			return sanitize_key( $_GET['calypso_env'] );
7075
		}
7076
7077
		if ( getenv( 'CALYPSO_ENV' ) ) {
7078
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7079
		}
7080
7081
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7082
			return sanitize_key( CALYPSO_ENV );
7083
		}
7084
7085
		return '';
7086
	}
7087
7088
	/**
7089
	 * Checks whether or not TOS has been agreed upon.
7090
	 * Will return true if a user has clicked to register, or is already connected.
7091
	 */
7092
	public static function jetpack_tos_agreed() {
7093
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7094
	}
7095
7096
	/**
7097
	 * Handles activating default modules as well general cleanup for the new connection.
7098
	 *
7099
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7100
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7101
	 * @param boolean $send_state_messages          Whether to send state messages.
7102
	 * @return void
7103
	 */
7104
	public static function handle_post_authorization_actions(
7105
		$activate_sso = false,
7106
		$redirect_on_activation_error = false,
7107
		$send_state_messages = true
7108
	) {
7109
		$other_modules = $activate_sso
7110
			? array( 'sso' )
7111
			: array();
7112
7113
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7114
			Jetpack::delete_active_modules();
7115
7116
			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...
7117
		} else {
7118
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7119
		}
7120
7121
		// Since this is a fresh connection, be sure to clear out IDC options
7122
		Jetpack_IDC::clear_all_idc_options();
7123
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7124
7125
		// Start nonce cleaner
7126
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7127
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7128
7129
		if ( $send_state_messages ) {
7130
			Jetpack::state( 'message', 'authorized' );
7131
		}
7132
	}
7133
7134
	/**
7135
	 * Returns a boolean for whether backups UI should be displayed or not.
7136
	 *
7137
	 * @return bool Should backups UI be displayed?
7138
	 */
7139
	public static function show_backups_ui() {
7140
		/**
7141
		 * Whether UI for backups should be displayed.
7142
		 *
7143
		 * @since 6.5.0
7144
		 *
7145
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7146
		 */
7147
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7148
	}
7149
7150
	/*
7151
	 * Deprecated manage functions
7152
	 */
7153
	function prepare_manage_jetpack_notice() {
7154
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7155
	}
7156
	function manage_activate_screen() {
7157
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7158
	}
7159
	function admin_jetpack_manage_notice() {
7160
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7161
	}
7162
	function opt_out_jetpack_manage_url() {
7163
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7164
	}
7165
	function opt_in_jetpack_manage_url() {
7166
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7167
	}
7168
	function opt_in_jetpack_manage_notice() {
7169
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7170
	}
7171
	function can_display_jetpack_manage_notice() {
7172
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7173
	}
7174
7175
	/**
7176
	 * Clean leftoveruser meta.
7177
	 *
7178
	 * Delete Jetpack-related user meta when it is no longer needed.
7179
	 *
7180
	 * @since 7.3.0
7181
	 *
7182
	 * @param int $user_id User ID being updated.
7183
	 */
7184
	public static function user_meta_cleanup( $user_id ) {
7185
		$meta_keys = array(
7186
			// AtD removed from Jetpack 7.3
7187
			'AtD_options',
7188
			'AtD_check_when',
7189
			'AtD_guess_lang',
7190
			'AtD_ignored_phrases',
7191
		);
7192
7193
		foreach ( $meta_keys as $meta_key ) {
7194
			if ( get_user_meta( $user_id, $meta_key ) ) {
7195
				delete_user_meta( $user_id, $meta_key );
7196
			}
7197
		}
7198
	}
7199
7200
	function is_active_and_not_development_mode( $maybe ) {
7201
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7202
			return false;
7203
		}
7204
		return true;
7205
	}
7206
7207
}
7208