Completed
Push — update/polish-constants-packag... ( ecda50...af8b6e )
by Marin
28:16 queued 16:25
created

class.jetpack.php (33 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1560
	}
1561
1562
	/**
1563
	 * Make an API call to WordPress.com for plan status
1564
	 *
1565
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1566
	 *
1567
	 * @return bool True if plan is updated, false if no update
1568
	 */
1569
	public static function refresh_active_plan_from_wpcom() {
1570
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1571
		return Jetpack_Plan::refresh_from_wpcom();
1572
	}
1573
1574
	/**
1575
	 * Get the plan that this Jetpack site is currently using
1576
	 *
1577
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1578
	 * @return array Active Jetpack plan details.
1579
	 */
1580
	public static function get_active_plan() {
1581
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1582
		return Jetpack_Plan::get();
1583
	}
1584
1585
	/**
1586
	 * Determine whether the active plan supports a particular feature
1587
	 *
1588
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1589
	 * @return bool True if plan supports feature, false if not.
1590
	 */
1591
	public static function active_plan_supports( $feature ) {
1592
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1593
		return Jetpack_Plan::supports( $feature );
1594
	}
1595
1596
	/**
1597
	 * Is Jetpack in development (offline) mode?
1598
	 */
1599
	public static function is_development_mode() {
1600
		$development_mode = false;
1601
1602
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1603
			$development_mode = JETPACK_DEV_DEBUG;
1604
		} elseif ( $site_url = site_url() ) {
1605
			$development_mode = false === strpos( $site_url, '.' );
1606
		}
1607
1608
		/**
1609
		 * Filters Jetpack's development mode.
1610
		 *
1611
		 * @see https://jetpack.com/support/development-mode/
1612
		 *
1613
		 * @since 2.2.1
1614
		 *
1615
		 * @param bool $development_mode Is Jetpack's development mode active.
1616
		 */
1617
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1618
		return $development_mode;
1619
	}
1620
1621
	/**
1622
	 * Whether the site is currently onboarding or not.
1623
	 * A site is considered as being onboarded if it currently has an onboarding token.
1624
	 *
1625
	 * @since 5.8
1626
	 *
1627
	 * @access public
1628
	 * @static
1629
	 *
1630
	 * @return bool True if the site is currently onboarding, false otherwise
1631
	 */
1632
	public static function is_onboarding() {
1633
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1634
	}
1635
1636
	/**
1637
	 * Determines reason for Jetpack development mode.
1638
	 */
1639
	public static function development_mode_trigger_text() {
1640
		if ( ! Jetpack::is_development_mode() ) {
1641
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1642
		}
1643
1644
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1645
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1646
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1647
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1648
		} else {
1649
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1650
		}
1651
1652
		return $notice;
1653
1654
	}
1655
	/**
1656
	* Get Jetpack development mode notice text and notice class.
1657
	*
1658
	* Mirrors the checks made in Jetpack::is_development_mode
1659
	*
1660
	*/
1661
	public static function show_development_mode_notice() {
1662 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1663
			$notice = sprintf(
1664
			/* translators: %s is a URL */
1665
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1666
				'https://jetpack.com/support/development-mode/'
1667
			);
1668
1669
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1670
1671
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1672
		}
1673
1674
		// Throw up a notice if using a development version and as for feedback.
1675
		if ( Jetpack::is_development_version() ) {
1676
			/* translators: %s is a URL */
1677
			$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/' );
1678
1679
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1680
		}
1681
		// Throw up a notice if using staging mode
1682
		if ( Jetpack::is_staging_site() ) {
1683
			/* translators: %s is a URL */
1684
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1685
1686
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1687
		}
1688
	}
1689
1690
	/**
1691
	 * Whether Jetpack's version maps to a public release, or a development version.
1692
	 */
1693
	public static function is_development_version() {
1694
		/**
1695
		 * Allows filtering whether this is a development version of Jetpack.
1696
		 *
1697
		 * This filter is especially useful for tests.
1698
		 *
1699
		 * @since 4.3.0
1700
		 *
1701
		 * @param bool $development_version Is this a develoment version of Jetpack?
1702
		 */
1703
		return (bool) apply_filters(
1704
			'jetpack_development_version',
1705
			! preg_match( '/^\d+(\.\d+)+$/', Constants_Manager::get_constant( 'JETPACK__VERSION' ) )
1706
		);
1707
	}
1708
1709
	/**
1710
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1711
	 */
1712
	public static function is_user_connected( $user_id = false ) {
1713
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1714
		if ( ! $user_id ) {
1715
			return false;
1716
		}
1717
1718
		return (bool) Jetpack_Data::get_access_token( $user_id );
1719
	}
1720
1721
	/**
1722
	 * Get the wpcom user data of the current|specified connected user.
1723
	 */
1724
	public static function get_connected_user_data( $user_id = null ) {
1725
		if ( ! $user_id ) {
1726
			$user_id = get_current_user_id();
1727
		}
1728
1729
		$transient_key = "jetpack_connected_user_data_$user_id";
1730
1731
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1732
			return $cached_user_data;
1733
		}
1734
1735
		Jetpack::load_xml_rpc_client();
1736
		$xml = new Jetpack_IXR_Client( array(
1737
			'user_id' => $user_id,
1738
		) );
1739
		$xml->query( 'wpcom.getUser' );
1740
		if ( ! $xml->isError() ) {
1741
			$user_data = $xml->getResponse();
1742
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1743
			return $user_data;
1744
		}
1745
1746
		return false;
1747
	}
1748
1749
	/**
1750
	 * Get the wpcom email of the current|specified connected user.
1751
	 */
1752 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1753
		if ( ! $user_id ) {
1754
			$user_id = get_current_user_id();
1755
		}
1756
		Jetpack::load_xml_rpc_client();
1757
		$xml = new Jetpack_IXR_Client( array(
1758
			'user_id' => $user_id,
1759
		) );
1760
		$xml->query( 'wpcom.getUserEmail' );
1761
		if ( ! $xml->isError() ) {
1762
			return $xml->getResponse();
1763
		}
1764
		return false;
1765
	}
1766
1767
	/**
1768
	 * Get the wpcom email of the master user.
1769
	 */
1770
	public static function get_master_user_email() {
1771
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1772
		if ( $master_user_id ) {
1773
			return self::get_connected_user_email( $master_user_id );
1774
		}
1775
		return '';
1776
	}
1777
1778
	function current_user_is_connection_owner() {
1779
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1780
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1781
	}
1782
1783
	/**
1784
	 * Gets current user IP address.
1785
	 *
1786
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1787
	 *
1788
	 * @return string                  Current user IP address.
1789
	 */
1790
	public static function current_user_ip( $check_all_headers = false ) {
1791
		if ( $check_all_headers ) {
1792
			foreach ( array(
1793
				'HTTP_CF_CONNECTING_IP',
1794
				'HTTP_CLIENT_IP',
1795
				'HTTP_X_FORWARDED_FOR',
1796
				'HTTP_X_FORWARDED',
1797
				'HTTP_X_CLUSTER_CLIENT_IP',
1798
				'HTTP_FORWARDED_FOR',
1799
				'HTTP_FORWARDED',
1800
				'HTTP_VIA',
1801
			) as $key ) {
1802
				if ( ! empty( $_SERVER[ $key ] ) ) {
1803
					return $_SERVER[ $key ];
1804
				}
1805
			}
1806
		}
1807
1808
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1809
	}
1810
1811
	/**
1812
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1813
	 */
1814
	function extra_oembed_providers() {
1815
		// Cloudup: https://dev.cloudup.com/#oembed
1816
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1817
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1818
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1819
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1820
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1821
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1822
	}
1823
1824
	/**
1825
	 * Synchronize connected user role changes
1826
	 */
1827
	function user_role_change( $user_id ) {
1828
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1829
		Jetpack_Sync_Users::user_role_change( $user_id );
1830
	}
1831
1832
	/**
1833
	 * Loads the currently active modules.
1834
	 */
1835
	public static function load_modules() {
1836
		if (
1837
			! self::is_active()
1838
			&& ! self::is_development_mode()
1839
			&& ! self::is_onboarding()
1840
			&& (
1841
				! is_multisite()
1842
				|| ! get_site_option( 'jetpack_protect_active' )
1843
			)
1844
		) {
1845
			return;
1846
		}
1847
1848
		$version = Jetpack_Options::get_option( 'version' );
1849 View Code Duplication
		if ( ! $version ) {
1850
			$version = $old_version = JETPACK__VERSION . ':' . time();
1851
			/** This action is documented in class.jetpack.php */
1852
			do_action( 'updating_jetpack_version', $version, false );
1853
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1854
		}
1855
		list( $version ) = explode( ':', $version );
1856
1857
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1858
1859
		$modules_data = array();
1860
1861
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1862
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1863
			$updated_modules = array();
1864
			foreach ( $modules as $module ) {
1865
				$modules_data[ $module ] = Jetpack::get_module( $module );
1866
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1867
					continue;
1868
				}
1869
1870
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1871
					continue;
1872
				}
1873
1874
				$updated_modules[] = $module;
1875
			}
1876
1877
			$modules = array_diff( $modules, $updated_modules );
1878
		}
1879
1880
		$is_development_mode = Jetpack::is_development_mode();
1881
1882
		foreach ( $modules as $index => $module ) {
1883
			// If we're in dev mode, disable modules requiring a connection
1884
			if ( $is_development_mode ) {
1885
				// Prime the pump if we need to
1886
				if ( empty( $modules_data[ $module ] ) ) {
1887
					$modules_data[ $module ] = Jetpack::get_module( $module );
1888
				}
1889
				// If the module requires a connection, but we're in local mode, don't include it.
1890
				if ( $modules_data[ $module ]['requires_connection'] ) {
1891
					continue;
1892
				}
1893
			}
1894
1895
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1896
				continue;
1897
			}
1898
1899
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1900
				unset( $modules[ $index ] );
1901
				self::update_active_modules( array_values( $modules ) );
1902
				continue;
1903
			}
1904
1905
			/**
1906
			 * Fires when a specific module is loaded.
1907
			 * The dynamic part of the hook, $module, is the module slug.
1908
			 *
1909
			 * @since 1.1.0
1910
			 */
1911
			do_action( 'jetpack_module_loaded_' . $module );
1912
		}
1913
1914
		/**
1915
		 * Fires when all the modules are loaded.
1916
		 *
1917
		 * @since 1.1.0
1918
		 */
1919
		do_action( 'jetpack_modules_loaded' );
1920
1921
		// 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.
1922
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1923
	}
1924
1925
	/**
1926
	 * Check if Jetpack's REST API compat file should be included
1927
	 * @action plugins_loaded
1928
	 * @return null
1929
	 */
1930
	public function check_rest_api_compat() {
1931
		/**
1932
		 * Filters the list of REST API compat files to be included.
1933
		 *
1934
		 * @since 2.2.5
1935
		 *
1936
		 * @param array $args Array of REST API compat files to include.
1937
		 */
1938
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1939
1940
		if ( function_exists( 'bbpress' ) )
1941
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1942
1943
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1944
			require_once $_jetpack_rest_api_compat_include;
1945
	}
1946
1947
	/**
1948
	 * Gets all plugins currently active in values, regardless of whether they're
1949
	 * traditionally activated or network activated.
1950
	 *
1951
	 * @todo Store the result in core's object cache maybe?
1952
	 */
1953
	public static function get_active_plugins() {
1954
		$active_plugins = (array) get_option( 'active_plugins', array() );
1955
1956
		if ( is_multisite() ) {
1957
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1958
			// whereas active_plugins stores them in the values.
1959
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1960
			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...
1961
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1962
			}
1963
		}
1964
1965
		sort( $active_plugins );
1966
1967
		return array_unique( $active_plugins );
1968
	}
1969
1970
	/**
1971
	 * Gets and parses additional plugin data to send with the heartbeat data
1972
	 *
1973
	 * @since 3.8.1
1974
	 *
1975
	 * @return array Array of plugin data
1976
	 */
1977
	public static function get_parsed_plugin_data() {
1978
		if ( ! function_exists( 'get_plugins' ) ) {
1979
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1980
		}
1981
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1982
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1983
		$active_plugins = Jetpack::get_active_plugins();
1984
1985
		$plugins = array();
1986
		foreach ( $all_plugins as $path => $plugin_data ) {
1987
			$plugins[ $path ] = array(
1988
					'is_active' => in_array( $path, $active_plugins ),
1989
					'file'      => $path,
1990
					'name'      => $plugin_data['Name'],
1991
					'version'   => $plugin_data['Version'],
1992
					'author'    => $plugin_data['Author'],
1993
			);
1994
		}
1995
1996
		return $plugins;
1997
	}
1998
1999
	/**
2000
	 * Gets and parses theme data to send with the heartbeat data
2001
	 *
2002
	 * @since 3.8.1
2003
	 *
2004
	 * @return array Array of theme data
2005
	 */
2006
	public static function get_parsed_theme_data() {
2007
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2008
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2009
2010
		$themes = array();
2011
		foreach ( $all_themes as $slug => $theme_data ) {
2012
			$theme_headers = array();
2013
			foreach ( $header_keys as $header_key ) {
2014
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2015
			}
2016
2017
			$themes[ $slug ] = array(
2018
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2019
					'slug' => $slug,
2020
					'theme_root' => $theme_data->get_theme_root_uri(),
2021
					'parent' => $theme_data->parent(),
2022
					'headers' => $theme_headers
2023
			);
2024
		}
2025
2026
		return $themes;
2027
	}
2028
2029
	/**
2030
	 * Checks whether a specific plugin is active.
2031
	 *
2032
	 * We don't want to store these in a static variable, in case
2033
	 * there are switch_to_blog() calls involved.
2034
	 */
2035
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2036
		return in_array( $plugin, self::get_active_plugins() );
2037
	}
2038
2039
	/**
2040
	 * Check if Jetpack's Open Graph tags should be used.
2041
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2042
	 *
2043
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2044
	 * @action plugins_loaded
2045
	 * @return null
2046
	 */
2047
	public function check_open_graph() {
2048
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2049
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2050
		}
2051
2052
		$active_plugins = self::get_active_plugins();
2053
2054
		if ( ! empty( $active_plugins ) ) {
2055
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2056
				if ( in_array( $plugin, $active_plugins ) ) {
2057
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2058
					break;
2059
				}
2060
			}
2061
		}
2062
2063
		/**
2064
		 * Allow the addition of Open Graph Meta Tags to all pages.
2065
		 *
2066
		 * @since 2.0.3
2067
		 *
2068
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2069
		 */
2070
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2071
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2072
		}
2073
	}
2074
2075
	/**
2076
	 * Check if Jetpack's Twitter tags should be used.
2077
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2078
	 *
2079
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2080
	 * @action plugins_loaded
2081
	 * @return null
2082
	 */
2083
	public function check_twitter_tags() {
2084
2085
		$active_plugins = self::get_active_plugins();
2086
2087
		if ( ! empty( $active_plugins ) ) {
2088
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2089
				if ( in_array( $plugin, $active_plugins ) ) {
2090
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2091
					break;
2092
				}
2093
			}
2094
		}
2095
2096
		/**
2097
		 * Allow Twitter Card Meta tags to be disabled.
2098
		 *
2099
		 * @since 2.6.0
2100
		 *
2101
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2102
		 */
2103
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2104
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2105
		}
2106
	}
2107
2108
	/**
2109
	 * Allows plugins to submit security reports.
2110
 	 *
2111
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2112
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2113
	 * @param array   $args         See definitions above
2114
	 */
2115
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2116
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2117
	}
2118
2119
/* Jetpack Options API */
2120
2121
	public static function get_option_names( $type = 'compact' ) {
2122
		return Jetpack_Options::get_option_names( $type );
2123
	}
2124
2125
	/**
2126
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2127
 	 *
2128
	 * @param string $name    Option name
2129
	 * @param mixed  $default (optional)
2130
	 */
2131
	public static function get_option( $name, $default = false ) {
2132
		return Jetpack_Options::get_option( $name, $default );
2133
	}
2134
2135
	/**
2136
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2137
 	 *
2138
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2139
	 * @param string $name  Option name
2140
	 * @param mixed  $value Option value
2141
	 */
2142
	public static function update_option( $name, $value ) {
2143
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2144
		return Jetpack_Options::update_option( $name, $value );
2145
	}
2146
2147
	/**
2148
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2149
 	 *
2150
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2151
	 * @param array $array array( option name => option value, ... )
2152
	 */
2153
	public static function update_options( $array ) {
2154
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2155
		return Jetpack_Options::update_options( $array );
2156
	}
2157
2158
	/**
2159
	 * Deletes the given option.  May be passed multiple option names as an array.
2160
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2161
	 *
2162
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2163
	 * @param string|array $names
2164
	 */
2165
	public static function delete_option( $names ) {
2166
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2167
		return Jetpack_Options::delete_option( $names );
2168
	}
2169
2170
	/**
2171
	 * Enters a user token into the user_tokens option
2172
	 *
2173
	 * @param int $user_id
2174
	 * @param string $token
2175
	 * return bool
2176
	 */
2177
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2178
		// not designed for concurrent updates
2179
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2180
		if ( ! is_array( $user_tokens ) )
2181
			$user_tokens = array();
2182
		$user_tokens[$user_id] = $token;
2183
		if ( $is_master_user ) {
2184
			$master_user = $user_id;
2185
			$options     = compact( 'user_tokens', 'master_user' );
2186
		} else {
2187
			$options = compact( 'user_tokens' );
2188
		}
2189
		return Jetpack_Options::update_options( $options );
2190
	}
2191
2192
	/**
2193
	 * Returns an array of all PHP files in the specified absolute path.
2194
	 * Equivalent to glob( "$absolute_path/*.php" ).
2195
	 *
2196
	 * @param string $absolute_path The absolute path of the directory to search.
2197
	 * @return array Array of absolute paths to the PHP files.
2198
	 */
2199
	public static function glob_php( $absolute_path ) {
2200
		if ( function_exists( 'glob' ) ) {
2201
			return glob( "$absolute_path/*.php" );
2202
		}
2203
2204
		$absolute_path = untrailingslashit( $absolute_path );
2205
		$files = array();
2206
		if ( ! $dir = @opendir( $absolute_path ) ) {
2207
			return $files;
2208
		}
2209
2210
		while ( false !== $file = readdir( $dir ) ) {
2211
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2212
				continue;
2213
			}
2214
2215
			$file = "$absolute_path/$file";
2216
2217
			if ( ! is_file( $file ) ) {
2218
				continue;
2219
			}
2220
2221
			$files[] = $file;
2222
		}
2223
2224
		closedir( $dir );
2225
2226
		return $files;
2227
	}
2228
2229
	public static function activate_new_modules( $redirect = false ) {
2230
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2231
			return;
2232
		}
2233
2234
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2235 View Code Duplication
		if ( ! $jetpack_old_version ) {
2236
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2237
			/** This action is documented in class.jetpack.php */
2238
			do_action( 'updating_jetpack_version', $version, false );
2239
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2240
		}
2241
2242
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2243
2244
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2245
			return;
2246
		}
2247
2248
		$active_modules     = Jetpack::get_active_modules();
2249
		$reactivate_modules = array();
2250
		foreach ( $active_modules as $active_module ) {
2251
			$module = Jetpack::get_module( $active_module );
2252
			if ( ! isset( $module['changed'] ) ) {
2253
				continue;
2254
			}
2255
2256
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2257
				continue;
2258
			}
2259
2260
			$reactivate_modules[] = $active_module;
2261
			Jetpack::deactivate_module( $active_module );
2262
		}
2263
2264
		$new_version = JETPACK__VERSION . ':' . time();
2265
		/** This action is documented in class.jetpack.php */
2266
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2267
		Jetpack_Options::update_options(
2268
			array(
2269
				'version'     => $new_version,
2270
				'old_version' => $jetpack_old_version,
2271
			)
2272
		);
2273
2274
		Jetpack::state( 'message', 'modules_activated' );
2275
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
0 ignored issues
show
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...
2276
2277
		if ( $redirect ) {
2278
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2279
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2280
				$page = $_GET['page'];
2281
			}
2282
2283
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2284
			exit;
2285
		}
2286
	}
2287
2288
	/**
2289
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2290
	 * Make sure to tuck away module "library" files in a sub-directory.
2291
	 */
2292
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2293
		static $modules = null;
2294
2295
		if ( ! isset( $modules ) ) {
2296
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2297
			// Use the cache if we're on the front-end and it's available...
2298
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2299
				$modules = $available_modules_option[ JETPACK__VERSION ];
2300
			} else {
2301
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2302
2303
				$modules = array();
2304
2305
				foreach ( $files as $file ) {
2306
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2307
						continue;
2308
					}
2309
2310
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2311
				}
2312
2313
				Jetpack_Options::update_option( 'available_modules', array(
2314
					JETPACK__VERSION => $modules,
2315
				) );
2316
			}
2317
		}
2318
2319
		/**
2320
		 * Filters the array of modules available to be activated.
2321
		 *
2322
		 * @since 2.4.0
2323
		 *
2324
		 * @param array $modules Array of available modules.
2325
		 * @param string $min_version Minimum version number required to use modules.
2326
		 * @param string $max_version Maximum version number required to use modules.
2327
		 */
2328
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2329
2330
		if ( ! $min_version && ! $max_version ) {
2331
			return array_keys( $mods );
2332
		}
2333
2334
		$r = array();
2335
		foreach ( $mods as $slug => $introduced ) {
2336
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2337
				continue;
2338
			}
2339
2340
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2341
				continue;
2342
			}
2343
2344
			$r[] = $slug;
2345
		}
2346
2347
		return $r;
2348
	}
2349
2350
	/**
2351
	 * Default modules loaded on activation.
2352
	 */
2353
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2354
		$return = array();
2355
2356
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2357
			$module_data = Jetpack::get_module( $module );
2358
2359
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2360
				case 'yes' :
2361
					$return[] = $module;
2362
					break;
2363
				case 'public' :
2364
					if ( Jetpack_Options::get_option( 'public' ) ) {
2365
						$return[] = $module;
2366
					}
2367
					break;
2368
				case 'no' :
2369
				default :
2370
					break;
2371
			}
2372
		}
2373
		/**
2374
		 * Filters the array of default modules.
2375
		 *
2376
		 * @since 2.5.0
2377
		 *
2378
		 * @param array $return Array of default modules.
2379
		 * @param string $min_version Minimum version number required to use modules.
2380
		 * @param string $max_version Maximum version number required to use modules.
2381
		 */
2382
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2383
	}
2384
2385
	/**
2386
	 * Checks activated modules during auto-activation to determine
2387
	 * if any of those modules are being deprecated.  If so, close
2388
	 * them out, and add any replacement modules.
2389
	 *
2390
	 * Runs at priority 99 by default.
2391
	 *
2392
	 * This is run late, so that it can still activate a module if
2393
	 * the new module is a replacement for another that the user
2394
	 * currently has active, even if something at the normal priority
2395
	 * would kibosh everything.
2396
	 *
2397
	 * @since 2.6
2398
	 * @uses jetpack_get_default_modules filter
2399
	 * @param array $modules
2400
	 * @return array
2401
	 */
2402
	function handle_deprecated_modules( $modules ) {
2403
		$deprecated_modules = array(
2404
			'debug'            => null,  // Closed out and moved to the debugger library.
2405
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2406
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2407
		);
2408
2409
		// Don't activate SSO if they never completed activating WPCC.
2410
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2411
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2412
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2413
				$deprecated_modules['wpcc'] = null;
2414
			}
2415
		}
2416
2417
		foreach ( $deprecated_modules as $module => $replacement ) {
2418
			if ( Jetpack::is_module_active( $module ) ) {
2419
				self::deactivate_module( $module );
2420
				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...
2421
					$modules[] = $replacement;
2422
				}
2423
			}
2424
		}
2425
2426
		return array_unique( $modules );
2427
	}
2428
2429
	/**
2430
	 * Checks activated plugins during auto-activation to determine
2431
	 * if any of those plugins are in the list with a corresponding module
2432
	 * that is not compatible with the plugin. The module will not be allowed
2433
	 * to auto-activate.
2434
	 *
2435
	 * @since 2.6
2436
	 * @uses jetpack_get_default_modules filter
2437
	 * @param array $modules
2438
	 * @return array
2439
	 */
2440
	function filter_default_modules( $modules ) {
2441
2442
		$active_plugins = self::get_active_plugins();
2443
2444
		if ( ! empty( $active_plugins ) ) {
2445
2446
			// For each module we'd like to auto-activate...
2447
			foreach ( $modules as $key => $module ) {
2448
				// If there are potential conflicts for it...
2449
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2450
					// For each potential conflict...
2451
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2452
						// If that conflicting plugin is active...
2453
						if ( in_array( $plugin, $active_plugins ) ) {
2454
							// Remove that item from being auto-activated.
2455
							unset( $modules[ $key ] );
2456
						}
2457
					}
2458
				}
2459
			}
2460
		}
2461
2462
		return $modules;
2463
	}
2464
2465
	/**
2466
	 * Extract a module's slug from its full path.
2467
	 */
2468
	public static function get_module_slug( $file ) {
2469
		return str_replace( '.php', '', basename( $file ) );
2470
	}
2471
2472
	/**
2473
	 * Generate a module's path from its slug.
2474
	 */
2475
	public static function get_module_path( $slug ) {
2476
		/**
2477
		 * Filters the path of a modules.
2478
		 *
2479
		 * @since 7.4.0
2480
		 *
2481
		 * @param array $return The absolute path to a module's root php file
2482
		 * @param string $slug The module slug
2483
		 */
2484
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2485
	}
2486
2487
	/**
2488
	 * Load module data from module file. Headers differ from WordPress
2489
	 * plugin headers to avoid them being identified as standalone
2490
	 * plugins on the WordPress plugins page.
2491
	 */
2492
	public static function get_module( $module ) {
2493
		$headers = array(
2494
			'name'                      => 'Module Name',
2495
			'description'               => 'Module Description',
2496
			'jumpstart_desc'            => 'Jumpstart Description',
2497
			'sort'                      => 'Sort Order',
2498
			'recommendation_order'      => 'Recommendation Order',
2499
			'introduced'                => 'First Introduced',
2500
			'changed'                   => 'Major Changes In',
2501
			'deactivate'                => 'Deactivate',
2502
			'free'                      => 'Free',
2503
			'requires_connection'       => 'Requires Connection',
2504
			'auto_activate'             => 'Auto Activate',
2505
			'module_tags'               => 'Module Tags',
2506
			'feature'                   => 'Feature',
2507
			'additional_search_queries' => 'Additional Search Queries',
2508
			'plan_classes'              => 'Plans',
2509
		);
2510
2511
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2512
2513
		$mod = Jetpack::get_file_data( $file, $headers );
2514
		if ( empty( $mod['name'] ) ) {
2515
			return false;
2516
		}
2517
2518
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2519
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2520
		$mod['deactivate']              = empty( $mod['deactivate'] );
2521
		$mod['free']                    = empty( $mod['free'] );
2522
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2523
2524
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2525
			$mod['auto_activate'] = 'No';
2526
		} else {
2527
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2528
		}
2529
2530
		if ( $mod['module_tags'] ) {
2531
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2532
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2533
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2534
		} else {
2535
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2536
		}
2537
2538 View Code Duplication
		if ( $mod['plan_classes'] ) {
2539
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2540
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2541
		} else {
2542
			$mod['plan_classes'] = array( 'free' );
2543
		}
2544
2545 View Code Duplication
		if ( $mod['feature'] ) {
2546
			$mod['feature'] = explode( ',', $mod['feature'] );
2547
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2548
		} else {
2549
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2550
		}
2551
2552
		/**
2553
		 * Filters the feature array on a module.
2554
		 *
2555
		 * This filter allows you to control where each module is filtered: Recommended,
2556
		 * Jumpstart, and the default "Other" listing.
2557
		 *
2558
		 * @since 3.5.0
2559
		 *
2560
		 * @param array   $mod['feature'] The areas to feature this module:
2561
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2562
		 *     'Recommended' shows on the main Jetpack admin screen.
2563
		 *     'Other' should be the default if no other value is in the array.
2564
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2565
		 * @param array   $mod All the currently assembled module data.
2566
		 */
2567
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2568
2569
		/**
2570
		 * Filter the returned data about a module.
2571
		 *
2572
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2573
		 * so please be careful.
2574
		 *
2575
		 * @since 3.6.0
2576
		 *
2577
		 * @param array   $mod    The details of the requested module.
2578
		 * @param string  $module The slug of the module, e.g. sharedaddy
2579
		 * @param string  $file   The path to the module source file.
2580
		 */
2581
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2582
	}
2583
2584
	/**
2585
	 * Like core's get_file_data implementation, but caches the result.
2586
	 */
2587
	public static function get_file_data( $file, $headers ) {
2588
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2589
		$file_name = basename( $file );
2590
2591
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2592
2593
		$file_data_option = get_transient( $cache_key );
2594
2595
		if ( false === $file_data_option ) {
2596
			$file_data_option = array();
2597
		}
2598
2599
		$key           = md5( $file_name . serialize( $headers ) );
2600
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2601
2602
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2603
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2604
			return $file_data_option[ $key ];
2605
		}
2606
2607
		$data = get_file_data( $file, $headers );
2608
2609
		$file_data_option[ $key ] = $data;
2610
2611
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2612
2613
		return $data;
2614
	}
2615
2616
2617
	/**
2618
	 * Return translated module tag.
2619
	 *
2620
	 * @param string $tag Tag as it appears in each module heading.
2621
	 *
2622
	 * @return mixed
2623
	 */
2624
	public static function translate_module_tag( $tag ) {
2625
		return jetpack_get_module_i18n_tag( $tag );
2626
	}
2627
2628
	/**
2629
	 * Get i18n strings as a JSON-encoded string
2630
	 *
2631
	 * @return string The locale as JSON
2632
	 */
2633
	public static function get_i18n_data_json() {
2634
2635
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2636
		// JSON files with the file they should be included for. This is an md5
2637
		// of '_inc/build/admin.js'.
2638
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2639
2640
		$i18n_json =
2641
				   JETPACK__PLUGIN_DIR
2642
				   . 'languages/json/jetpack-'
2643
				   . get_user_locale()
2644
				   . '-'
2645
				   . $path_md5
2646
				   . '.json';
2647
2648
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2649
			$locale_data = @file_get_contents( $i18n_json );
2650
			if ( $locale_data ) {
2651
				return $locale_data;
2652
			}
2653
		}
2654
2655
		// Return valid empty Jed locale
2656
		return '{ "locale_data": { "messages": { "": {} } } }';
2657
	}
2658
2659
	/**
2660
	 * Add locale data setup to wp-i18n
2661
	 *
2662
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2663
	 *
2664
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2665
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2666
	 *
2667
	 * This method provides a safe way to request the setup multiple times but add the script at
2668
	 * most once.
2669
	 *
2670
	 * @since 6.7.0
2671
	 *
2672
	 * @return void
2673
	 */
2674
	public static function setup_wp_i18n_locale_data() {
2675
		static $script_added = false;
2676
		if ( ! $script_added ) {
2677
			$script_added = true;
2678
			wp_add_inline_script(
2679
				'wp-i18n',
2680
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2681
			);
2682
		}
2683
	}
2684
2685
	/**
2686
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2687
	 *
2688
	 * @since 3.9.2
2689
	 *
2690
	 * @param array $modules
2691
	 *
2692
	 * @return string|void
2693
	 */
2694
	public static function get_translated_modules( $modules ) {
2695
		foreach ( $modules as $index => $module ) {
2696
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2697
			if ( isset( $module['name'] ) ) {
2698
				$modules[ $index ]['name'] = $i18n_module['name'];
2699
			}
2700
			if ( isset( $module['description'] ) ) {
2701
				$modules[ $index ]['description'] = $i18n_module['description'];
2702
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2703
			}
2704
		}
2705
		return $modules;
2706
	}
2707
2708
	/**
2709
	 * Get a list of activated modules as an array of module slugs.
2710
	 */
2711
	public static function get_active_modules() {
2712
		$active = Jetpack_Options::get_option( 'active_modules' );
2713
2714
		if ( ! is_array( $active ) ) {
2715
			$active = array();
2716
		}
2717
2718
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2719
			$active[] = 'vaultpress';
2720
		} else {
2721
			$active = array_diff( $active, array( 'vaultpress' ) );
2722
		}
2723
2724
		//If protect is active on the main site of a multisite, it should be active on all sites.
2725
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2726
			$active[] = 'protect';
2727
		}
2728
2729
		/**
2730
		 * Allow filtering of the active modules.
2731
		 *
2732
		 * Gives theme and plugin developers the power to alter the modules that
2733
		 * are activated on the fly.
2734
		 *
2735
		 * @since 5.8.0
2736
		 *
2737
		 * @param array $active Array of active module slugs.
2738
		 */
2739
		$active = apply_filters( 'jetpack_active_modules', $active );
2740
2741
		return array_unique( $active );
2742
	}
2743
2744
	/**
2745
	 * Check whether or not a Jetpack module is active.
2746
	 *
2747
	 * @param string $module The slug of a Jetpack module.
2748
	 * @return bool
2749
	 *
2750
	 * @static
2751
	 */
2752
	public static function is_module_active( $module ) {
2753
		return in_array( $module, self::get_active_modules() );
2754
	}
2755
2756
	public static function is_module( $module ) {
2757
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2758
	}
2759
2760
	/**
2761
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2762
	 *
2763
	 * @param bool $catch True to start catching, False to stop.
2764
	 *
2765
	 * @static
2766
	 */
2767
	public static function catch_errors( $catch ) {
2768
		static $display_errors, $error_reporting;
2769
2770
		if ( $catch ) {
2771
			$display_errors  = @ini_set( 'display_errors', 1 );
2772
			$error_reporting = @error_reporting( E_ALL );
2773
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2774
		} else {
2775
			@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...
2776
			@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...
2777
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2778
		}
2779
	}
2780
2781
	/**
2782
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2783
	 */
2784
	public static function catch_errors_on_shutdown() {
2785
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2786
	}
2787
2788
	/**
2789
	 * Rewrite any string to make paths easier to read.
2790
	 *
2791
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2792
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2793
	 *
2794
	 * @param $string
2795
	 * @return mixed
2796
	 */
2797
	public static function alias_directories( $string ) {
2798
		// ABSPATH has a trailing slash.
2799
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2800
		// WP_CONTENT_DIR does not have a trailing slash.
2801
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2802
2803
		return $string;
2804
	}
2805
2806
	public static function activate_default_modules(
2807
		$min_version = false,
2808
		$max_version = false,
2809
		$other_modules = array(),
2810
		$redirect = true,
2811
		$send_state_messages = true
2812
	) {
2813
		$jetpack = Jetpack::init();
2814
2815
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2816
		$modules = array_merge( $other_modules, $modules );
2817
2818
		// Look for standalone plugins and disable if active.
2819
2820
		$to_deactivate = array();
2821
		foreach ( $modules as $module ) {
2822
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2823
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2824
			}
2825
		}
2826
2827
		$deactivated = array();
2828
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2829
			list( $probable_file, $probable_title ) = $deactivate_me;
2830
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2831
				$deactivated[] = $module;
2832
			}
2833
		}
2834
2835
		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...
2836
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2837
2838
			$url = add_query_arg(
2839
				array(
2840
					'action'   => 'activate_default_modules',
2841
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2842
				),
2843
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2844
			);
2845
			wp_safe_redirect( $url );
2846
			exit;
2847
		}
2848
2849
		/**
2850
		 * Fires before default modules are activated.
2851
		 *
2852
		 * @since 1.9.0
2853
		 *
2854
		 * @param string $min_version Minimum version number required to use modules.
2855
		 * @param string $max_version Maximum version number required to use modules.
2856
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2857
		 */
2858
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2859
2860
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2861
		if ( $send_state_messages ) {
2862
			Jetpack::restate();
2863
			Jetpack::catch_errors( true );
2864
		}
2865
2866
		$active = Jetpack::get_active_modules();
2867
2868
		foreach ( $modules as $module ) {
2869
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2870
				$active[] = $module;
2871
				self::update_active_modules( $active );
2872
				continue;
2873
			}
2874
2875
			if ( $send_state_messages && in_array( $module, $active ) ) {
2876
				$module_info = Jetpack::get_module( $module );
2877 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2878
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2879
					if ( $active_state = Jetpack::state( $state ) ) {
2880
						$active_state = explode( ',', $active_state );
2881
					} else {
2882
						$active_state = array();
2883
					}
2884
					$active_state[] = $module;
2885
					Jetpack::state( $state, implode( ',', $active_state ) );
2886
				}
2887
				continue;
2888
			}
2889
2890
			$file = Jetpack::get_module_path( $module );
2891
			if ( ! file_exists( $file ) ) {
2892
				continue;
2893
			}
2894
2895
			// we'll override this later if the plugin can be included without fatal error
2896
			if ( $redirect ) {
2897
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2898
			}
2899
2900
			if ( $send_state_messages ) {
2901
				Jetpack::state( 'error', 'module_activation_failed' );
2902
				Jetpack::state( 'module', $module );
2903
			}
2904
2905
			ob_start();
2906
			require_once $file;
2907
2908
			$active[] = $module;
2909
2910 View Code Duplication
			if ( $send_state_messages ) {
2911
2912
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2913
				if ( $active_state = Jetpack::state( $state ) ) {
2914
					$active_state = explode( ',', $active_state );
2915
				} else {
2916
					$active_state = array();
2917
				}
2918
				$active_state[] = $module;
2919
				Jetpack::state( $state, implode( ',', $active_state ) );
2920
			}
2921
2922
			Jetpack::update_active_modules( $active );
2923
2924
			ob_end_clean();
2925
		}
2926
2927
		if ( $send_state_messages ) {
2928
			Jetpack::state( 'error', false );
0 ignored issues
show
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...
2929
			Jetpack::state( 'module', false );
0 ignored issues
show
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...
2930
		}
2931
2932
		Jetpack::catch_errors( false );
2933
		/**
2934
		 * Fires when default modules are activated.
2935
		 *
2936
		 * @since 1.9.0
2937
		 *
2938
		 * @param string $min_version Minimum version number required to use modules.
2939
		 * @param string $max_version Maximum version number required to use modules.
2940
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2941
		 */
2942
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2943
	}
2944
2945
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2946
		/**
2947
		 * Fires before a module is activated.
2948
		 *
2949
		 * @since 2.6.0
2950
		 *
2951
		 * @param string $module Module slug.
2952
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2953
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2954
		 */
2955
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2956
2957
		$jetpack = Jetpack::init();
2958
2959
		if ( ! strlen( $module ) )
2960
			return false;
2961
2962
		if ( ! Jetpack::is_module( $module ) )
2963
			return false;
2964
2965
		// If it's already active, then don't do it again
2966
		$active = Jetpack::get_active_modules();
2967
		foreach ( $active as $act ) {
2968
			if ( $act == $module )
2969
				return true;
2970
		}
2971
2972
		$module_data = Jetpack::get_module( $module );
2973
2974
		if ( ! Jetpack::is_active() ) {
2975
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2976
				return false;
2977
2978
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2979
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2980
				return false;
2981
		}
2982
2983
		// Check and see if the old plugin is active
2984
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2985
			// Deactivate the old plugin
2986
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2987
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2988
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2989
				Jetpack::state( 'deactivated_plugins', $module );
2990
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2991
				exit;
2992
			}
2993
		}
2994
2995
		// Protect won't work with mis-configured IPs
2996
		if ( 'protect' === $module ) {
2997
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2998
			if ( ! jetpack_protect_get_ip() ) {
2999
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3000
				return false;
3001
			}
3002
		}
3003
3004
		if ( ! Jetpack_Plan::supports( $module ) ) {
3005
			return false;
3006
		}
3007
3008
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3009
		Jetpack::state( 'module', $module );
3010
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3011
3012
		Jetpack::catch_errors( true );
3013
		ob_start();
3014
		require Jetpack::get_module_path( $module );
3015
		/** This action is documented in class.jetpack.php */
3016
		do_action( 'jetpack_activate_module', $module );
3017
		$active[] = $module;
3018
		Jetpack::update_active_modules( $active );
3019
3020
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
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...
3021
		ob_end_clean();
3022
		Jetpack::catch_errors( false );
3023
3024
		if ( $redirect ) {
3025
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3026
		}
3027
		if ( $exit ) {
3028
			exit;
3029
		}
3030
		return true;
3031
	}
3032
3033
	function activate_module_actions( $module ) {
3034
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3035
	}
3036
3037
	public static function deactivate_module( $module ) {
3038
		/**
3039
		 * Fires when a module is deactivated.
3040
		 *
3041
		 * @since 1.9.0
3042
		 *
3043
		 * @param string $module Module slug.
3044
		 */
3045
		do_action( 'jetpack_pre_deactivate_module', $module );
3046
3047
		$jetpack = Jetpack::init();
0 ignored issues
show
$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...
3048
3049
		$active = Jetpack::get_active_modules();
3050
		$new    = array_filter( array_diff( $active, (array) $module ) );
3051
3052
		return self::update_active_modules( $new );
3053
	}
3054
3055
	public static function enable_module_configurable( $module ) {
3056
		$module = Jetpack::get_module_slug( $module );
3057
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3058
	}
3059
3060
	/**
3061
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3062
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3063
	 *
3064
	 * @param string $module Module slug
3065
	 * @return string $url module configuration URL
3066
	 */
3067
	public static function module_configuration_url( $module ) {
3068
		$module = Jetpack::get_module_slug( $module );
3069
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3070
		/**
3071
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3072
		 *
3073
		 * @since 6.9.0
3074
		 *
3075
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3076
		 */
3077
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3078
3079
		return $url;
3080
	}
3081
3082
/* Installation */
3083
	public static function bail_on_activation( $message, $deactivate = true ) {
3084
?>
3085
<!doctype html>
3086
<html>
3087
<head>
3088
<meta charset="<?php bloginfo( 'charset' ); ?>">
3089
<style>
3090
* {
3091
	text-align: center;
3092
	margin: 0;
3093
	padding: 0;
3094
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3095
}
3096
p {
3097
	margin-top: 1em;
3098
	font-size: 18px;
3099
}
3100
</style>
3101
<body>
3102
<p><?php echo esc_html( $message ); ?></p>
3103
</body>
3104
</html>
3105
<?php
3106
		if ( $deactivate ) {
3107
			$plugins = get_option( 'active_plugins' );
3108
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3109
			$update  = false;
3110
			foreach ( $plugins as $i => $plugin ) {
3111
				if ( $plugin === $jetpack ) {
3112
					$plugins[$i] = false;
3113
					$update = true;
3114
				}
3115
			}
3116
3117
			if ( $update ) {
3118
				update_option( 'active_plugins', array_filter( $plugins ) );
3119
			}
3120
		}
3121
		exit;
3122
	}
3123
3124
	/**
3125
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3126
	 * @static
3127
	 */
3128
	public static function plugin_activation( $network_wide ) {
3129
		Jetpack_Options::update_option( 'activated', 1 );
3130
3131
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3132
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3133
		}
3134
3135
		if ( $network_wide )
3136
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
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...
3137
3138
		// For firing one-off events (notices) immediately after activation
3139
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3140
3141
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3142
3143
		Jetpack::plugin_initialize();
3144
	}
3145
3146
	public static function get_activation_source( $referer_url ) {
3147
3148
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3149
			return array( 'wp-cli', null );
3150
		}
3151
3152
		$referer = parse_url( $referer_url );
3153
3154
		$source_type = 'unknown';
3155
		$source_query = null;
3156
3157
		if ( ! is_array( $referer ) ) {
3158
			return array( $source_type, $source_query );
3159
		}
3160
3161
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3162
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3163
3164
		if ( isset( $referer['query'] ) ) {
3165
			parse_str( $referer['query'], $query_parts );
3166
		} else {
3167
			$query_parts = array();
3168
		}
3169
3170
		if ( $plugins_path === $referer['path'] ) {
3171
			$source_type = 'list';
3172
		} elseif ( $plugins_install_path === $referer['path'] ) {
3173
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3174
			switch( $tab ) {
3175
				case 'popular':
3176
					$source_type = 'popular';
3177
					break;
3178
				case 'recommended':
3179
					$source_type = 'recommended';
3180
					break;
3181
				case 'favorites':
3182
					$source_type = 'favorites';
3183
					break;
3184
				case 'search':
3185
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3186
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3187
					break;
3188
				default:
3189
					$source_type = 'featured';
3190
			}
3191
		}
3192
3193
		return array( $source_type, $source_query );
3194
	}
3195
3196
	/**
3197
	 * Runs before bumping version numbers up to a new version
3198
	 * @param  string $version    Version:timestamp
3199
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3200
	 * @return null              [description]
3201
	 */
3202
	public static function do_version_bump( $version, $old_version ) {
3203
		if ( ! $old_version ) { // For new sites
3204
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3205
		}
3206
	}
3207
3208
	/**
3209
	 * Sets the internal version number and activation state.
3210
	 * @static
3211
	 */
3212
	public static function plugin_initialize() {
3213
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3214
			Jetpack_Options::update_option( 'activated', 2 );
3215
		}
3216
3217 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3218
			$version = $old_version = JETPACK__VERSION . ':' . time();
3219
			/** This action is documented in class.jetpack.php */
3220
			do_action( 'updating_jetpack_version', $version, false );
3221
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3222
		}
3223
3224
		Jetpack::load_modules();
3225
3226
		Jetpack_Options::delete_option( 'do_activate' );
3227
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3228
	}
3229
3230
	/**
3231
	 * Removes all connection options
3232
	 * @static
3233
	 */
3234
	public static function plugin_deactivation( ) {
3235
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3236
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3237
			Jetpack_Network::init()->deactivate();
3238
		} else {
3239
			Jetpack::disconnect( false );
3240
			//Jetpack_Heartbeat::init()->deactivate();
3241
		}
3242
	}
3243
3244
	/**
3245
	 * Disconnects from the Jetpack servers.
3246
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3247
	 * @static
3248
	 */
3249
	public static function disconnect( $update_activated_state = true ) {
3250
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3251
		Jetpack::clean_nonces( true );
3252
3253
		// If the site is in an IDC because sync is not allowed,
3254
		// let's make sure to not disconnect the production site.
3255
		if ( ! self::validate_sync_error_idc_option() ) {
3256
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3257
			Jetpack::load_xml_rpc_client();
3258
			$xml = new Jetpack_IXR_Client();
3259
			$xml->query( 'jetpack.deregister' );
3260
		}
3261
3262
		Jetpack_Options::delete_option(
3263
			array(
3264
				'blog_token',
3265
				'user_token',
3266
				'user_tokens',
3267
				'master_user',
3268
				'time_diff',
3269
				'fallback_no_verify_ssl_certs',
3270
			)
3271
		);
3272
3273
		Jetpack_IDC::clear_all_idc_options();
3274
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3275
3276
		if ( $update_activated_state ) {
3277
			Jetpack_Options::update_option( 'activated', 4 );
3278
		}
3279
3280
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3281
			// Check then record unique disconnection if site has never been disconnected previously
3282
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3283
				$jetpack_unique_connection['disconnected'] = 1;
3284
			} else {
3285
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3286
					//track unique disconnect
3287
					$jetpack = Jetpack::init();
3288
3289
					$jetpack->stat( 'connections', 'unique-disconnect' );
3290
					$jetpack->do_stats( 'server_side' );
3291
				}
3292
				// increment number of times disconnected
3293
				$jetpack_unique_connection['disconnected'] += 1;
3294
			}
3295
3296
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3297
		}
3298
3299
		// Delete cached connected user data
3300
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3301
		delete_transient( $transient_key );
3302
3303
		// Delete all the sync related data. Since it could be taking up space.
3304
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3305
		Jetpack_Sync_Sender::get_instance()->uninstall();
3306
3307
		// Disable the Heartbeat cron
3308
		Jetpack_Heartbeat::init()->deactivate();
3309
	}
3310
3311
	/**
3312
	 * Unlinks the current user from the linked WordPress.com user
3313
	 */
3314
	public static function unlink_user( $user_id = null ) {
3315
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3316
			return false;
3317
3318
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3319
3320
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3321
			return false;
3322
3323
		if ( ! isset( $tokens[ $user_id ] ) )
3324
			return false;
3325
3326
		Jetpack::load_xml_rpc_client();
3327
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3328
		$xml->query( 'jetpack.unlink_user', $user_id );
3329
3330
		unset( $tokens[ $user_id ] );
3331
3332
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3333
3334
		/**
3335
		 * Fires after the current user has been unlinked from WordPress.com.
3336
		 *
3337
		 * @since 4.1.0
3338
		 *
3339
		 * @param int $user_id The current user's ID.
3340
		 */
3341
		do_action( 'jetpack_unlinked_user', $user_id );
3342
3343
		return true;
3344
	}
3345
3346
	/**
3347
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3348
	 */
3349
	public static function try_registration() {
3350
		// The user has agreed to the TOS at some point by now.
3351
		Jetpack_Options::update_option( 'tos_agreed', true );
3352
3353
		// Let's get some testing in beta versions and such.
3354
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3355
			// Before attempting to connect, let's make sure that the domains are viable.
3356
			$domains_to_check = array_unique( array(
3357
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3358
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3359
			) );
3360
			foreach ( $domains_to_check as $domain ) {
3361
				$result = Jetpack_Data::is_usable_domain( $domain );
3362
				if ( is_wp_error( $result ) ) {
3363
					return $result;
3364
				}
3365
			}
3366
		}
3367
3368
		$result = Jetpack::register();
3369
3370
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3371
		if ( ! $result || is_wp_error( $result ) ) {
3372
			return $result;
3373
		} else {
3374
			return true;
3375
		}
3376
	}
3377
3378
	/**
3379
	 * Tracking an internal event log. Try not to put too much chaff in here.
3380
	 *
3381
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3382
	 */
3383
	public static function log( $code, $data = null ) {
3384
		// only grab the latest 200 entries
3385
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3386
3387
		// Append our event to the log
3388
		$log_entry = array(
3389
			'time'    => time(),
3390
			'user_id' => get_current_user_id(),
3391
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3392
			'code'    => $code,
3393
		);
3394
		// Don't bother storing it unless we've got some.
3395
		if ( ! is_null( $data ) ) {
3396
			$log_entry['data'] = $data;
3397
		}
3398
		$log[] = $log_entry;
3399
3400
		// Try add_option first, to make sure it's not autoloaded.
3401
		// @todo: Add an add_option method to Jetpack_Options
3402
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3403
			Jetpack_Options::update_option( 'log', $log );
3404
		}
3405
3406
		/**
3407
		 * Fires when Jetpack logs an internal event.
3408
		 *
3409
		 * @since 3.0.0
3410
		 *
3411
		 * @param array $log_entry {
3412
		 *	Array of details about the log entry.
3413
		 *
3414
		 *	@param string time Time of the event.
3415
		 *	@param int user_id ID of the user who trigerred the event.
3416
		 *	@param int blog_id Jetpack Blog ID.
3417
		 *	@param string code Unique name for the event.
3418
		 *	@param string data Data about the event.
3419
		 * }
3420
		 */
3421
		do_action( 'jetpack_log_entry', $log_entry );
3422
	}
3423
3424
	/**
3425
	 * Get the internal event log.
3426
	 *
3427
	 * @param $event (string) - only return the specific log events
3428
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3429
	 *
3430
	 * @return array of log events || WP_Error for invalid params
3431
	 */
3432
	public static function get_log( $event = false, $num = false ) {
3433
		if ( $event && ! is_string( $event ) ) {
3434
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3435
		}
3436
3437
		if ( $num && ! is_numeric( $num ) ) {
3438
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3439
		}
3440
3441
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3442
3443
		// If nothing set - act as it did before, otherwise let's start customizing the output
3444
		if ( ! $num && ! $event ) {
3445
			return $entire_log;
3446
		} else {
3447
			$entire_log = array_reverse( $entire_log );
3448
		}
3449
3450
		$custom_log_output = array();
3451
3452
		if ( $event ) {
3453
			foreach ( $entire_log as $log_event ) {
3454
				if ( $event == $log_event[ 'code' ] ) {
3455
					$custom_log_output[] = $log_event;
3456
				}
3457
			}
3458
		} else {
3459
			$custom_log_output = $entire_log;
3460
		}
3461
3462
		if ( $num ) {
3463
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3464
		}
3465
3466
		return $custom_log_output;
3467
	}
3468
3469
	/**
3470
	 * Log modification of important settings.
3471
	 */
3472
	public static function log_settings_change( $option, $old_value, $value ) {
3473
		switch( $option ) {
3474
			case 'jetpack_sync_non_public_post_stati':
3475
				self::log( $option, $value );
3476
				break;
3477
		}
3478
	}
3479
3480
	/**
3481
	 * Return stat data for WPCOM sync
3482
	 */
3483
	public static function get_stat_data( $encode = true, $extended = true ) {
3484
		$data = Jetpack_Heartbeat::generate_stats_array();
3485
3486
		if ( $extended ) {
3487
			$additional_data = self::get_additional_stat_data();
3488
			$data = array_merge( $data, $additional_data );
3489
		}
3490
3491
		if ( $encode ) {
3492
			return json_encode( $data );
3493
		}
3494
3495
		return $data;
3496
	}
3497
3498
	/**
3499
	 * Get additional stat data to sync to WPCOM
3500
	 */
3501
	public static function get_additional_stat_data( $prefix = '' ) {
3502
		$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...
3503
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3504
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3505
		$return["{$prefix}site-count"]     = 0;
3506
3507
		if ( function_exists( 'get_blog_count' ) ) {
3508
			$return["{$prefix}site-count"] = get_blog_count();
3509
		}
3510
		return $return;
3511
	}
3512
3513
	private static function get_site_user_count() {
3514
		global $wpdb;
3515
3516
		if ( function_exists( 'wp_is_large_network' ) ) {
3517
			if ( wp_is_large_network( 'users' ) ) {
3518
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3519
			}
3520
		}
3521 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3522
			// It wasn't there, so regenerate the data and save the transient
3523
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3524
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3525
		}
3526
		return $user_count;
3527
	}
3528
3529
	/* Admin Pages */
3530
3531
	function admin_init() {
3532
		// If the plugin is not connected, display a connect message.
3533
		if (
3534
			// the plugin was auto-activated and needs its candy
3535
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3536
		||
3537
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3538
			! Jetpack_Options::get_option( 'activated' )
3539
		) {
3540
			Jetpack::plugin_initialize();
3541
		}
3542
3543
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3544
			Jetpack_Connection_Banner::init();
3545
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3546
			// Upgrade: 1.1 -> 1.1.1
3547
			// Check and see if host can verify the Jetpack servers' SSL certificate
3548
			$args = array();
3549
			Jetpack_Client::_wp_remote_request(
3550
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3551
				$args,
3552
				true
3553
			);
3554
		}
3555
3556
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3557
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3558
		}
3559
3560
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3561
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3562
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3563
3564
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3565
			// Artificially throw errors in certain whitelisted cases during plugin activation
3566
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3567
		}
3568
3569
		// Add custom column in wp-admin/users.php to show whether user is linked.
3570
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3571
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3572
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3573
	}
3574
3575
	function admin_body_class( $admin_body_class = '' ) {
3576
		$classes = explode( ' ', trim( $admin_body_class ) );
3577
3578
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3579
3580
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3581
		return " $admin_body_class ";
3582
	}
3583
3584
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3585
		return $admin_body_class . ' jetpack-pagestyles ';
3586
	}
3587
3588
	/**
3589
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3590
	 * This function artificially throws errors for such cases (whitelisted).
3591
	 *
3592
	 * @param string $plugin The activated plugin.
3593
	 */
3594
	function throw_error_on_activate_plugin( $plugin ) {
3595
		$active_modules = Jetpack::get_active_modules();
3596
3597
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3598
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3599
			$throw = false;
3600
3601
			// Try and make sure it really was the stats plugin
3602
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3603
				if ( 'stats.php' == basename( $plugin ) ) {
3604
					$throw = true;
3605
				}
3606
			} else {
3607
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3608
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3609
					$throw = true;
3610
				}
3611
			}
3612
3613
			if ( $throw ) {
3614
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3615
			}
3616
		}
3617
	}
3618
3619
	function intercept_plugin_error_scrape_init() {
3620
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3621
	}
3622
3623
	function intercept_plugin_error_scrape( $action, $result ) {
3624
		if ( ! $result ) {
3625
			return;
3626
		}
3627
3628
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3629
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3630
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3631
			}
3632
		}
3633
	}
3634
3635
	function add_remote_request_handlers() {
3636
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3637
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3638
	}
3639
3640
	function remote_request_handlers() {
3641
		$action = current_filter();
0 ignored issues
show
$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...
3642
3643
		switch ( current_filter() ) {
3644
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3645
			$response = $this->upload_handler();
3646
			break;
3647
3648
		case 'wp_ajax_nopriv_jetpack_update_file' :
3649
			$response = $this->upload_handler( true );
3650
			break;
3651
		default :
3652
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3653
			break;
3654
		}
3655
3656
		if ( ! $response ) {
3657
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3658
		}
3659
3660
		if ( is_wp_error( $response ) ) {
3661
			$status_code       = $response->get_error_data();
3662
			$error             = $response->get_error_code();
3663
			$error_description = $response->get_error_message();
3664
3665
			if ( ! is_int( $status_code ) ) {
3666
				$status_code = 400;
3667
			}
3668
3669
			status_header( $status_code );
3670
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3671
		}
3672
3673
		status_header( 200 );
3674
		if ( true === $response ) {
3675
			exit;
3676
		}
3677
3678
		die( json_encode( (object) $response ) );
3679
	}
3680
3681
	/**
3682
	 * Uploads a file gotten from the global $_FILES.
3683
	 * If `$update_media_item` is true and `post_id` is defined
3684
	 * the attachment file of the media item (gotten through of the post_id)
3685
	 * will be updated instead of add a new one.
3686
	 *
3687
	 * @param  boolean $update_media_item - update media attachment
3688
	 * @return array - An array describing the uploadind files process
3689
	 */
3690
	function upload_handler( $update_media_item = false ) {
3691
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3692
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3693
		}
3694
3695
		$user = wp_authenticate( '', '' );
3696
		if ( ! $user || is_wp_error( $user ) ) {
3697
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3698
		}
3699
3700
		wp_set_current_user( $user->ID );
3701
3702
		if ( ! current_user_can( 'upload_files' ) ) {
3703
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3704
		}
3705
3706
		if ( empty( $_FILES ) ) {
3707
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3708
		}
3709
3710
		foreach ( array_keys( $_FILES ) as $files_key ) {
3711
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3712
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3713
			}
3714
		}
3715
3716
		$media_keys = array_keys( $_FILES['media'] );
3717
3718
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3719
		if ( ! $token || is_wp_error( $token ) ) {
3720
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3721
		}
3722
3723
		$uploaded_files = array();
3724
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3725
		unset( $GLOBALS['post'] );
3726
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3727
			$file = array();
3728
			foreach ( $media_keys as $media_key ) {
3729
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3730
			}
3731
3732
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3733
3734
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3735
			if ( $hmac_provided !== $hmac_file ) {
3736
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3737
				continue;
3738
			}
3739
3740
			$_FILES['.jetpack.upload.'] = $file;
3741
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3742
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3743
				$post_id = 0;
3744
			}
3745
3746
			if ( $update_media_item ) {
3747
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3748
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3749
				}
3750
3751
				$media_array = $_FILES['media'];
3752
3753
				$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...
3754
				$file_array['type'] = $media_array['type'][0];
3755
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3756
				$file_array['error'] = $media_array['error'][0];
3757
				$file_array['size'] = $media_array['size'][0];
3758
3759
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3760
3761
				if ( is_wp_error( $edited_media_item ) ) {
3762
					return $edited_media_item;
3763
				}
3764
3765
				$response = (object) array(
3766
					'id'   => (string) $post_id,
3767
					'file' => (string) $edited_media_item->post_title,
3768
					'url'  => (string) wp_get_attachment_url( $post_id ),
3769
					'type' => (string) $edited_media_item->post_mime_type,
3770
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3771
				);
3772
3773
				return (array) array( $response );
3774
			}
3775
3776
			$attachment_id = media_handle_upload(
3777
				'.jetpack.upload.',
3778
				$post_id,
3779
				array(),
3780
				array(
3781
					'action' => 'jetpack_upload_file',
3782
				)
3783
			);
3784
3785
			if ( ! $attachment_id ) {
3786
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3787
			} elseif ( is_wp_error( $attachment_id ) ) {
3788
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3789
			} else {
3790
				$attachment = get_post( $attachment_id );
3791
				$uploaded_files[$index] = (object) array(
3792
					'id'   => (string) $attachment_id,
3793
					'file' => $attachment->post_title,
3794
					'url'  => wp_get_attachment_url( $attachment_id ),
3795
					'type' => $attachment->post_mime_type,
3796
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3797
				);
3798
				// Zip files uploads are not supported unless they are done for installation purposed
3799
				// lets delete them in case something goes wrong in this whole process
3800
				if ( 'application/zip' === $attachment->post_mime_type ) {
3801
					// Schedule a cleanup for 2 hours from now in case of failed install.
3802
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3803
				}
3804
			}
3805
		}
3806
		if ( ! is_null( $global_post ) ) {
3807
			$GLOBALS['post'] = $global_post;
3808
		}
3809
3810
		return $uploaded_files;
3811
	}
3812
3813
	/**
3814
	 * Add help to the Jetpack page
3815
	 *
3816
	 * @since Jetpack (1.2.3)
3817
	 * @return false if not the Jetpack page
3818
	 */
3819
	function admin_help() {
3820
		$current_screen = get_current_screen();
3821
3822
		// Overview
3823
		$current_screen->add_help_tab(
3824
			array(
3825
				'id'		=> 'home',
3826
				'title'		=> __( 'Home', 'jetpack' ),
3827
				'content'	=>
3828
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3829
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3830
					'<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>',
3831
			)
3832
		);
3833
3834
		// Screen Content
3835
		if ( current_user_can( 'manage_options' ) ) {
3836
			$current_screen->add_help_tab(
3837
				array(
3838
					'id'		=> 'settings',
3839
					'title'		=> __( 'Settings', 'jetpack' ),
3840
					'content'	=>
3841
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3842
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3843
						'<ol>' .
3844
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3845
							'<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>' .
3846
						'</ol>' .
3847
						'<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>'
3848
				)
3849
			);
3850
		}
3851
3852
		// Help Sidebar
3853
		$current_screen->set_help_sidebar(
3854
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3855
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3856
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3857
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3858
		);
3859
	}
3860
3861
	function admin_menu_css() {
3862
		wp_enqueue_style( 'jetpack-icons' );
3863
	}
3864
3865
	function admin_menu_order() {
3866
		return true;
3867
	}
3868
3869 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3870
		$jp_menu_order = array();
3871
3872
		foreach ( $menu_order as $index => $item ) {
3873
			if ( $item != 'jetpack' ) {
3874
				$jp_menu_order[] = $item;
3875
			}
3876
3877
			if ( $index == 0 ) {
3878
				$jp_menu_order[] = 'jetpack';
3879
			}
3880
		}
3881
3882
		return $jp_menu_order;
3883
	}
3884
3885
	function admin_banner_styles() {
3886
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3887
3888 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3889
			wp_register_style(
3890
				'jetpack-dops-style',
3891
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3892
				array(),
3893
				JETPACK__VERSION
3894
			);
3895
		}
3896
3897
		wp_enqueue_style(
3898
			'jetpack',
3899
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3900
			array( 'jetpack-dops-style' ),
3901
			 JETPACK__VERSION . '-20121016'
3902
		);
3903
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3904
		wp_style_add_data( 'jetpack', 'suffix', $min );
3905
	}
3906
3907
	function plugin_action_links( $actions ) {
3908
3909
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3910
3911
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3912
			return array_merge(
3913
				$jetpack_home,
3914
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3915
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3916
				$actions
3917
				);
3918
			}
3919
3920
		return array_merge( $jetpack_home, $actions );
3921
	}
3922
3923
	/*
3924
	 * Registration flow:
3925
	 * 1 - ::admin_page_load() action=register
3926
	 * 2 - ::try_registration()
3927
	 * 3 - ::register()
3928
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3929
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3930
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3931
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3932
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3933
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3934
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3935
	 *       jetpack_id, jetpack_secret, jetpack_public
3936
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3937
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3938
	 * 5 - user logs in with WP.com account
3939
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3940
	 *		- Jetpack_Client_Server::authorize()
3941
	 *		- Jetpack_Client_Server::get_token()
3942
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3943
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3944
	 *			- which responds with access_token, token_type, scope
3945
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3946
	 *		- Jetpack::activate_default_modules()
3947
	 *     		- Deactivates deprecated plugins
3948
	 *     		- Activates all default modules
3949
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3950
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3951
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3952
	 *     Done!
3953
	 */
3954
3955
	/**
3956
	 * Handles the page load events for the Jetpack admin page
3957
	 */
3958
	function admin_page_load() {
3959
		$error = false;
3960
3961
		// Make sure we have the right body class to hook stylings for subpages off of.
3962
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3963
3964
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3965
			// Should only be used in intermediate redirects to preserve state across redirects
3966
			Jetpack::restate();
3967
		}
3968
3969
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3970
			// @todo: Add validation against a known whitelist
3971
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3972
			// User clicked in the iframe to link their accounts
3973
			if ( ! Jetpack::is_user_connected() ) {
3974
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3975
3976
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3977
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3978
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3979
3980
				if ( isset( $_GET['notes_iframe'] ) )
3981
					$connect_url .= '&notes_iframe';
3982
				wp_redirect( $connect_url );
3983
				exit;
3984
			} else {
3985
				if ( ! isset( $_GET['calypso_env'] ) ) {
3986
					Jetpack::state( 'message', 'already_authorized' );
3987
					wp_safe_redirect( Jetpack::admin_url() );
3988
					exit;
3989
				} else {
3990
					$connect_url = $this->build_connect_url( true, false, $from );
3991
					$connect_url .= '&already_authorized=true';
3992
					wp_redirect( $connect_url );
3993
					exit;
3994
				}
3995
			}
3996
		}
3997
3998
3999
		if ( isset( $_GET['action'] ) ) {
4000
			switch ( $_GET['action'] ) {
4001
			case 'authorize':
4002
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4003
					Jetpack::state( 'message', 'already_authorized' );
4004
					wp_safe_redirect( Jetpack::admin_url() );
4005
					exit;
4006
				}
4007
				Jetpack::log( 'authorize' );
4008
				$client_server = new Jetpack_Client_Server;
4009
				$client_server->client_authorize();
4010
				exit;
4011
			case 'register' :
4012
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4013
					$error = 'cheatin';
4014
					break;
4015
				}
4016
				check_admin_referer( 'jetpack-register' );
4017
				Jetpack::log( 'register' );
4018
				Jetpack::maybe_set_version_option();
4019
				$registered = Jetpack::try_registration();
4020
				if ( is_wp_error( $registered ) ) {
4021
					$error = $registered->get_error_code();
4022
					Jetpack::state( 'error', $error );
4023
					Jetpack::state( 'error', $registered->get_error_message() );
4024
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4025
						'error_code' => $error,
4026
						'error_message' => $registered->get_error_message()
4027
					) );
4028
					break;
4029
				}
4030
4031
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4032
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4033
4034
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4035
					'from' => $from
4036
				) );
4037
4038
				$url = $this->build_connect_url( true, $redirect, $from );
4039
4040
				if ( ! empty( $_GET['onboarding'] ) ) {
4041
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4042
				}
4043
4044
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4045
					$url = add_query_arg( 'auth_approved', 'true', $url );
4046
				}
4047
4048
				wp_redirect( $url );
4049
				exit;
4050
			case 'activate' :
4051
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4052
					$error = 'cheatin';
4053
					break;
4054
				}
4055
4056
				$module = stripslashes( $_GET['module'] );
4057
				check_admin_referer( "jetpack_activate-$module" );
4058
				Jetpack::log( 'activate', $module );
4059
				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...
4060
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4061
				}
4062
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4063
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4064
				exit;
4065
			case 'activate_default_modules' :
4066
				check_admin_referer( 'activate_default_modules' );
4067
				Jetpack::log( 'activate_default_modules' );
4068
				Jetpack::restate();
4069
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4070
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4071
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4072
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4073
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4074
				exit;
4075
			case 'disconnect' :
4076
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4077
					$error = 'cheatin';
4078
					break;
4079
				}
4080
4081
				check_admin_referer( 'jetpack-disconnect' );
4082
				Jetpack::log( 'disconnect' );
4083
				Jetpack::disconnect();
4084
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4085
				exit;
4086
			case 'reconnect' :
4087
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4088
					$error = 'cheatin';
4089
					break;
4090
				}
4091
4092
				check_admin_referer( 'jetpack-reconnect' );
4093
				Jetpack::log( 'reconnect' );
4094
				$this->disconnect();
4095
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4096
				exit;
4097 View Code Duplication
			case 'deactivate' :
4098
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4099
					$error = 'cheatin';
4100
					break;
4101
				}
4102
4103
				$modules = stripslashes( $_GET['module'] );
4104
				check_admin_referer( "jetpack_deactivate-$modules" );
4105
				foreach ( explode( ',', $modules ) as $module ) {
4106
					Jetpack::log( 'deactivate', $module );
4107
					Jetpack::deactivate_module( $module );
4108
					Jetpack::state( 'message', 'module_deactivated' );
4109
				}
4110
				Jetpack::state( 'module', $modules );
4111
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4112
				exit;
4113
			case 'unlink' :
4114
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4115
				check_admin_referer( 'jetpack-unlink' );
4116
				Jetpack::log( 'unlink' );
4117
				$this->unlink_user();
4118
				Jetpack::state( 'message', 'unlinked' );
4119
				if ( 'sub-unlink' == $redirect ) {
4120
					wp_safe_redirect( admin_url() );
4121
				} else {
4122
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4123
				}
4124
				exit;
4125
			case 'onboard' :
4126
				if ( ! current_user_can( 'manage_options' ) ) {
4127
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4128
				} else {
4129
					Jetpack::create_onboarding_token();
4130
					$url = $this->build_connect_url( true );
4131
4132
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4133
						$url = add_query_arg( 'onboarding', $token, $url );
4134
					}
4135
4136
					$calypso_env = $this->get_calypso_env();
4137
					if ( ! empty( $calypso_env ) ) {
4138
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4139
					}
4140
4141
					wp_redirect( $url );
4142
					exit;
4143
				}
4144
				exit;
4145
			default:
4146
				/**
4147
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4148
				 *
4149
				 * @since 2.6.0
4150
				 *
4151
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4152
				 */
4153
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4154
			}
4155
		}
4156
4157
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4158
			self::activate_new_modules( true );
4159
		}
4160
4161
		$message_code = Jetpack::state( 'message' );
4162
		if ( Jetpack::state( 'optin-manage' ) ) {
4163
			$activated_manage = $message_code;
4164
			$message_code = 'jetpack-manage';
4165
		}
4166
4167
		switch ( $message_code ) {
4168
		case 'jetpack-manage':
4169
			$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>';
4170
			if ( $activated_manage ) {
0 ignored issues
show
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...
4171
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4172
			}
4173
			break;
4174
4175
		}
4176
4177
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4178
4179
		if ( ! empty( $deactivated_plugins ) ) {
4180
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4181
			$deactivated_titles  = array();
4182
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4183
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4184
					continue;
4185
				}
4186
4187
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4188
			}
4189
4190
			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...
4191
				if ( $this->message ) {
4192
					$this->message .= "<br /><br />\n";
4193
				}
4194
4195
				$this->message .= wp_sprintf(
4196
					_n(
4197
						'Jetpack contains the most recent version of the old %l plugin.',
4198
						'Jetpack contains the most recent versions of the old %l plugins.',
4199
						count( $deactivated_titles ),
4200
						'jetpack'
4201
					),
4202
					$deactivated_titles
4203
				);
4204
4205
				$this->message .= "<br />\n";
4206
4207
				$this->message .= _n(
4208
					'The old version has been deactivated and can be removed from your site.',
4209
					'The old versions have been deactivated and can be removed from your site.',
4210
					count( $deactivated_titles ),
4211
					'jetpack'
4212
				);
4213
			}
4214
		}
4215
4216
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4217
4218
		if ( $this->message || $this->error || $this->privacy_checks ) {
4219
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4220
		}
4221
4222
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4223
	}
4224
4225
	function admin_notices() {
4226
4227
		if ( $this->error ) {
4228
?>
4229
<div id="message" class="jetpack-message jetpack-err">
4230
	<div class="squeezer">
4231
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4232
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4233
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4234
<?php	endif; ?>
4235
	</div>
4236
</div>
4237
<?php
4238
		}
4239
4240
		if ( $this->message ) {
4241
?>
4242
<div id="message" class="jetpack-message">
4243
	<div class="squeezer">
4244
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4245
	</div>
4246
</div>
4247
<?php
4248
		}
4249
4250
		if ( $this->privacy_checks ) :
4251
			$module_names = $module_slugs = array();
4252
4253
			$privacy_checks = explode( ',', $this->privacy_checks );
4254
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4255
			foreach ( $privacy_checks as $module_slug ) {
4256
				$module = Jetpack::get_module( $module_slug );
4257
				if ( ! $module ) {
4258
					continue;
4259
				}
4260
4261
				$module_slugs[] = $module_slug;
4262
				$module_names[] = "<strong>{$module['name']}</strong>";
4263
			}
4264
4265
			$module_slugs = join( ',', $module_slugs );
4266
?>
4267
<div id="message" class="jetpack-message jetpack-err">
4268
	<div class="squeezer">
4269
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4270
		<p><?php
4271
			echo wp_kses(
4272
				wptexturize(
4273
					wp_sprintf(
4274
						_nx(
4275
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4276
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4277
							count( $privacy_checks ),
4278
							'%l = list of Jetpack module/feature names',
4279
							'jetpack'
4280
						),
4281
						$module_names
4282
					)
4283
				),
4284
				array( 'strong' => true )
4285
			);
4286
4287
			echo "\n<br />\n";
4288
4289
			echo wp_kses(
4290
				sprintf(
4291
					_nx(
4292
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4293
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4294
						count( $privacy_checks ),
4295
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4296
						'jetpack'
4297
					),
4298
					wp_nonce_url(
4299
						Jetpack::admin_url(
4300
							array(
4301
								'page'   => 'jetpack',
4302
								'action' => 'deactivate',
4303
								'module' => urlencode( $module_slugs ),
4304
							)
4305
						),
4306
						"jetpack_deactivate-$module_slugs"
4307
					),
4308
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4309
				),
4310
				array( 'a' => array( 'href' => true, 'title' => true ) )
4311
			);
4312
		?></p>
4313
	</div>
4314
</div>
4315
<?php endif;
4316
	}
4317
4318
	/**
4319
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4320
	 */
4321
	function stat( $group, $detail ) {
4322
		if ( ! isset( $this->stats[ $group ] ) )
4323
			$this->stats[ $group ] = array();
4324
		$this->stats[ $group ][] = $detail;
4325
	}
4326
4327
	/**
4328
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4329
	 */
4330
	function do_stats( $method = '' ) {
4331
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4332
			foreach ( $this->stats as $group => $stats ) {
4333
				if ( is_array( $stats ) && count( $stats ) ) {
4334
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4335
					if ( 'server_side' === $method ) {
4336
						self::do_server_side_stat( $args );
4337
					} else {
4338
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4339
					}
4340
				}
4341
				unset( $this->stats[ $group ] );
4342
			}
4343
		}
4344
	}
4345
4346
	/**
4347
	 * Runs stats code for a one-off, server-side.
4348
	 *
4349
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4350
	 *
4351
	 * @return bool If it worked.
4352
	 */
4353
	static function do_server_side_stat( $args ) {
4354
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4355
		if ( is_wp_error( $response ) )
4356
			return false;
4357
4358
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4359
			return false;
4360
4361
		return true;
4362
	}
4363
4364
	/**
4365
	 * Builds the stats url.
4366
	 *
4367
	 * @param $args array|string The arguments to append to the URL.
4368
	 *
4369
	 * @return string The URL to be pinged.
4370
	 */
4371
	static function build_stats_url( $args ) {
4372
		$defaults = array(
4373
			'v'    => 'wpcom2',
4374
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4375
		);
4376
		$args     = wp_parse_args( $args, $defaults );
4377
		/**
4378
		 * Filter the URL used as the Stats tracking pixel.
4379
		 *
4380
		 * @since 2.3.2
4381
		 *
4382
		 * @param string $url Base URL used as the Stats tracking pixel.
4383
		 */
4384
		$base_url = apply_filters(
4385
			'jetpack_stats_base_url',
4386
			'https://pixel.wp.com/g.gif'
4387
		);
4388
		$url      = add_query_arg( $args, $base_url );
4389
		return $url;
4390
	}
4391
4392
	static function translate_current_user_to_role() {
4393
		foreach ( self::$capability_translations as $role => $cap ) {
4394
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4395
				return $role;
4396
			}
4397
		}
4398
4399
		return false;
4400
	}
4401
4402
	static function translate_user_to_role( $user ) {
4403
		foreach ( self::$capability_translations as $role => $cap ) {
4404
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4405
				return $role;
4406
			}
4407
		}
4408
4409
		return false;
4410
    }
4411
4412
	static function translate_role_to_cap( $role ) {
4413
		if ( ! isset( self::$capability_translations[$role] ) ) {
4414
			return false;
4415
		}
4416
4417
		return self::$capability_translations[$role];
4418
	}
4419
4420
	static function sign_role( $role, $user_id = null ) {
4421
		if ( empty( $user_id ) ) {
4422
			$user_id = (int) get_current_user_id();
4423
		}
4424
4425
		if ( ! $user_id  ) {
4426
			return false;
4427
		}
4428
4429
		$token = Jetpack_Data::get_access_token();
4430
		if ( ! $token || is_wp_error( $token ) ) {
4431
			return false;
4432
		}
4433
4434
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4435
	}
4436
4437
4438
	/**
4439
	 * Builds a URL to the Jetpack connection auth page
4440
	 *
4441
	 * @since 3.9.5
4442
	 *
4443
	 * @param bool $raw If true, URL will not be escaped.
4444
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4445
	 *                              If string, will be a custom redirect.
4446
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4447
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4448
	 *
4449
	 * @return string Connect URL
4450
	 */
4451
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4452
		$site_id = Jetpack_Options::get_option( 'id' );
4453
		$blog_token = Jetpack_Data::get_access_token();
4454
4455
		if ( $register || ! $blog_token || ! $site_id ) {
4456
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4457
4458
			if ( ! empty( $redirect ) ) {
4459
				$url = add_query_arg(
4460
					'redirect',
4461
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4462
					$url
4463
				);
4464
			}
4465
4466
			if( is_network_admin() ) {
4467
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4468
			}
4469
		} else {
4470
4471
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4472
			// because otherwise this logic can get us in to a loop.
4473
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4474
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4475
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4476
4477
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4478
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4479
					'1.1'
4480
				);
4481
4482
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4483
4484
					// Generating a register URL instead to refresh the existing token
4485
					return $this->build_connect_url( $raw, $redirect, $from, true );
4486
				}
4487
			}
4488
4489
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4490
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4491
			}
4492
4493
			$role = self::translate_current_user_to_role();
4494
			$signed_role = self::sign_role( $role );
4495
4496
			$user = wp_get_current_user();
4497
4498
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4499
			$redirect = $redirect
4500
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4501
				: $jetpack_admin_page;
4502
4503
			if( isset( $_REQUEST['is_multisite'] ) ) {
4504
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4505
			}
4506
4507
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4508
4509
			/**
4510
			 * Filter the type of authorization.
4511
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4512
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4513
			 *
4514
			 * @since 4.3.3
4515
			 *
4516
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4517
			 */
4518
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4519
4520
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4521
4522
			$args = urlencode_deep(
4523
				array(
4524
					'response_type' => 'code',
4525
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4526
					'redirect_uri'  => add_query_arg(
4527
						array(
4528
							'action'   => 'authorize',
4529
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4530
							'redirect' => urlencode( $redirect ),
4531
						),
4532
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4533
					),
4534
					'state'         => $user->ID,
4535
					'scope'         => $signed_role,
4536
					'user_email'    => $user->user_email,
4537
					'user_login'    => $user->user_login,
4538
					'is_active'     => Jetpack::is_active(),
4539
					'jp_version'    => JETPACK__VERSION,
4540
					'auth_type'     => $auth_type,
4541
					'secret'        => $secrets['secret_1'],
4542
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4543
					'blogname'      => get_option( 'blogname' ),
4544
					'site_url'      => site_url(),
4545
					'home_url'      => home_url(),
4546
					'site_icon'     => get_site_icon_url(),
4547
					'site_lang'     => get_locale(),
4548
					'_ui'           => $tracks_identity['_ui'],
4549
					'_ut'           => $tracks_identity['_ut'],
4550
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4551
				)
4552
			);
4553
4554
			self::apply_activation_source_to_args( $args );
4555
4556
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4557
		}
4558
4559
		if ( $from ) {
4560
			$url = add_query_arg( 'from', $from, $url );
4561
		}
4562
4563
		// Ensure that class to get the affiliate code is loaded
4564
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4565
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4566
		}
4567
		// Get affiliate code and add it to the URL
4568
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4569
4570
		$calypso_env = $this->get_calypso_env();
4571
4572
		if ( ! empty( $calypso_env ) ) {
4573
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4574
		}
4575
4576
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4577
	}
4578
4579
	/**
4580
	 * Get our assumed site creation date.
4581
	 * Calculated based on the earlier date of either:
4582
	 * - Earliest admin user registration date.
4583
	 * - Earliest date of post of any post type.
4584
	 *
4585
	 * @since 7.2.0
4586
	 *
4587
	 * @return string Assumed site creation date and time.
4588
	 */
4589
	public static function get_assumed_site_creation_date() {
4590
		$earliest_registered_users = get_users( array(
4591
			'role'    => 'administrator',
4592
			'orderby' => 'user_registered',
4593
			'order'   => 'ASC',
4594
			'fields'  => array( 'user_registered' ),
4595
			'number'  => 1,
4596
		) );
4597
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4598
4599
		$earliest_posts = get_posts( array(
4600
			'posts_per_page' => 1,
4601
			'post_type'      => 'any',
4602
			'post_status'    => 'any',
4603
			'orderby'        => 'date',
4604
			'order'          => 'ASC',
4605
		) );
4606
4607
		// If there are no posts at all, we'll count only on user registration date.
4608
		if ( $earliest_posts ) {
4609
			$earliest_post_date = $earliest_posts[0]->post_date;
4610
		} else {
4611
			$earliest_post_date = PHP_INT_MAX;
4612
		}
4613
4614
		return min( $earliest_registration_date, $earliest_post_date );
4615
	}
4616
4617
	public static function apply_activation_source_to_args( &$args ) {
4618
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4619
4620
		if ( $activation_source_name ) {
4621
			$args['_as'] = urlencode( $activation_source_name );
4622
		}
4623
4624
		if ( $activation_source_keyword ) {
4625
			$args['_ak'] = urlencode( $activation_source_keyword );
4626
		}
4627
	}
4628
4629
	function build_reconnect_url( $raw = false ) {
4630
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4631
		return $raw ? $url : esc_url( $url );
4632
	}
4633
4634
	public static function admin_url( $args = null ) {
4635
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4636
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4637
		return $url;
4638
	}
4639
4640
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4641
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4642
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4643
	}
4644
4645
	function dismiss_jetpack_notice() {
4646
4647
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4648
			return;
4649
		}
4650
4651
		switch( $_GET['jetpack-notice'] ) {
4652
			case 'dismiss':
4653
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4654
4655
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4656
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4657
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4658
				}
4659
				break;
4660
			case 'jetpack-protect-multisite-opt-out':
4661
4662
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4663
					// Don't show the banner again
4664
4665
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4666
					// redirect back to the page that had the notice
4667
					if ( wp_get_referer() ) {
4668
						wp_safe_redirect( wp_get_referer() );
4669
					} else {
4670
						// Take me to Jetpack
4671
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4672
					}
4673
				}
4674
				break;
4675
		}
4676
	}
4677
4678
	public static function sort_modules( $a, $b ) {
4679
		if ( $a['sort'] == $b['sort'] )
4680
			return 0;
4681
4682
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4683
	}
4684
4685
	function ajax_recheck_ssl() {
4686
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4687
		$result = Jetpack::permit_ssl( true );
4688
		wp_send_json( array(
4689
			'enabled' => $result,
4690
			'message' => get_transient( 'jetpack_https_test_message' )
4691
		) );
4692
	}
4693
4694
/* Client API */
4695
4696
	/**
4697
	 * Returns the requested Jetpack API URL
4698
	 *
4699
	 * @return string
4700
	 */
4701
	public static function api_url( $relative_url ) {
4702
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4703
	}
4704
4705
	/**
4706
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4707
	 */
4708
	public static function fix_url_for_bad_hosts( $url ) {
4709
		if ( 0 !== strpos( $url, 'https://' ) ) {
4710
			return $url;
4711
		}
4712
4713
		switch ( JETPACK_CLIENT__HTTPS ) {
4714
			case 'ALWAYS' :
4715
				return $url;
4716
			case 'NEVER' :
4717
				return set_url_scheme( $url, 'http' );
4718
			// default : case 'AUTO' :
4719
		}
4720
4721
		// we now return the unmodified SSL URL by default, as a security precaution
4722
		return $url;
4723
	}
4724
4725
	/**
4726
	 * Create a random secret for validating onboarding payload
4727
	 *
4728
	 * @return string Secret token
4729
	 */
4730
	public static function create_onboarding_token() {
4731
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4732
			$token = wp_generate_password( 32, false );
4733
			Jetpack_Options::update_option( 'onboarding', $token );
4734
		}
4735
4736
		return $token;
4737
	}
4738
4739
	/**
4740
	 * Remove the onboarding token
4741
	 *
4742
	 * @return bool True on success, false on failure
4743
	 */
4744
	public static function invalidate_onboarding_token() {
4745
		return Jetpack_Options::delete_option( 'onboarding' );
4746
	}
4747
4748
	/**
4749
	 * Validate an onboarding token for a specific action
4750
	 *
4751
	 * @return boolean True if token/action pair is accepted, false if not
4752
	 */
4753
	public static function validate_onboarding_token_action( $token, $action ) {
4754
		// Compare tokens, bail if tokens do not match
4755
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4756
			return false;
4757
		}
4758
4759
		// List of valid actions we can take
4760
		$valid_actions = array(
4761
			'/jetpack/v4/settings',
4762
		);
4763
4764
		// Whitelist the action
4765
		if ( ! in_array( $action, $valid_actions ) ) {
4766
			return false;
4767
		}
4768
4769
		return true;
4770
	}
4771
4772
	/**
4773
	 * Checks to see if the URL is using SSL to connect with Jetpack
4774
	 *
4775
	 * @since 2.3.3
4776
	 * @return boolean
4777
	 */
4778
	public static function permit_ssl( $force_recheck = false ) {
4779
		// Do some fancy tests to see if ssl is being supported
4780
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4781
			$message = '';
4782
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4783
				$ssl = 0;
4784
			} else {
4785
				switch ( JETPACK_CLIENT__HTTPS ) {
4786
					case 'NEVER':
4787
						$ssl = 0;
4788
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4789
						break;
4790
					case 'ALWAYS':
4791
					case 'AUTO':
4792
					default:
4793
						$ssl = 1;
4794
						break;
4795
				}
4796
4797
				// If it's not 'NEVER', test to see
4798
				if ( $ssl ) {
4799
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4800
						$ssl = 0;
4801
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4802
					} else {
4803
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4804
						if ( is_wp_error( $response ) ) {
4805
							$ssl = 0;
4806
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4807
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4808
							$ssl = 0;
4809
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4810
						}
4811
					}
4812
				}
4813
			}
4814
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4815
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4816
		}
4817
4818
		return (bool) $ssl;
4819
	}
4820
4821
	/*
4822
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4823
	 */
4824
	public function alert_auto_ssl_fail() {
4825
		if ( ! current_user_can( 'manage_options' ) )
4826
			return;
4827
4828
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4829
		?>
4830
4831
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4832
			<div class="jp-banner__content">
4833
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4834
				<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>
4835
				<p>
4836
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4837
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4838
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4839
				</p>
4840
				<p>
4841
					<?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' ),
4842
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4843
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4844
				</p>
4845
			</div>
4846
		</div>
4847
		<style>
4848
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4849
		</style>
4850
		<script type="text/javascript">
4851
			jQuery( document ).ready( function( $ ) {
4852
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4853
					var $this = $( this );
4854
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4855
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4856
					e.preventDefault();
4857
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4858
					$.post( ajaxurl, data )
4859
					  .done( function( response ) {
4860
					  	if ( response.enabled ) {
4861
					  		$( '#jetpack-ssl-warning' ).hide();
4862
					  	} else {
4863
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4864
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4865
					  	}
4866
					  }.bind( $this ) );
4867
				} );
4868
			} );
4869
		</script>
4870
4871
		<?php
4872
	}
4873
4874
	/**
4875
	 * Returns the Jetpack XML-RPC API
4876
	 *
4877
	 * @return string
4878
	 */
4879
	public static function xmlrpc_api_url() {
4880
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4881
		return untrailingslashit( $base ) . '/xmlrpc.php';
4882
	}
4883
4884
	/**
4885
	 * Creates two secret tokens and the end of life timestamp for them.
4886
	 *
4887
	 * Note these tokens are unique per call, NOT static per site for connecting.
4888
	 *
4889
	 * @since 2.6
4890
	 * @return array
4891
	 */
4892
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4893
		if ( false === $user_id ) {
4894
			$user_id = get_current_user_id();
4895
		}
4896
4897
		return self::init()->connection_manager->generate_secrets( $action, $user_id, $exp );
4898
	}
4899
4900
	public static function get_secrets( $action, $user_id ) {
4901
		$secrets = self::init()->connection_manager->get_secrets( $action, $user_id );
4902
4903
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4904
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4905
		}
4906
4907
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4908
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4909
		}
4910
4911
		return $secrets;
4912
	}
4913
4914
	public static function delete_secrets( $action, $user_id ) {
4915
		return self::init()->connection_manager->delete_secrets( $action, $user_id );
4916
	}
4917
4918
	/**
4919
	 * Builds the timeout limit for queries talking with the wpcom servers.
4920
	 *
4921
	 * Based on local php max_execution_time in php.ini
4922
	 *
4923
	 * @since 2.6
4924
	 * @return int
4925
	 * @deprecated
4926
	 **/
4927
	public function get_remote_query_timeout_limit() {
4928
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4929
		return Jetpack::get_max_execution_time();
4930
	}
4931
4932
	/**
4933
	 * Builds the timeout limit for queries talking with the wpcom servers.
4934
	 *
4935
	 * Based on local php max_execution_time in php.ini
4936
	 *
4937
	 * @since 5.4
4938
	 * @return int
4939
	 **/
4940
	public static function get_max_execution_time() {
4941
		$timeout = (int) ini_get( 'max_execution_time' );
4942
4943
		// Ensure exec time set in php.ini
4944
		if ( ! $timeout ) {
4945
			$timeout = 30;
4946
		}
4947
		return $timeout;
4948
	}
4949
4950
	/**
4951
	 * Sets a minimum request timeout, and returns the current timeout
4952
	 *
4953
	 * @since 5.4
4954
	 **/
4955
	public static function set_min_time_limit( $min_timeout ) {
4956
		$timeout = self::get_max_execution_time();
4957
		if ( $timeout < $min_timeout ) {
4958
			$timeout = $min_timeout;
4959
			set_time_limit( $timeout );
4960
		}
4961
		return $timeout;
4962
	}
4963
4964
4965
	/**
4966
	 * Takes the response from the Jetpack register new site endpoint and
4967
	 * verifies it worked properly.
4968
	 *
4969
	 * @since 2.6
4970
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4971
	 **/
4972
	public function validate_remote_register_response( $response ) {
4973
	  if ( is_wp_error( $response ) ) {
4974
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4975
		}
4976
4977
		$code   = wp_remote_retrieve_response_code( $response );
4978
		$entity = wp_remote_retrieve_body( $response );
4979
		if ( $entity )
4980
			$registration_response = json_decode( $entity );
4981
		else
4982
			$registration_response = false;
4983
4984
		$code_type = intval( $code / 100 );
4985
		if ( 5 == $code_type ) {
4986
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4987
		} elseif ( 408 == $code ) {
4988
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4989
		} elseif ( ! empty( $registration_response->error ) ) {
4990
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4991
				$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' );
4992
			} else {
4993
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
4994
			}
4995
4996
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
4997
		} elseif ( 200 != $code ) {
4998
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4999
		}
5000
5001
		// Jetpack ID error block
5002
		if ( empty( $registration_response->jetpack_id ) ) {
5003
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5004
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5005
			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 );
5006
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5007
			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 );
5008
		}
5009
5010
	    return $registration_response;
5011
	}
5012
	/**
5013
	 * @return bool|WP_Error
5014
	 */
5015
	public static function register() {
5016
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5017
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5018
		$secrets = Jetpack::generate_secrets( 'register' );
5019
5020 View Code Duplication
		if (
5021
			empty( $secrets['secret_1'] ) ||
5022
			empty( $secrets['secret_2'] ) ||
5023
			empty( $secrets['exp'] )
5024
		) {
5025
			return new Jetpack_Error( 'missing_secrets' );
5026
		}
5027
5028
		// better to try (and fail) to set a higher timeout than this system
5029
		// supports than to have register fail for more users than it should
5030
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5031
5032
		$gmt_offset = get_option( 'gmt_offset' );
5033
		if ( ! $gmt_offset ) {
5034
			$gmt_offset = 0;
5035
		}
5036
5037
		$stats_options = get_option( 'stats_options' );
5038
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5039
5040
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5041
5042
		$args = array(
5043
			'method'  => 'POST',
5044
			'body'    => array(
5045
				'siteurl'         => site_url(),
5046
				'home'            => home_url(),
5047
				'gmt_offset'      => $gmt_offset,
5048
				'timezone_string' => (string) get_option( 'timezone_string' ),
5049
				'site_name'       => (string) get_option( 'blogname' ),
5050
				'secret_1'        => $secrets['secret_1'],
5051
				'secret_2'        => $secrets['secret_2'],
5052
				'site_lang'       => get_locale(),
5053
				'timeout'         => $timeout,
5054
				'stats_id'        => $stats_id,
5055
				'state'           => get_current_user_id(),
5056
				'_ui'             => $tracks_identity['_ui'],
5057
				'_ut'             => $tracks_identity['_ut'],
5058
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5059
				'jetpack_version' => JETPACK__VERSION
5060
			),
5061
			'headers' => array(
5062
				'Accept' => 'application/json',
5063
			),
5064
			'timeout' => $timeout,
5065
		);
5066
5067
		self::apply_activation_source_to_args( $args['body'] );
5068
5069
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5070
5071
		// Make sure the response is valid and does not contain any Jetpack errors
5072
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5073
		if ( is_wp_error( $registration_details ) ) {
5074
			return $registration_details;
5075
		} elseif ( ! $registration_details ) {
5076
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5077
		}
5078
5079 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5080
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5081
		}
5082
5083
		if ( isset( $registration_details->jetpack_public ) ) {
5084
			$jetpack_public = (int) $registration_details->jetpack_public;
5085
		} else {
5086
			$jetpack_public = false;
5087
		}
5088
5089
		Jetpack_Options::update_options(
5090
			array(
5091
				'id'         => (int)    $registration_details->jetpack_id,
5092
				'blog_token' => (string) $registration_details->jetpack_secret,
5093
				'public'     => $jetpack_public,
5094
			)
5095
		);
5096
5097
		/**
5098
		 * Fires when a site is registered on WordPress.com.
5099
		 *
5100
		 * @since 3.7.0
5101
		 *
5102
		 * @param int $json->jetpack_id Jetpack Blog ID.
5103
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5104
		 * @param int|bool $jetpack_public Is the site public.
5105
		 */
5106
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5107
5108
		// Initialize Jump Start for the first and only time.
5109
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5110
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5111
5112
			$jetpack = Jetpack::init();
5113
5114
			$jetpack->stat( 'jumpstart', 'unique-views' );
5115
			$jetpack->do_stats( 'server_side' );
5116
		};
5117
5118
		return true;
5119
	}
5120
5121
	/**
5122
	 * If the db version is showing something other that what we've got now, bump it to current.
5123
	 *
5124
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
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...
5125
	 */
5126
	public static function maybe_set_version_option() {
5127
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5128
		if ( JETPACK__VERSION != $version ) {
5129
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5130
5131
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5132
				/** This action is documented in class.jetpack.php */
5133
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5134
			}
5135
5136
			return true;
5137
		}
5138
		return false;
5139
	}
5140
5141
/* Client Server API */
5142
5143
	/**
5144
	 * Loads the Jetpack XML-RPC client
5145
	 */
5146
	public static function load_xml_rpc_client() {
5147
		require_once ABSPATH . WPINC . '/class-IXR.php';
5148
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5149
	}
5150
5151
	/**
5152
	 * Resets the saved authentication state in between testing requests.
5153
	 */
5154
	public function reset_saved_auth_state() {
5155
		$this->xmlrpc_verification = null;
5156
		$this->rest_authentication_status = null;
5157
	}
5158
5159
	function verify_xml_rpc_signature() {
5160
		if ( $this->xmlrpc_verification ) {
5161
			return $this->xmlrpc_verification;
5162
		}
5163
5164
		// It's not for us
5165
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5166
			return false;
5167
		}
5168
5169
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
5170
		if (
5171
			empty( $token_key )
5172
		||
5173
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5174
		) {
5175
			return false;
5176
		}
5177
5178
		if ( '0' === $user_id ) {
5179
			$token_type = 'blog';
5180
			$user_id = 0;
5181
		} else {
5182
			$token_type = 'user';
5183
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5184
				return false;
5185
			}
5186
			$user_id = (int) $user_id;
5187
5188
			$user = new WP_User( $user_id );
5189
			if ( ! $user || ! $user->exists() ) {
5190
				return false;
5191
			}
5192
		}
5193
5194
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
5195
		if ( ! $token ) {
5196
			return false;
5197
		}
5198
5199
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5200
5201
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5202
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5203
			$post_data   = $_POST;
5204
			$file_hashes = array();
5205
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5206
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5207
					continue;
5208
				}
5209
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5210
				$file_hashes[$post_data_key] = $post_data_value;
5211
			}
5212
5213
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5214
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5215
				$post_data[$post_data_key] = $post_data_value;
5216
			}
5217
5218
			ksort( $post_data );
5219
5220
			$body = http_build_query( stripslashes_deep( $post_data ) );
5221
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5222
			$body = file_get_contents( 'php://input' );
5223
		} else {
5224
			$body = null;
5225
		}
5226
5227
		$signature = $jetpack_signature->sign_current_request(
5228
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5229
		);
5230
5231
		if ( ! $signature ) {
5232
			return false;
5233
		} else if ( is_wp_error( $signature ) ) {
5234
			return $signature;
5235
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5236
			return false;
5237
		}
5238
5239
		$timestamp = (int) $_GET['timestamp'];
5240
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5241
5242
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5243
			return false;
5244
		}
5245
5246
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5247
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5248
			if ( ! empty( $_GET['onboarding'] ) ) {
5249
				$jpo = $_GET;
5250
			} else {
5251
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5252
			}
5253
5254
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5255
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5256
5257
			if (
5258
				isset( $jpo_user ) && isset( $jpo_token ) &&
5259
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5260
				isset( $_GET['rest_route'] ) &&
5261
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5262
			) {
5263
				$jpUser = get_user_by( 'email', $jpo_user );
5264
				if ( is_a( $jpUser, 'WP_User' ) ) {
5265
					wp_set_current_user( $jpUser->ID );
5266
					$user_can = is_multisite()
5267
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5268
						: current_user_can( 'manage_options' );
5269
					if ( $user_can ) {
5270
						$token_type = 'user';
5271
						$token->external_user_id = $jpUser->ID;
5272
					}
5273
				}
5274
			}
5275
		}
5276
5277
		$this->xmlrpc_verification = array(
5278
			'type'      => $token_type,
5279
			'token_key' => $token_key,
5280
			'user_id'   => $token->external_user_id,
5281
		);
5282
5283
		return $this->xmlrpc_verification;
5284
	}
5285
5286
	/**
5287
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5288
	 */
5289
	function authenticate_jetpack( $user, $username, $password ) {
5290
		if ( is_a( $user, 'WP_User' ) ) {
5291
			return $user;
5292
		}
5293
5294
		$token_details = $this->verify_xml_rpc_signature();
5295
5296
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5297
			return $user;
5298
		}
5299
5300
		if ( 'user' !== $token_details['type'] ) {
5301
			return $user;
5302
		}
5303
5304
		if ( ! $token_details['user_id'] ) {
5305
			return $user;
5306
		}
5307
5308
		nocache_headers();
5309
5310
		return new WP_User( $token_details['user_id'] );
5311
	}
5312
5313
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5314
	// Uses the existing XMLRPC request signing implementation.
5315
	function wp_rest_authenticate( $user ) {
5316
		if ( ! empty( $user ) ) {
5317
			// Another authentication method is in effect.
5318
			return $user;
5319
		}
5320
5321
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5322
			// Nothing to do for this authentication method.
5323
			return null;
5324
		}
5325
5326
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5327
			// Nothing to do for this authentication method.
5328
			return null;
5329
		}
5330
5331
		// Ensure that we always have the request body available.  At this
5332
		// point, the WP REST API code to determine the request body has not
5333
		// run yet.  That code may try to read from 'php://input' later, but
5334
		// this can only be done once per request in PHP versions prior to 5.6.
5335
		// So we will go ahead and perform this read now if needed, and save
5336
		// the request body where both the Jetpack signature verification code
5337
		// and the WP REST API code can see it.
5338
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5339
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5340
		}
5341
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5342
5343
		// Only support specific request parameters that have been tested and
5344
		// are known to work with signature verification.  A different method
5345
		// can be passed to the WP REST API via the '?_method=' parameter if
5346
		// needed.
5347
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5348
			$this->rest_authentication_status = new WP_Error(
5349
				'rest_invalid_request',
5350
				__( 'This request method is not supported.', 'jetpack' ),
5351
				array( 'status' => 400 )
5352
			);
5353
			return null;
5354
		}
5355
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5356
			$this->rest_authentication_status = new WP_Error(
5357
				'rest_invalid_request',
5358
				__( 'This request method does not support body parameters.', 'jetpack' ),
5359
				array( 'status' => 400 )
5360
			);
5361
			return null;
5362
		}
5363
5364
		$verified = $this->verify_xml_rpc_signature();
5365
5366
		if ( is_wp_error( $verified ) ) {
5367
			$this->rest_authentication_status = $verified;
5368
			return null;
5369
		}
5370
5371
		if (
5372
			$verified &&
5373
			isset( $verified['type'] ) &&
5374
			'user' === $verified['type'] &&
5375
			! empty( $verified['user_id'] )
5376
		) {
5377
			// Authentication successful.
5378
			$this->rest_authentication_status = true;
5379
			return $verified['user_id'];
5380
		}
5381
5382
		// Something else went wrong.  Probably a signature error.
5383
		$this->rest_authentication_status = new WP_Error(
5384
			'rest_invalid_signature',
5385
			__( 'The request is not signed correctly.', 'jetpack' ),
5386
			array( 'status' => 400 )
5387
		);
5388
		return null;
5389
	}
5390
5391
	/**
5392
	 * Report authentication status to the WP REST API.
5393
	 *
5394
	 * @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
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...
5395
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5396
	 */
5397
	public function wp_rest_authentication_errors( $value ) {
5398
		if ( $value !== null ) {
5399
			return $value;
5400
		}
5401
		return $this->rest_authentication_status;
5402
	}
5403
5404
	function add_nonce( $timestamp, $nonce ) {
5405
		global $wpdb;
5406
		static $nonces_used_this_request = array();
5407
5408
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5409
			return $nonces_used_this_request["$timestamp:$nonce"];
5410
		}
5411
5412
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5413
		$timestamp = (int) $timestamp;
5414
		$nonce     = esc_sql( $nonce );
5415
5416
		// Raw query so we can avoid races: add_option will also update
5417
		$show_errors = $wpdb->show_errors( false );
5418
5419
		$old_nonce = $wpdb->get_row(
5420
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5421
		);
5422
5423
		if ( is_null( $old_nonce ) ) {
5424
			$return = $wpdb->query(
5425
				$wpdb->prepare(
5426
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5427
					"jetpack_nonce_{$timestamp}_{$nonce}",
5428
					time(),
5429
					'no'
5430
				)
5431
			);
5432
		} else {
5433
			$return = false;
5434
		}
5435
5436
		$wpdb->show_errors( $show_errors );
5437
5438
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5439
5440
		return $return;
5441
	}
5442
5443
	/**
5444
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5445
	 * Capture it here so we can verify the signature later.
5446
	 */
5447
	function xmlrpc_methods( $methods ) {
5448
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5449
		return $methods;
5450
	}
5451
5452
	function public_xmlrpc_methods( $methods ) {
5453
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5454
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5455
		}
5456
		return $methods;
5457
	}
5458
5459
	function jetpack_getOptions( $args ) {
5460
		global $wp_xmlrpc_server;
5461
5462
		$wp_xmlrpc_server->escape( $args );
5463
5464
		$username	= $args[1];
5465
		$password	= $args[2];
5466
5467
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5468
			return $wp_xmlrpc_server->error;
5469
		}
5470
5471
		$options = array();
5472
		$user_data = $this->get_connected_user_data();
5473
		if ( is_array( $user_data ) ) {
5474
			$options['jetpack_user_id'] = array(
5475
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5476
				'readonly'      => true,
5477
				'value'         => $user_data['ID'],
5478
			);
5479
			$options['jetpack_user_login'] = array(
5480
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5481
				'readonly'      => true,
5482
				'value'         => $user_data['login'],
5483
			);
5484
			$options['jetpack_user_email'] = array(
5485
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5486
				'readonly'      => true,
5487
				'value'         => $user_data['email'],
5488
			);
5489
			$options['jetpack_user_site_count'] = array(
5490
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5491
				'readonly'      => true,
5492
				'value'         => $user_data['site_count'],
5493
			);
5494
		}
5495
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5496
		$args = stripslashes_deep( $args );
5497
		return $wp_xmlrpc_server->wp_getOptions( $args );
5498
	}
5499
5500
	function xmlrpc_options( $options ) {
5501
		$jetpack_client_id = false;
5502
		if ( self::is_active() ) {
5503
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5504
		}
5505
		$options['jetpack_version'] = array(
5506
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5507
				'readonly'      => true,
5508
				'value'         => JETPACK__VERSION,
5509
		);
5510
5511
		$options['jetpack_client_id'] = array(
5512
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5513
				'readonly'      => true,
5514
				'value'         => $jetpack_client_id,
5515
		);
5516
		return $options;
5517
	}
5518
5519
	public static function clean_nonces( $all = false ) {
5520
		global $wpdb;
5521
5522
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5523
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5524
5525
		if ( true !== $all ) {
5526
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5527
			$sql_args[] = time() - 3600;
5528
		}
5529
5530
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5531
5532
		$sql = $wpdb->prepare( $sql, $sql_args );
5533
5534
		for ( $i = 0; $i < 1000; $i++ ) {
5535
			if ( ! $wpdb->query( $sql ) ) {
5536
				break;
5537
			}
5538
		}
5539
	}
5540
5541
	/**
5542
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5543
	 * SET: state( $key, $value );
5544
	 * GET: $value = state( $key );
5545
	 *
5546
	 * @param string $key
0 ignored issues
show
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...
5547
	 * @param string $value
0 ignored issues
show
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...
5548
	 * @param bool $restate private
5549
	 */
5550
	public static function state( $key = null, $value = null, $restate = false ) {
5551
		static $state = array();
5552
		static $path, $domain;
5553
		if ( ! isset( $path ) ) {
5554
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5555
			$admin_url = Jetpack::admin_url();
5556
			$bits      = wp_parse_url( $admin_url );
5557
5558
			if ( is_array( $bits ) ) {
5559
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5560
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5561
			} else {
5562
				$path = $domain = null;
5563
			}
5564
		}
5565
5566
		// Extract state from cookies and delete cookies
5567
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5568
			$yum = $_COOKIE[ 'jetpackState' ];
5569
			unset( $_COOKIE[ 'jetpackState' ] );
5570
			foreach ( $yum as $k => $v ) {
5571
				if ( strlen( $v ) )
5572
					$state[ $k ] = $v;
5573
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5574
			}
5575
		}
5576
5577
		if ( $restate ) {
5578
			foreach ( $state as $k => $v ) {
5579
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5580
			}
5581
			return;
5582
		}
5583
5584
		// Get a state variable
5585
		if ( isset( $key ) && ! isset( $value ) ) {
5586
			if ( array_key_exists( $key, $state ) )
5587
				return $state[ $key ];
5588
			return null;
5589
		}
5590
5591
		// Set a state variable
5592
		if ( isset ( $key ) && isset( $value ) ) {
5593
			if( is_array( $value ) && isset( $value[0] ) ) {
5594
				$value = $value[0];
5595
			}
5596
			$state[ $key ] = $value;
5597
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5598
		}
5599
	}
5600
5601
	public static function restate() {
5602
		Jetpack::state( null, null, true );
5603
	}
5604
5605
	public static function check_privacy( $file ) {
5606
		static $is_site_publicly_accessible = null;
5607
5608
		if ( is_null( $is_site_publicly_accessible ) ) {
5609
			$is_site_publicly_accessible = false;
5610
5611
			Jetpack::load_xml_rpc_client();
5612
			$rpc = new Jetpack_IXR_Client();
5613
5614
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5615
			if ( $success ) {
5616
				$response = $rpc->getResponse();
5617
				if ( $response ) {
5618
					$is_site_publicly_accessible = true;
5619
				}
5620
			}
5621
5622
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5623
		}
5624
5625
		if ( $is_site_publicly_accessible ) {
5626
			return;
5627
		}
5628
5629
		$module_slug = self::get_module_slug( $file );
5630
5631
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5632
		if ( ! $privacy_checks ) {
5633
			$privacy_checks = $module_slug;
5634
		} else {
5635
			$privacy_checks .= ",$module_slug";
5636
		}
5637
5638
		Jetpack::state( 'privacy_checks', $privacy_checks );
5639
	}
5640
5641
	/**
5642
	 * Helper method for multicall XMLRPC.
5643
	 */
5644
	public static function xmlrpc_async_call() {
5645
		global $blog_id;
5646
		static $clients = array();
5647
5648
		$client_blog_id = is_multisite() ? $blog_id : 0;
5649
5650
		if ( ! isset( $clients[$client_blog_id] ) ) {
5651
			Jetpack::load_xml_rpc_client();
5652
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5653
			if ( function_exists( 'ignore_user_abort' ) ) {
5654
				ignore_user_abort( true );
5655
			}
5656
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5657
		}
5658
5659
		$args = func_get_args();
5660
5661
		if ( ! empty( $args[0] ) ) {
5662
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5663
		} elseif ( is_multisite() ) {
5664
			foreach ( $clients as $client_blog_id => $client ) {
5665
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5666
					continue;
5667
				}
5668
5669
				$switch_success = switch_to_blog( $client_blog_id, true );
5670
				if ( ! $switch_success ) {
5671
					continue;
5672
				}
5673
5674
				flush();
5675
				$client->query();
5676
5677
				restore_current_blog();
5678
			}
5679
		} else {
5680
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5681
				flush();
5682
				$clients[0]->query();
5683
			}
5684
		}
5685
	}
5686
5687
	public static function staticize_subdomain( $url ) {
5688
5689
		// Extract hostname from URL
5690
		$host = parse_url( $url, PHP_URL_HOST );
5691
5692
		// Explode hostname on '.'
5693
		$exploded_host = explode( '.', $host );
5694
5695
		// Retrieve the name and TLD
5696
		if ( count( $exploded_host ) > 1 ) {
5697
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5698
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5699
			// Rebuild domain excluding subdomains
5700
			$domain = $name . '.' . $tld;
5701
		} else {
5702
			$domain = $host;
5703
		}
5704
		// Array of Automattic domains
5705
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5706
5707
		// Return $url if not an Automattic domain
5708
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5709
			return $url;
5710
		}
5711
5712
		if ( is_ssl() ) {
5713
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5714
		}
5715
5716
		srand( crc32( basename( $url ) ) );
5717
		$static_counter = rand( 0, 2 );
5718
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5719
5720
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5721
	}
5722
5723
/* JSON API Authorization */
5724
5725
	/**
5726
	 * Handles the login action for Authorizing the JSON API
5727
	 */
5728
	function login_form_json_api_authorization() {
5729
		$this->verify_json_api_authorization_request();
5730
5731
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5732
5733
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5734
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5735
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5736
	}
5737
5738
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5739
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5740
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5741
			return $url;
5742
		}
5743
5744
		$parsed_url = parse_url( $url );
5745
		$url = strtok( $url, '?' );
5746
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5747
		if ( ! empty( $parsed_url['query'] ) )
5748
			$url .= "&{$parsed_url['query']}";
5749
5750
		return $url;
5751
	}
5752
5753
	// Make sure the POSTed request is handled by the same action
5754
	function preserve_action_in_login_form_for_json_api_authorization() {
5755
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5756
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5757
	}
5758
5759
	// If someone logs in to approve API access, store the Access Code in usermeta
5760
	function store_json_api_authorization_token( $user_login, $user ) {
5761
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5762
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5763
		$token = wp_generate_password( 32, false );
5764
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5765
	}
5766
5767
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5768
	function allow_wpcom_public_api_domain( $domains ) {
5769
		$domains[] = 'public-api.wordpress.com';
5770
		return $domains;
5771
	}
5772
5773
	static function is_redirect_encoded( $redirect_url ) {
5774
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5775
	}
5776
5777
	// Add all wordpress.com environments to the safe redirect whitelist
5778
	function allow_wpcom_environments( $domains ) {
5779
		$domains[] = 'wordpress.com';
5780
		$domains[] = 'wpcalypso.wordpress.com';
5781
		$domains[] = 'horizon.wordpress.com';
5782
		$domains[] = 'calypso.localhost';
5783
		return $domains;
5784
	}
5785
5786
	// Add the Access Code details to the public-api.wordpress.com redirect
5787
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5788
		return add_query_arg(
5789
			urlencode_deep(
5790
				array(
5791
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5792
					'jetpack-user-id' => (int) $user->ID,
5793
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5794
				)
5795
			),
5796
			$redirect_to
5797
		);
5798
	}
5799
5800
5801
	/**
5802
	 * Verifies the request by checking the signature
5803
	 *
5804
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5805
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5806
	 *
5807
	 * @param null|array $environment
5808
	 */
5809
	function verify_json_api_authorization_request( $environment = null ) {
5810
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5811
5812
		$environment = is_null( $environment )
5813
			? $_REQUEST
5814
			: $environment;
5815
5816
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
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...
5817
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
5818
		if ( ! $token || empty( $token->secret ) ) {
5819
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5820
		}
5821
5822
		$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' );
5823
5824
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5825
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5826
			JetpackTracking::record_user_event( 'error_double_encode' );
5827
5828
			$die_error = sprintf(
5829
				/* translators: %s is a URL */
5830
				__( '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' ),
5831
				'https://jetpack.com/support/double-encoding/'
5832
			);
5833
		}
5834
5835
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5836
5837
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5838
			$signature = $jetpack_signature->sign_request(
5839
				$environment['token'],
5840
				$environment['timestamp'],
5841
				$environment['nonce'],
5842
				'',
5843
				'GET',
5844
				$environment['jetpack_json_api_original_query'],
5845
				null,
5846
				true
5847
			);
5848
		} else {
5849
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5850
		}
5851
5852
		if ( ! $signature ) {
5853
			wp_die( $die_error );
5854
		} else if ( is_wp_error( $signature ) ) {
5855
			wp_die( $die_error );
5856
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5857
			if ( is_ssl() ) {
5858
				// 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
5859
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5860
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5861
					wp_die( $die_error );
5862
				}
5863
			} else {
5864
				wp_die( $die_error );
5865
			}
5866
		}
5867
5868
		$timestamp = (int) $environment['timestamp'];
5869
		$nonce     = stripslashes( (string) $environment['nonce'] );
5870
5871
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5872
			// De-nonce the nonce, at least for 5 minutes.
5873
			// 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)
5874
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5875
			if ( $old_nonce_time < time() - 300 ) {
5876
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5877
			}
5878
		}
5879
5880
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5881
		$data_filters = array(
5882
			'state'        => 'opaque',
5883
			'client_id'    => 'int',
5884
			'client_title' => 'string',
5885
			'client_image' => 'url',
5886
		);
5887
5888
		foreach ( $data_filters as $key => $sanitation ) {
5889
			if ( ! isset( $data->$key ) ) {
5890
				wp_die( $die_error );
5891
			}
5892
5893
			switch ( $sanitation ) {
5894
			case 'int' :
5895
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5896
				break;
5897
			case 'opaque' :
5898
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5899
				break;
5900
			case 'string' :
5901
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5902
				break;
5903
			case 'url' :
5904
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5905
				break;
5906
			}
5907
		}
5908
5909
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5910
			wp_die( $die_error );
5911
		}
5912
	}
5913
5914
	function login_message_json_api_authorization( $message ) {
5915
		return '<p class="message">' . sprintf(
5916
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5917
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5918
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5919
	}
5920
5921
	/**
5922
	 * Get $content_width, but with a <s>twist</s> filter.
5923
	 */
5924
	public static function get_content_width() {
5925
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5926
			? $GLOBALS['content_width']
5927
			: false;
5928
		/**
5929
		 * Filter the Content Width value.
5930
		 *
5931
		 * @since 2.2.3
5932
		 *
5933
		 * @param string $content_width Content Width value.
5934
		 */
5935
		return apply_filters( 'jetpack_content_width', $content_width );
5936
	}
5937
5938
	/**
5939
	 * Pings the WordPress.com Mirror Site for the specified options.
5940
	 *
5941
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5942
	 *
5943
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5944
	 */
5945
	public function get_cloud_site_options( $option_names ) {
5946
		$option_names = array_filter( (array) $option_names, 'is_string' );
5947
5948
		Jetpack::load_xml_rpc_client();
5949
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5950
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5951
		if ( $xml->isError() ) {
5952
			return array(
5953
				'error_code' => $xml->getErrorCode(),
5954
				'error_msg'  => $xml->getErrorMessage(),
5955
			);
5956
		}
5957
		$cloud_site_options = $xml->getResponse();
5958
5959
		return $cloud_site_options;
5960
	}
5961
5962
	/**
5963
	 * Checks if the site is currently in an identity crisis.
5964
	 *
5965
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5966
	 */
5967
	public static function check_identity_crisis() {
5968
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5969
			return false;
5970
		}
5971
5972
		return Jetpack_Options::get_option( 'sync_error_idc' );
5973
	}
5974
5975
	/**
5976
	 * Checks whether the home and siteurl specifically are whitelisted
5977
	 * Written so that we don't have re-check $key and $value params every time
5978
	 * we want to check if this site is whitelisted, for example in footer.php
5979
	 *
5980
	 * @since  3.8.0
5981
	 * @return bool True = already whitelisted False = not whitelisted
5982
	 */
5983
	public static function is_staging_site() {
5984
		$is_staging = false;
5985
5986
		$known_staging = array(
5987
			'urls' => array(
5988
				'#\.staging\.wpengine\.com$#i', // WP Engine
5989
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5990
				),
5991
			'constants' => array(
5992
				'IS_WPE_SNAPSHOT',      // WP Engine
5993
				'KINSTA_DEV_ENV',       // Kinsta.com
5994
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5995
				'JETPACK_STAGING_MODE', // Generic
5996
				)
5997
			);
5998
		/**
5999
		 * Filters the flags of known staging sites.
6000
		 *
6001
		 * @since 3.9.0
6002
		 *
6003
		 * @param array $known_staging {
6004
		 *     An array of arrays that each are used to check if the current site is staging.
6005
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6006
		 *     @type array $constants PHP constants of known staging/developement environments.
6007
		 *  }
6008
		 */
6009
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6010
6011
		if ( isset( $known_staging['urls'] ) ) {
6012
			foreach ( $known_staging['urls'] as $url ){
6013
				if ( preg_match( $url, site_url() ) ) {
6014
					$is_staging = true;
6015
					break;
6016
				}
6017
			}
6018
		}
6019
6020
		if ( isset( $known_staging['constants'] ) ) {
6021
			foreach ( $known_staging['constants'] as $constant ) {
6022
				if ( defined( $constant ) && constant( $constant ) ) {
6023
					$is_staging = true;
6024
				}
6025
			}
6026
		}
6027
6028
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6029
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6030
			$is_staging = true;
6031
		}
6032
6033
		/**
6034
		 * Filters is_staging_site check.
6035
		 *
6036
		 * @since 3.9.0
6037
		 *
6038
		 * @param bool $is_staging If the current site is a staging site.
6039
		 */
6040
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6041
	}
6042
6043
	/**
6044
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6045
	 *
6046
	 * @since 4.4.0
6047
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6048
	 *
6049
	 * @return bool
6050
	 */
6051
	public static function validate_sync_error_idc_option() {
6052
		$is_valid = false;
6053
6054
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6055
		if ( false === $idc_allowed ) {
6056
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6057
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6058
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6059
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6060
				$transient_duration = HOUR_IN_SECONDS;
6061
			} else {
6062
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6063
				$idc_allowed = '1';
6064
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6065
			}
6066
6067
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6068
		}
6069
6070
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6071
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6072
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6073
			$local_options = self::get_sync_error_idc_option();
6074
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6075
				$is_valid = true;
6076
			}
6077
		}
6078
6079
		/**
6080
		 * Filters whether the sync_error_idc option is valid.
6081
		 *
6082
		 * @since 4.4.0
6083
		 *
6084
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6085
		 */
6086
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6087
6088
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6089
			// Since the option exists, and did not validate, delete it
6090
			Jetpack_Options::delete_option( 'sync_error_idc' );
6091
		}
6092
6093
		return $is_valid;
6094
	}
6095
6096
	/**
6097
	 * Normalizes a url by doing three things:
6098
	 *  - Strips protocol
6099
	 *  - Strips www
6100
	 *  - Adds a trailing slash
6101
	 *
6102
	 * @since 4.4.0
6103
	 * @param string $url
6104
	 * @return WP_Error|string
6105
	 */
6106
	public static function normalize_url_protocol_agnostic( $url ) {
6107
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6108
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6109
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6110
		}
6111
6112
		// Strip www and protocols
6113
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6114
		return $url;
6115
	}
6116
6117
	/**
6118
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6119
	 *
6120
	 * @since 4.4.0
6121
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6122
	 *
6123
	 * @param array $response
6124
	 * @return array Array of the local urls, wpcom urls, and error code
6125
	 */
6126
	public static function get_sync_error_idc_option( $response = array() ) {
6127
		// Since the local options will hit the database directly, store the values
6128
		// in a transient to allow for autoloading and caching on subsequent views.
6129
		$local_options = get_transient( 'jetpack_idc_local' );
6130
		if ( false === $local_options ) {
6131
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
6132
			$local_options = array(
6133
				'home'    => Jetpack_Sync_Functions::home_url(),
6134
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6135
			);
6136
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6137
		}
6138
6139
		$options = array_merge( $local_options, $response );
6140
6141
		$returned_values = array();
6142
		foreach( $options as $key => $option ) {
6143
			if ( 'error_code' === $key ) {
6144
				$returned_values[ $key ] = $option;
6145
				continue;
6146
			}
6147
6148
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6149
				continue;
6150
			}
6151
6152
			$returned_values[ $key ] = $normalized_url;
6153
		}
6154
6155
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6156
6157
		return $returned_values;
6158
	}
6159
6160
	/**
6161
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6162
	 * If set to true, the site will be put into staging mode.
6163
	 *
6164
	 * @since 4.3.2
6165
	 * @return bool
6166
	 */
6167
	public static function sync_idc_optin() {
6168
		if ( Constants_Manager::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6169
			$default = Constants_Manager::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6170
		} else {
6171
			$default = ! Constants_Manager::is_defined( 'SUNRISE' ) && ! is_multisite();
6172
		}
6173
6174
		/**
6175
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6176
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6177
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6178
		 *
6179
		 * @since 4.3.2
6180
		 *
6181
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6182
		 */
6183
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6184
	}
6185
6186
	/**
6187
	 * Maybe Use a .min.css stylesheet, maybe not.
6188
	 *
6189
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6190
	 */
6191
	public static function maybe_min_asset( $url, $path, $plugin ) {
6192
		// Short out on things trying to find actual paths.
6193
		if ( ! $path || empty( $plugin ) ) {
6194
			return $url;
6195
		}
6196
6197
		$path = ltrim( $path, '/' );
6198
6199
		// Strip out the abspath.
6200
		$base = dirname( plugin_basename( $plugin ) );
6201
6202
		// Short out on non-Jetpack assets.
6203
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6204
			return $url;
6205
		}
6206
6207
		// File name parsing.
6208
		$file              = "{$base}/{$path}";
6209
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6210
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6211
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6212
		$extension         = array_shift( $file_name_parts_r );
6213
6214
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6215
			// Already pointing at the minified version.
6216
			if ( 'min' === $file_name_parts_r[0] ) {
6217
				return $url;
6218
			}
6219
6220
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6221
			if ( file_exists( $min_full_path ) ) {
6222
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6223
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6224
				if ( 'css' === $extension ) {
6225
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6226
					self::$min_assets[ $key ] = $path;
6227
				}
6228
			}
6229
		}
6230
6231
		return $url;
6232
	}
6233
6234
	/**
6235
	 * If the asset is minified, let's flag .min as the suffix.
6236
	 *
6237
	 * Attached to `style_loader_src` filter.
6238
	 *
6239
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
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...
6240
	 * @param string $handle The registered handle of the script in question.
6241
	 * @param string $href The url of the asset in question.
0 ignored issues
show
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...
6242
	 */
6243
	public static function set_suffix_on_min( $src, $handle ) {
6244
		if ( false === strpos( $src, '.min.css' ) ) {
6245
			return $src;
6246
		}
6247
6248
		if ( ! empty( self::$min_assets ) ) {
6249
			foreach ( self::$min_assets as $file => $path ) {
6250
				if ( false !== strpos( $src, $file ) ) {
6251
					wp_style_add_data( $handle, 'suffix', '.min' );
6252
					return $src;
6253
				}
6254
			}
6255
		}
6256
6257
		return $src;
6258
	}
6259
6260
	/**
6261
	 * Maybe inlines a stylesheet.
6262
	 *
6263
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6264
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6265
	 *
6266
	 * Attached to `style_loader_tag` filter.
6267
	 *
6268
	 * @param string $tag The tag that would link to the external asset.
6269
	 * @param string $handle The registered handle of the script in question.
6270
	 *
6271
	 * @return string
6272
	 */
6273
	public static function maybe_inline_style( $tag, $handle ) {
6274
		global $wp_styles;
6275
		$item = $wp_styles->registered[ $handle ];
6276
6277
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6278
			return $tag;
6279
		}
6280
6281
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6282
			$href = $matches[1];
6283
			// Strip off query string
6284
			if ( $pos = strpos( $href, '?' ) ) {
6285
				$href = substr( $href, 0, $pos );
6286
			}
6287
			// Strip off fragment
6288
			if ( $pos = strpos( $href, '#' ) ) {
6289
				$href = substr( $href, 0, $pos );
6290
			}
6291
		} else {
6292
			return $tag;
6293
		}
6294
6295
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6296
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6297
			return $tag;
6298
		}
6299
6300
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6301
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6302
			// And this isn't the pass that actually deals with the RTL version...
6303
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6304
				// Short out, as the RTL version will deal with it in a moment.
6305
				return $tag;
6306
			}
6307
		}
6308
6309
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6310
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6311
		if ( $css ) {
6312
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6313
			if ( empty( $item->extra['after'] ) ) {
6314
				wp_add_inline_style( $handle, $css );
6315
			} else {
6316
				array_unshift( $item->extra['after'], $css );
6317
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6318
			}
6319
		}
6320
6321
		return $tag;
6322
	}
6323
6324
	/**
6325
	 * Loads a view file from the views
6326
	 *
6327
	 * Data passed in with the $data parameter will be available in the
6328
	 * template file as $data['value']
6329
	 *
6330
	 * @param string $template - Template file to load
6331
	 * @param array $data - Any data to pass along to the template
6332
	 * @return boolean - If template file was found
6333
	 **/
6334
	public function load_view( $template, $data = array() ) {
6335
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6336
6337
		if( file_exists( $views_dir . $template ) ) {
6338
			require_once( $views_dir . $template );
6339
			return true;
6340
		}
6341
6342
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6343
		return false;
6344
	}
6345
6346
	/**
6347
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6348
	 */
6349
	public function deprecated_hooks() {
6350
		global $wp_filter;
6351
6352
		/*
6353
		 * Format:
6354
		 * deprecated_filter_name => replacement_name
6355
		 *
6356
		 * If there is no replacement, use null for replacement_name
6357
		 */
6358
		$deprecated_list = array(
6359
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6360
			'wpl_sharing_2014_1'                                     => null,
6361
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6362
			'jetpack_identity_crisis_options_to_check'               => null,
6363
			'update_option_jetpack_single_user_site'                 => null,
6364
			'audio_player_default_colors'                            => null,
6365
			'add_option_jetpack_featured_images_enabled'             => null,
6366
			'add_option_jetpack_update_details'                      => null,
6367
			'add_option_jetpack_updates'                             => null,
6368
			'add_option_jetpack_network_name'                        => null,
6369
			'add_option_jetpack_network_allow_new_registrations'     => null,
6370
			'add_option_jetpack_network_add_new_users'               => null,
6371
			'add_option_jetpack_network_site_upload_space'           => null,
6372
			'add_option_jetpack_network_upload_file_types'           => null,
6373
			'add_option_jetpack_network_enable_administration_menus' => null,
6374
			'add_option_jetpack_is_multi_site'                       => null,
6375
			'add_option_jetpack_is_main_network'                     => null,
6376
			'add_option_jetpack_main_network_site'                   => null,
6377
			'jetpack_sync_all_registered_options'                    => null,
6378
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6379
			'jetpack_is_post_mailable'                               => null,
6380
			'jetpack_seo_site_host'                                  => null,
6381
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6382
			'jetpack_holiday_snow_option_name'                       => null,
6383
			'jetpack_holiday_chance_of_snow'                         => null,
6384
			'jetpack_holiday_snow_js_url'                            => null,
6385
			'jetpack_is_holiday_snow_season'                         => null,
6386
			'jetpack_holiday_snow_option_updated'                    => null,
6387
			'jetpack_holiday_snowing'                                => null,
6388
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6389
			'jetpack_cache_plans'                                    => null,
6390
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6391
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6392
			'jetpack_enable_site_verification'                       => null,
6393
			'can_display_jetpack_manage_notice'                      => null,
6394
			// Removed in Jetpack 7.3.0
6395
			'atd_load_scripts'                                       => null,
6396
			'atd_http_post_timeout'                                  => null,
6397
			'atd_http_post_error'                                    => null,
6398
			'atd_service_domain'                                     => null,
6399
		);
6400
6401
		// This is a silly loop depth. Better way?
6402
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6403
			if ( has_action( $hook ) ) {
6404
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6405
					foreach( $values AS $hooked ) {
6406
						if ( is_callable( $hooked['function'] ) ) {
6407
							$function_name = 'an anonymous function';
6408
						} else {
6409
							$function_name = $hooked['function'];
6410
						}
6411
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6412
					}
6413
				}
6414
			}
6415
		}
6416
	}
6417
6418
	/**
6419
	 * Converts any url in a stylesheet, to the correct absolute url.
6420
	 *
6421
	 * Considerations:
6422
	 *  - Normal, relative URLs     `feh.png`
6423
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6424
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6425
	 *  - Absolute URLs             `http://domain.com/feh.png`
6426
	 *  - Domain root relative URLs `/feh.png`
6427
	 *
6428
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6429
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6430
	 *
6431
	 * @return mixed|string
6432
	 */
6433
	public static function absolutize_css_urls( $css, $css_file_url ) {
6434
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6435
		$css_dir = dirname( $css_file_url );
6436
		$p       = parse_url( $css_dir );
6437
		$domain  = sprintf(
6438
					'%1$s//%2$s%3$s%4$s',
6439
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6440
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6441
					$p['host'],
6442
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6443
				);
6444
6445
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6446
			$find = $replace = array();
6447
			foreach ( $matches as $match ) {
6448
				$url = trim( $match['path'], "'\" \t" );
6449
6450
				// If this is a data url, we don't want to mess with it.
6451
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6452
					continue;
6453
				}
6454
6455
				// If this is an absolute or protocol-agnostic url,
6456
				// we don't want to mess with it.
6457
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6458
					continue;
6459
				}
6460
6461
				switch ( substr( $url, 0, 1 ) ) {
6462
					case '/':
6463
						$absolute = $domain . $url;
6464
						break;
6465
					default:
6466
						$absolute = $css_dir . '/' . $url;
6467
				}
6468
6469
				$find[]    = $match[0];
6470
				$replace[] = sprintf( 'url("%s")', $absolute );
6471
			}
6472
			$css = str_replace( $find, $replace, $css );
6473
		}
6474
6475
		return $css;
6476
	}
6477
6478
	/**
6479
	 * This methods removes all of the registered css files on the front end
6480
	 * from Jetpack in favor of using a single file. In effect "imploding"
6481
	 * all the files into one file.
6482
	 *
6483
	 * Pros:
6484
	 * - Uses only ONE css asset connection instead of 15
6485
	 * - Saves a minimum of 56k
6486
	 * - Reduces server load
6487
	 * - Reduces time to first painted byte
6488
	 *
6489
	 * Cons:
6490
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6491
	 *		should not cause any issues with themes.
6492
	 * - Plugins/themes dequeuing styles no longer do anything. See
6493
	 *		jetpack_implode_frontend_css filter for a workaround
6494
	 *
6495
	 * For some situations developers may wish to disable css imploding and
6496
	 * instead operate in legacy mode where each file loads seperately and
6497
	 * can be edited individually or dequeued. This can be accomplished with
6498
	 * the following line:
6499
	 *
6500
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6501
	 *
6502
	 * @since 3.2
6503
	 **/
6504
	public function implode_frontend_css( $travis_test = false ) {
6505
		$do_implode = true;
6506
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6507
			$do_implode = false;
6508
		}
6509
6510
		// Do not implode CSS when the page loads via the AMP plugin.
6511
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6512
			$do_implode = false;
6513
		}
6514
6515
		/**
6516
		 * Allow CSS to be concatenated into a single jetpack.css file.
6517
		 *
6518
		 * @since 3.2.0
6519
		 *
6520
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6521
		 */
6522
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6523
6524
		// Do not use the imploded file when default behavior was altered through the filter
6525
		if ( ! $do_implode ) {
6526
			return;
6527
		}
6528
6529
		// We do not want to use the imploded file in dev mode, or if not connected
6530
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6531
			if ( ! $travis_test ) {
6532
				return;
6533
			}
6534
		}
6535
6536
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6537
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6538
			return;
6539
		}
6540
6541
		/*
6542
		 * Now we assume Jetpack is connected and able to serve the single
6543
		 * file.
6544
		 *
6545
		 * In the future there will be a check here to serve the file locally
6546
		 * or potentially from the Jetpack CDN
6547
		 *
6548
		 * For now:
6549
		 * - Enqueue a single imploded css file
6550
		 * - Zero out the style_loader_tag for the bundled ones
6551
		 * - Be happy, drink scotch
6552
		 */
6553
6554
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6555
6556
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6557
6558
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6559
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6560
	}
6561
6562
	function concat_remove_style_loader_tag( $tag, $handle ) {
6563
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6564
			$tag = '';
6565
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6566
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6567
			}
6568
		}
6569
6570
		return $tag;
6571
	}
6572
6573
	/*
6574
	 * Check the heartbeat data
6575
	 *
6576
	 * Organizes the heartbeat data by severity.  For example, if the site
6577
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6578
	 *
6579
	 * Data will be added to "caution" array, if it either:
6580
	 *  - Out of date Jetpack version
6581
	 *  - Out of date WP version
6582
	 *  - Out of date PHP version
6583
	 *
6584
	 * $return array $filtered_data
6585
	 */
6586
	public static function jetpack_check_heartbeat_data() {
6587
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6588
6589
		$good    = array();
6590
		$caution = array();
6591
		$bad     = array();
6592
6593
		foreach ( $raw_data as $stat => $value ) {
6594
6595
			// Check jetpack version
6596
			if ( 'version' == $stat ) {
6597
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6598
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6599
					continue;
6600
				}
6601
			}
6602
6603
			// Check WP version
6604
			if ( 'wp-version' == $stat ) {
6605
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6606
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6607
					continue;
6608
				}
6609
			}
6610
6611
			// Check PHP version
6612
			if ( 'php-version' == $stat ) {
6613
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6614
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6615
					continue;
6616
				}
6617
			}
6618
6619
			// Check ID crisis
6620
			if ( 'identitycrisis' == $stat ) {
6621
				if ( 'yes' == $value ) {
6622
					$bad[ $stat ] = $value;
6623
					continue;
6624
				}
6625
			}
6626
6627
			// The rest are good :)
6628
			$good[ $stat ] = $value;
6629
		}
6630
6631
		$filtered_data = array(
6632
			'good'    => $good,
6633
			'caution' => $caution,
6634
			'bad'     => $bad
6635
		);
6636
6637
		return $filtered_data;
6638
	}
6639
6640
6641
	/*
6642
	 * This method is used to organize all options that can be reset
6643
	 * without disconnecting Jetpack.
6644
	 *
6645
	 * It is used in class.jetpack-cli.php to reset options
6646
	 *
6647
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6648
	 *
6649
	 * @return array of options to delete.
6650
	 */
6651
	public static function get_jetpack_options_for_reset() {
6652
		return Jetpack_Options::get_options_for_reset();
6653
	}
6654
6655
	/*
6656
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6657
	 * so we can bring them directly to their site in calypso.
6658
	 *
6659
	 * @param string | url
6660
	 * @return string | url without the guff
6661
	 */
6662
	public static function build_raw_urls( $url ) {
6663
		$strip_http = '/.*?:\/\//i';
6664
		$url = preg_replace( $strip_http, '', $url  );
6665
		$url = str_replace( '/', '::', $url );
6666
		return $url;
6667
	}
6668
6669
	/**
6670
	 * Stores and prints out domains to prefetch for page speed optimization.
6671
	 *
6672
	 * @param mixed $new_urls
6673
	 */
6674
	public static function dns_prefetch( $new_urls = null ) {
6675
		static $prefetch_urls = array();
6676
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6677
			echo "\r\n";
6678
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6679
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6680
			}
6681
		} elseif ( ! empty( $new_urls ) ) {
6682
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6683
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6684
			}
6685
			foreach ( (array) $new_urls as $this_new_url ) {
6686
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6687
			}
6688
			$prefetch_urls = array_unique( $prefetch_urls );
6689
		}
6690
	}
6691
6692
	public function wp_dashboard_setup() {
6693
		if ( self::is_active() ) {
6694
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6695
		}
6696
6697
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6698
			$widget_title = sprintf(
6699
				wp_kses(
6700
					/* translators: Placeholder is a Jetpack logo. */
6701
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6702
					array( 'span' => array() )
6703
				),
6704
				Jetpack::get_jp_emblem( true )
6705
			);
6706
6707
			wp_add_dashboard_widget(
6708
				'jetpack_summary_widget',
6709
				$widget_title,
6710
				array( __CLASS__, 'dashboard_widget' )
6711
			);
6712
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6713
6714
			// If we're inactive and not in development mode, sort our box to the top.
6715
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6716
				global $wp_meta_boxes;
6717
6718
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6719
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6720
6721
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6722
			}
6723
		}
6724
	}
6725
6726
	/**
6727
	 * @param mixed $result Value for the user's option
0 ignored issues
show
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...
6728
	 * @return mixed
6729
	 */
6730
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6731
		if ( ! is_array( $sorted ) ) {
6732
			return $sorted;
6733
		}
6734
6735
		foreach ( $sorted as $box_context => $ids ) {
6736
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6737
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6738
				continue;
6739
			}
6740
6741
			$ids_array = explode( ',', $ids );
6742
			$key = array_search( 'dashboard_stats', $ids_array );
6743
6744
			if ( false !== $key ) {
6745
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6746
				$ids_array[ $key ] = 'jetpack_summary_widget';
6747
				$sorted[ $box_context ] = implode( ',', $ids_array );
6748
				// We've found it, stop searching, and just return.
6749
				break;
6750
			}
6751
		}
6752
6753
		return $sorted;
6754
	}
6755
6756
	public static function dashboard_widget() {
6757
		/**
6758
		 * Fires when the dashboard is loaded.
6759
		 *
6760
		 * @since 3.4.0
6761
		 */
6762
		do_action( 'jetpack_dashboard_widget' );
6763
	}
6764
6765
	public static function dashboard_widget_footer() {
6766
		?>
6767
		<footer>
6768
6769
		<div class="protect">
6770
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6771
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6772
				<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>
6773
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6774
				<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' ); ?>">
6775
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6776
				</a>
6777
			<?php else : ?>
6778
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6779
			<?php endif; ?>
6780
		</div>
6781
6782
		<div class="akismet">
6783
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6784
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6785
				<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>
6786
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6787
				<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">
6788
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6789
				</a>
6790
			<?php else : ?>
6791
				<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>
6792
			<?php endif; ?>
6793
		</div>
6794
6795
		</footer>
6796
		<?php
6797
	}
6798
6799
	/**
6800
	 * Return string containing the Jetpack logo.
6801
	 *
6802
	 * @since 3.9.0
6803
	 *
6804
	 * @param bool $logotype Should we use the full logotype (logo + text). Default to false.
6805
	 *
6806
	 * @return string
6807
	 */
6808
	public static function get_jp_emblem( $logotype = false ) {
6809
		$logo = '<path fill="#00BE28" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16c8.8,0,16-7.2,16-16S24.8,0,16,0z M15.2,18.7h-8l8-15.5V18.7z M16.8,28.8 V13.3h8L16.8,28.8z"/>';
6810
		$text = '
6811
<path d="M41.3,26.6c-0.5-0.7-0.9-1.4-1.3-2.1c2.3-1.4,3-2.5,3-4.6V8h-3V6h6v13.4C46,22.8,45,24.8,41.3,26.6z" />
6812
<path d="M65,18.4c0,1.1,0.8,1.3,1.4,1.3c0.5,0,2-0.2,2.6-0.4v2.1c-0.9,0.3-2.5,0.5-3.7,0.5c-1.5,0-3.2-0.5-3.2-3.1V12H60v-2h2.1V7.1 H65V10h4v2h-4V18.4z" />
6813
<path d="M71,10h3v1.3c1.1-0.8,1.9-1.3,3.3-1.3c2.5,0,4.5,1.8,4.5,5.6s-2.2,6.3-5.8,6.3c-0.9,0-1.3-0.1-2-0.3V28h-3V10z M76.5,12.3 c-0.8,0-1.6,0.4-2.5,1.2v5.9c0.6,0.1,0.9,0.2,1.8,0.2c2,0,3.2-1.3,3.2-3.9C79,13.4,78.1,12.3,76.5,12.3z" />
6814
<path d="M93,22h-3v-1.5c-0.9,0.7-1.9,1.5-3.5,1.5c-1.5,0-3.1-1.1-3.1-3.2c0-2.9,2.5-3.4,4.2-3.7l2.4-0.3v-0.3c0-1.5-0.5-2.3-2-2.3 c-0.7,0-2.3,0.5-3.7,1.1L84,11c1.2-0.4,3-1,4.4-1c2.7,0,4.6,1.4,4.6,4.7L93,22z M90,16.4l-2.2,0.4c-0.7,0.1-1.4,0.5-1.4,1.6 c0,0.9,0.5,1.4,1.3,1.4s1.5-0.5,2.3-1V16.4z" />
6815
<path d="M104.5,21.3c-1.1,0.4-2.2,0.6-3.5,0.6c-4.2,0-5.9-2.4-5.9-5.9c0-3.7,2.3-6,6.1-6c1.4,0,2.3,0.2,3.2,0.5V13 c-0.8-0.3-2-0.6-3.2-0.6c-1.7,0-3.2,0.9-3.2,3.6c0,2.9,1.5,3.8,3.3,3.8c0.9,0,1.9-0.2,3.2-0.7V21.3z" />
6816
<path d="M110,15.2c0.2-0.3,0.2-0.8,3.8-5.2h3.7l-4.6,5.7l5,6.3h-3.7l-4.2-5.8V22h-3V6h3V15.2z" />
6817
<path d="M58.5,21.3c-1.5,0.5-2.7,0.6-4.2,0.6c-3.6,0-5.8-1.8-5.8-6c0-3.1,1.9-5.9,5.5-5.9s4.9,2.5,4.9,4.9c0,0.8,0,1.5-0.1,2h-7.3 c0.1,2.5,1.5,2.8,3.6,2.8c1.1,0,2.2-0.3,3.4-0.7C58.5,19,58.5,21.3,58.5,21.3z M56,15c0-1.4-0.5-2.9-2-2.9c-1.4,0-2.3,1.3-2.4,2.9 C51.6,15,56,15,56,15z" />
6818
		';
6819
6820
		return sprintf(
6821
			'<svg id="jetpack-logo__icon" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 %1$s 32">%2$s</svg>',
6822
			( true === $logotype ? '118' : '32' ),
6823
			( true === $logotype ? $logo . $text : $logo )
6824
		);
6825
	}
6826
6827
	/*
6828
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6829
	 */
6830
	function jetpack_icon_user_connected( $columns ) {
6831
		$columns['user_jetpack'] = '';
6832
		return $columns;
6833
	}
6834
6835
	/*
6836
	 * Show Jetpack icon if the user is linked.
6837
	 */
6838
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6839
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6840
			$emblem_html = sprintf(
6841
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6842
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6843
				Jetpack::get_jp_emblem()
6844
			);
6845
			return $emblem_html;
6846
		}
6847
6848
		return $val;
6849
	}
6850
6851
	/*
6852
	 * Style the Jetpack user column
6853
	 */
6854
	function jetpack_user_col_style() {
6855
		global $current_screen;
6856
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6857
			<style>
6858
				.fixed .column-user_jetpack {
6859
					width: 21px;
6860
				}
6861
				.jp-emblem-user-admin svg {
6862
					width: 20px;
6863
					height: 20px;
6864
				}
6865
				.jp-emblem-user-admin path {
6866
					fill: #00BE28;
6867
				}
6868
			</style>
6869
		<?php }
6870
	}
6871
6872
	/**
6873
	 * Checks if Akismet is active and working.
6874
	 *
6875
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6876
	 * that implied usage of methods present since more recent version.
6877
	 * See https://github.com/Automattic/jetpack/pull/9585
6878
	 *
6879
	 * @since  5.1.0
6880
	 *
6881
	 * @return bool True = Akismet available. False = Aksimet not available.
6882
	 */
6883
	public static function is_akismet_active() {
6884
		static $status = null;
6885
6886
		if ( ! is_null( $status ) ) {
6887
			return $status;
6888
		}
6889
6890
		// Check if a modern version of Akismet is active.
6891
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6892
			$status = false;
6893
			return $status;
6894
		}
6895
6896
		// Make sure there is a key known to Akismet at all before verifying key.
6897
		$akismet_key = Akismet::get_api_key();
6898
		if ( ! $akismet_key ) {
6899
			$status = false;
6900
			return $status;
6901
		}
6902
6903
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6904
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6905
6906
		// 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.
6907
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6908
		// We cache the result of the Akismet key verification for ten minutes.
6909
		if ( ! $akismet_key_state || $recheck ) {
6910
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6911
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6912
		}
6913
6914
		$status = 'valid' === $akismet_key_state;
6915
6916
		return $status;
6917
	}
6918
6919
	/**
6920
	 * Checks if one or more function names is in debug_backtrace
6921
	 *
6922
	 * @param $names Mixed string name of function or array of string names of functions
6923
	 *
6924
	 * @return bool
6925
	 */
6926
	public static function is_function_in_backtrace( $names ) {
6927
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6928
		if ( ! is_array( $names ) ) {
6929
			$names = array( $names );
6930
		}
6931
		$names_as_keys = array_flip( $names );
6932
6933
		//Do check in constant O(1) time for PHP5.5+
6934
		if ( function_exists( 'array_column' ) ) {
6935
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6936
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6937
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6938
			return ! empty ( $intersection );
6939
		}
6940
6941
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6942
		foreach ( $backtrace as $call ) {
6943
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6944
				return true;
6945
			}
6946
		}
6947
		return false;
6948
	}
6949
6950
	/**
6951
	 * Given a minified path, and a non-minified path, will return
6952
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6953
	 *
6954
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6955
	 * root Jetpack directory.
6956
	 *
6957
	 * @since 5.6.0
6958
	 *
6959
	 * @param string $min_path
6960
	 * @param string $non_min_path
6961
	 * @return string The URL to the file
6962
	 */
6963
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6964
		$path = ( Constants_Manager::is_defined( 'SCRIPT_DEBUG' ) && Constants_Manager::get_constant( 'SCRIPT_DEBUG' ) )
6965
			? $non_min_path
6966
			: $min_path;
6967
6968
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6969
	}
6970
6971
	/**
6972
	 * Checks for whether Jetpack Backup & Scan is enabled.
6973
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6974
	 * @return bool|int|mixed
6975
	 */
6976
	public static function is_rewind_enabled() {
6977
		if ( ! Jetpack::is_active() ) {
6978
			return false;
6979
		}
6980
6981
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6982
		if ( false === $rewind_enabled ) {
6983
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6984
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6985
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6986
				&& ! empty( $rewind_data['state'] )
6987
				&& 'active' === $rewind_data['state'] )
6988
				? 1
6989
				: 0;
6990
6991
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6992
		}
6993
		return $rewind_enabled;
6994
	}
6995
6996
	/**
6997
	 * Return Calypso environment value; used for developing Jetpack and pairing
6998
	 * it with different Calypso enrionments, such as localhost.
6999
	 *
7000
	 * @since 7.4.0
7001
	 *
7002
	 * @return string Calypso environment
7003
	 */
7004
	public static function get_calypso_env() {
7005
		if ( isset( $_GET['calypso_env'] ) ) {
7006
			return sanitize_key( $_GET['calypso_env'] );
7007
		}
7008
7009
		if ( getenv( 'CALYPSO_ENV' ) ) {
7010
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7011
		}
7012
7013
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7014
			return sanitize_key( CALYPSO_ENV );
7015
		}
7016
7017
		return '';
7018
	}
7019
7020
	/**
7021
	 * Checks whether or not TOS has been agreed upon.
7022
	 * Will return true if a user has clicked to register, or is already connected.
7023
	 */
7024
	public static function jetpack_tos_agreed() {
7025
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7026
	}
7027
7028
	/**
7029
	 * Handles activating default modules as well general cleanup for the new connection.
7030
	 *
7031
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7032
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7033
	 * @param boolean $send_state_messages          Whether to send state messages.
7034
	 * @return void
7035
	 */
7036
	public static function handle_post_authorization_actions(
7037
		$activate_sso = false,
7038
		$redirect_on_activation_error = false,
7039
		$send_state_messages = true
7040
	) {
7041
		$other_modules = $activate_sso
7042
			? array( 'sso' )
7043
			: array();
7044
7045
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7046
			Jetpack::delete_active_modules();
7047
7048
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
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...
7049
		} else {
7050
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7051
		}
7052
7053
		// Since this is a fresh connection, be sure to clear out IDC options
7054
		Jetpack_IDC::clear_all_idc_options();
7055
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7056
7057
		// Start nonce cleaner
7058
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7059
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7060
7061
		if ( $send_state_messages ) {
7062
			Jetpack::state( 'message', 'authorized' );
7063
		}
7064
	}
7065
7066
	/**
7067
	 * Returns a boolean for whether backups UI should be displayed or not.
7068
	 *
7069
	 * @return bool Should backups UI be displayed?
7070
	 */
7071
	public static function show_backups_ui() {
7072
		/**
7073
		 * Whether UI for backups should be displayed.
7074
		 *
7075
		 * @since 6.5.0
7076
		 *
7077
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7078
		 */
7079
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7080
	}
7081
7082
	/*
7083
	 * Deprecated manage functions
7084
	 */
7085
	function prepare_manage_jetpack_notice() {
7086
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7087
	}
7088
	function manage_activate_screen() {
7089
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7090
	}
7091
	function admin_jetpack_manage_notice() {
7092
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7093
	}
7094
	function opt_out_jetpack_manage_url() {
7095
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7096
	}
7097
	function opt_in_jetpack_manage_url() {
7098
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7099
	}
7100
	function opt_in_jetpack_manage_notice() {
7101
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7102
	}
7103
	function can_display_jetpack_manage_notice() {
7104
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7105
	}
7106
7107
	/**
7108
	 * Clean leftoveruser meta.
7109
	 *
7110
	 * Delete Jetpack-related user meta when it is no longer needed.
7111
	 *
7112
	 * @since 7.3.0
7113
	 *
7114
	 * @param int $user_id User ID being updated.
7115
	 */
7116
	public static function user_meta_cleanup( $user_id ) {
7117
		$meta_keys = array(
7118
			// AtD removed from Jetpack 7.3
7119
			'AtD_options',
7120
			'AtD_check_when',
7121
			'AtD_guess_lang',
7122
			'AtD_ignored_phrases',
7123
		);
7124
7125
		foreach ( $meta_keys as $meta_key ) {
7126
			if ( get_user_meta( $user_id, $meta_key ) ) {
7127
				delete_user_meta( $user_id, $meta_key );
7128
			}
7129
		}
7130
	}
7131
}
7132