Completed
Push — update/centralise-tracking ( 6855e5 )
by
unknown
167:14 queued 160:12
created

Jetpack::featured_images_enabled()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
5
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
6
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
7
use Automattic\Jetpack\Constants;
8
use Automattic\Jetpack\Tracking;
9
10
/*
11
Options:
12
jetpack_options (array)
13
	An array of options.
14
	@see Jetpack_Options::get_option_names()
15
16
jetpack_register (string)
17
	Temporary verification secrets.
18
19
jetpack_activated (int)
20
	1: the plugin was activated normally
21
	2: the plugin was activated on this site because of a network-wide activation
22
	3: the plugin was auto-installed
23
	4: the plugin was manually disconnected (but is still installed)
24
25
jetpack_active_modules (array)
26
	Array of active module slugs.
27
28
jetpack_do_activate (bool)
29
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
30
*/
31
32
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
33
34
class Jetpack {
35
	public $xmlrpc_server = null;
36
37
	private $xmlrpc_verification = null;
38
	private $rest_authentication_status = null;
39
40
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
41
42
	private $tracking;
43
44
	/**
45
	 * @var array The handles of styles that are concatenated into jetpack.css.
46
	 *
47
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
48
	 */
49
	public $concatenated_style_handles = array(
50
		'jetpack-carousel',
51
		'grunion.css',
52
		'the-neverending-homepage',
53
		'jetpack_likes',
54
		'jetpack_related-posts',
55
		'sharedaddy',
56
		'jetpack-slideshow',
57
		'presentations',
58
		'quiz',
59
		'jetpack-subscriptions',
60
		'jetpack-responsive-videos-style',
61
		'jetpack-social-menu',
62
		'tiled-gallery',
63
		'jetpack_display_posts_widget',
64
		'gravatar-profile-widget',
65
		'goodreads-widget',
66
		'jetpack_social_media_icons_widget',
67
		'jetpack-top-posts-widget',
68
		'jetpack_image_widget',
69
		'jetpack-my-community-widget',
70
		'jetpack-authors-widget',
71
		'wordads',
72
		'eu-cookie-law-style',
73
		'flickr-widget-style',
74
		'jetpack-search-widget',
75
		'jetpack-simple-payments-widget-style',
76
		'jetpack-widget-social-icons-styles',
77
	);
78
79
	/**
80
	 * Contains all assets that have had their URL rewritten to minified versions.
81
	 *
82
	 * @var array
83
	 */
84
	static $min_assets = array();
85
86
	public $plugins_to_deactivate = array(
87
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
88
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
89
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
90
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
91
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
92
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
93
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
94
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
95
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
96
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
97
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
98
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
99
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
100
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
101
	);
102
103
	static $capability_translations = array(
104
		'administrator' => 'manage_options',
105
		'editor'        => 'edit_others_posts',
106
		'author'        => 'publish_posts',
107
		'contributor'   => 'edit_posts',
108
		'subscriber'    => 'read',
109
	);
110
111
	/**
112
	 * Map of modules that have conflicts with plugins and should not be auto-activated
113
	 * if the plugins are active.  Used by filter_default_modules
114
	 *
115
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
116
	 * change `module-slug` and add this to your plugin:
117
	 *
118
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
119
	 * function my_jetpack_get_default_modules( $modules ) {
120
	 *     return array_diff( $modules, array( 'module-slug' ) );
121
	 * }
122
	 *
123
	 * @var array
124
	 */
125
	private $conflicting_plugins = array(
126
		'comments'          => array(
127
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
128
			'Disqus'                               => 'disqus-comment-system/disqus.php',
129
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
130
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
131
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
132
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
133
		),
134
		'comment-likes' => array(
135
			'Epoch'                                => 'epoch/plugincore.php',
136
		),
137
		'contact-form'      => array(
138
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
139
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
140
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
141
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
142
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
143
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
144
		),
145
		'minileven'         => array(
146
			'WPtouch'                              => 'wptouch/wptouch.php',
147
		),
148
		'latex'             => array(
149
			'LaTeX for WordPress'                  => 'latex/latex.php',
150
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
151
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
152
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
153
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
154
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
155
		),
156
		'protect'           => array(
157
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
158
			'Captcha'                              => 'captcha/captcha.php',
159
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
160
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
161
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
162
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
163
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
164
			'Security-protection'                  => 'security-protection/security-protection.php',
165
			'Login Security'                       => 'login-security/login-security.php',
166
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
167
			'Wordfence Security'                   => 'wordfence/wordfence.php',
168
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
169
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
170
		),
171
		'random-redirect'   => array(
172
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
173
		),
174
		'related-posts'     => array(
175
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
176
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
177
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
178
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
179
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
180
			'outbrain'                             => 'outbrain/outbrain.php',
181
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
182
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
183
		),
184
		'sharedaddy'        => array(
185
			'AddThis'                              => 'addthis/addthis_social_widget.php',
186
			'Add To Any'                           => 'add-to-any/add-to-any.php',
187
			'ShareThis'                            => 'share-this/sharethis.php',
188
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
189
		),
190
		'seo-tools' => array(
191
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
192
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
193
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
194
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
195
			'The SEO Framework'                    => 'autodescription/autodescription.php',
196
		),
197
		'verification-tools' => array(
198
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
199
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
200
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
201
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
202
			'The SEO Framework'                    => 'autodescription/autodescription.php',
203
		),
204
		'widget-visibility' => array(
205
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
206
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
207
		),
208
		'sitemaps' => array(
209
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
210
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
211
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
212
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
213
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
214
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
215
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
216
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
217
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
218
			'The SEO Framework'                    => 'autodescription/autodescription.php',
219
			'Sitemap'                              => 'sitemap/sitemap.php',
220
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
221
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
222
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
223
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
224
		),
225
		'lazy-images' => array(
226
			'Lazy Load'              => 'lazy-load/lazy-load.php',
227
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
228
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
229
		),
230
	);
231
232
	/**
233
	 * Plugins for which we turn off our Facebook OG Tags implementation.
234
	 *
235
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
236
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
237
	 *
238
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
239
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
240
	 */
241
	private $open_graph_conflicting_plugins = array(
242
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
243
		                                                         // 2 Click Social Media Buttons
244
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
245
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
246
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
247
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
248
		                                                         // Open Graph Meta Tags by Heateor
249
		'facebook/facebook.php',                                 // Facebook (official plugin)
250
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
251
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
252
		                                                         // Facebook Featured Image & OG Meta Tags
253
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
254
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
255
		                                                         // Facebook Open Graph Meta Tags for WordPress
256
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
257
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
258
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
259
		                                                         // Fedmich's Facebook Open Graph Meta
260
		'network-publisher/networkpub.php',                      // Network Publisher
261
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
262
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
263
		                                                         // NextScripts SNAP
264
		'og-tags/og-tags.php',                                   // OG Tags
265
		'opengraph/opengraph.php',                               // Open Graph
266
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
267
		                                                         // Open Graph Protocol Framework
268
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
269
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
270
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
271
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
272
		'sharepress/sharepress.php',                             // SharePress
273
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
274
		'social-discussions/social-discussions.php',             // Social Discussions
275
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
276
		'socialize/socialize.php',                               // Socialize
277
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
278
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
279
		                                                         // Tweet, Like, Google +1 and Share
280
		'wordbooker/wordbooker.php',                             // Wordbooker
281
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
282
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
283
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
284
		                                                         // WP Facebook Like Send & Open Graph Meta
285
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
286
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
287
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
288
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
289
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
290
	);
291
292
	/**
293
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
294
	 */
295
	private $twitter_cards_conflicting_plugins = array(
296
	//	'twitter/twitter.php',                       // The official one handles this on its own.
297
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
298
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
299
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
300
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
301
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
302
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
303
		'twitter-cards/twitter-cards.php',           // Twitter Cards
304
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
305
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
306
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
307
	);
308
309
	/**
310
	 * Message to display in admin_notice
311
	 * @var string
312
	 */
313
	public $message = '';
314
315
	/**
316
	 * Error to display in admin_notice
317
	 * @var string
318
	 */
319
	public $error = '';
320
321
	/**
322
	 * Modules that need more privacy description.
323
	 * @var string
324
	 */
325
	public $privacy_checks = '';
326
327
	/**
328
	 * Stats to record once the page loads
329
	 *
330
	 * @var array
331
	 */
332
	public $stats = array();
333
334
	/**
335
	 * Jetpack_Sync object
336
	 */
337
	public $sync;
338
339
	/**
340
	 * Verified data for JSON authorization request
341
	 */
342
	public $json_api_authorization_request = array();
343
344
	/**
345
	 * @var \Automattic\Jetpack\Connection\Manager
346
	 */
347
	protected $connection_manager;
348
349
	/**
350
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
351
	 */
352
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
353
354
	/**
355
	 * Holds the singleton instance of this class
356
	 * @since 2.3.3
357
	 * @var Jetpack
358
	 */
359
	static $instance = false;
360
361
	/**
362
	 * Singleton
363
	 * @static
364
	 */
365
	public static function init() {
366
		if ( ! self::$instance ) {
367
			self::$instance = new Jetpack;
368
369
			self::$instance->plugin_upgrade();
370
		}
371
372
		return self::$instance;
373
	}
374
375
	/**
376
	 * Must never be called statically
377
	 */
378
	function plugin_upgrade() {
379
		if ( Jetpack::is_active() ) {
380
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
381
			if ( JETPACK__VERSION != $version ) {
382
				// Prevent multiple upgrades at once - only a single process should trigger
383
				// an upgrade to avoid stampedes
384
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
385
					return;
386
				}
387
388
				// Set a short lock to prevent multiple instances of the upgrade
389
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
390
391
				// check which active modules actually exist and remove others from active_modules list
392
				$unfiltered_modules = Jetpack::get_active_modules();
393
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
394
				if ( array_diff( $unfiltered_modules, $modules ) ) {
395
					Jetpack::update_active_modules( $modules );
396
				}
397
398
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
399
400
				// Upgrade to 4.3.0
401
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
402
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
403
				}
404
405
				// Make sure Markdown for posts gets turned back on
406
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
407
					update_option( 'wpcom_publish_posts_with_markdown', true );
408
				}
409
410
				if ( did_action( 'wp_loaded' ) ) {
411
					self::upgrade_on_load();
412
				} else {
413
					add_action(
414
						'wp_loaded',
415
						array( __CLASS__, 'upgrade_on_load' )
416
					);
417
				}
418
			}
419
		}
420
	}
421
422
	/**
423
	 * Runs upgrade routines that need to have modules loaded.
424
	 */
425
	static function upgrade_on_load() {
426
427
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
428
		// This can happen in case Jetpack has been just upgraded and is
429
		// being initialized late during the page load. In this case we wait
430
		// until the next proper admin page load with Jetpack active.
431
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
432
			delete_transient( self::$plugin_upgrade_lock_key );
433
434
			return;
435
		}
436
437
		Jetpack::maybe_set_version_option();
438
439
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
440
			Jetpack_Widget_Conditions::migrate_post_type_rules();
441
		}
442
443
		if (
444
			class_exists( 'Jetpack_Sitemap_Manager' )
445
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
446
		) {
447
			do_action( 'jetpack_sitemaps_purge_data' );
448
		}
449
450
		delete_transient( self::$plugin_upgrade_lock_key );
451
	}
452
453
	/**
454
	 * Saves all the currently active modules to options.
455
	 * Also fires Action hooks for each newly activated and deactivated module.
456
	 *
457
	 * @param $modules Array Array of active modules to be saved in options.
458
	 *
459
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
Documentation introduced by
The doc-type $success could not be parsed: Unknown type name "$success" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
460
	 */
461
	static function update_active_modules( $modules ) {
462
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
463
		$active_modules       = Jetpack::get_active_modules();
464
		$new_active_modules   = array_diff( $modules, $current_modules );
465
		$new_inactive_modules = array_diff( $active_modules, $modules );
466
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
467
		$reindexed_modules    = array_values( $new_current_modules );
468
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
469
470
		foreach ( $new_active_modules as $module ) {
471
			/**
472
			 * Fires when a specific module is activated.
473
			 *
474
			 * @since 1.9.0
475
			 *
476
			 * @param string $module Module slug.
477
			 * @param boolean $success whether the module was activated. @since 4.2
478
			 */
479
			do_action( 'jetpack_activate_module', $module, $success );
480
			/**
481
			 * Fires when a module is activated.
482
			 * The dynamic part of the filter, $module, is the module slug.
483
			 *
484
			 * @since 1.9.0
485
			 *
486
			 * @param string $module Module slug.
487
			 */
488
			do_action( "jetpack_activate_module_$module", $module );
489
		}
490
491
		foreach ( $new_inactive_modules as $module ) {
492
			/**
493
			 * Fired after a module has been deactivated.
494
			 *
495
			 * @since 4.2.0
496
			 *
497
			 * @param string $module Module slug.
498
			 * @param boolean $success whether the module was deactivated.
499
			 */
500
			do_action( 'jetpack_deactivate_module', $module, $success );
501
			/**
502
			 * Fires when a module is deactivated.
503
			 * The dynamic part of the filter, $module, is the module slug.
504
			 *
505
			 * @since 1.9.0
506
			 *
507
			 * @param string $module Module slug.
508
			 */
509
			do_action( "jetpack_deactivate_module_$module", $module );
510
		}
511
512
		return $success;
513
	}
514
515
	static function delete_active_modules() {
516
		self::update_active_modules( array() );
517
	}
518
519
	/**
520
	 * Constructor.  Initializes WordPress hooks
521
	 */
522
	private function __construct() {
523
		/*
524
		 * Check for and alert any deprecated hooks
525
		 */
526
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
527
528
		/*
529
		 * Enable enhanced handling of previewing sites in Calypso
530
		 */
531
		if ( Jetpack::is_active() ) {
532
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
533
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
534
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
535
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
536
		}
537
538
		if ( ! self::jetpack_tos_agreed() ) {
539
			add_action( 'init', array( $this, 'track_jetpack_usage' ) );
540
			return;
541
		}
542
543
544
545
		/*
546
		 * Load things that should only be in Network Admin.
547
		 *
548
		 * For now blow away everything else until a more full
549
		 * understanding of what is needed at the network level is
550
		 * available
551
		 */
552
		if ( is_multisite() ) {
553
			Jetpack_Network::init();
554
		}
555
556
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
557
			return function() {
558
				return wp_generate_password( 32, false );
559
			};
560
		} );
561
562
		$this->connection_manager = new Connection_Manager( );
563
564
		/**
565
		 * Prepare Gutenberg Editor functionality
566
		 */
567
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
568
		Jetpack_Gutenberg::init();
569
		Jetpack_Gutenberg::load_independent_blocks();
570
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
571
572
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
573
574
		// Unlink user before deleting the user from .com
575
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
576
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
577
578
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
579
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
580
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
581
				define( 'XMLRPC_REQUEST', true );
582
			}
583
584
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
585
586
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
587
		}
588
589
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
590
			@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...
591
592
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
593
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
594
595
			$this->require_jetpack_authentication();
596
597
			if ( Jetpack::is_active() ) {
598
				// Hack to preserve $HTTP_RAW_POST_DATA
599
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
600
601
				$signed = $this->verify_xml_rpc_signature();
602
				if ( $signed && ! is_wp_error( $signed ) ) {
603
					// The actual API methods.
604
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
605
				} else {
606
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
607
					// active Jetpack connection, so that additional users can link their account.
608
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
609
				}
610
			} else {
611
				new XMLRPC_Connector( $this->connection_manager );
612
613
				// The bootstrap API methods.
614
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
615
				$signed = $this->verify_xml_rpc_signature();
616
				if ( $signed && ! is_wp_error( $signed ) ) {
617
					// the jetpack Provision method is available for blog-token-signed requests
618
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
619
				}
620
			}
621
622
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
623
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
624
		} elseif (
625
			is_admin() &&
626
			isset( $_POST['action'] ) && (
627
				'jetpack_upload_file' == $_POST['action'] ||
628
				'jetpack_update_file' == $_POST['action']
629
			)
630
		) {
631
			$this->require_jetpack_authentication();
632
			$this->add_remote_request_handlers();
633
		} else {
634
			if ( Jetpack::is_active() ) {
635
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
636
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
637
			} else {
638
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
639
			}
640
		}
641
642
		if ( Jetpack::is_active() ) {
643
			Jetpack_Heartbeat::init();
644
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
645
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
646
				Jetpack_Search_Performance_Logger::init();
647
			}
648
		}
649
650
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
651
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
652
653
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
654
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
655
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
656
		}
657
658
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
659
660
		add_action( 'admin_init', array( $this, 'admin_init' ) );
661
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
662
663
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
664
665
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
666
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
667
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
668
669
		// returns HTTPS support status
670
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
671
672
		// JITM AJAX callback function
673
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
674
675
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
676
677
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
678
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
679
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
680
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
681
682
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
683
684
		/**
685
		 * These actions run checks to load additional files.
686
		 * They check for external files or plugins, so they need to run as late as possible.
687
		 */
688
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
689
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
690
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
691
692
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
693
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
694
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
695
696
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
697
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
698
699
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
700
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
701
702
		// A filter to control all just in time messages
703
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
704
705
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
706
707
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
708
		// We should make sure to only do this for front end links.
709
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
710
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
711
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
712
713
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
714
			//so they point moderation links on emails to Calypso
715
			jetpack_require_lib( 'functions.wp-notify' );
716
		}
717
718
		// Update the Jetpack plan from API on heartbeats
719
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
720
721
		/**
722
		 * This is the hack to concatenate all css files into one.
723
		 * For description and reasoning see the implode_frontend_css method
724
		 *
725
		 * Super late priority so we catch all the registered styles
726
		 */
727
		if( !is_admin() ) {
728
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
729
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
730
		}
731
732
733
		/**
734
		 * These are sync actions that we need to keep track of for jitms
735
		 */
736
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
737
738
		// Actually push the stats on shutdown.
739
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
740
			add_action( 'shutdown', array( $this, 'push_stats' ) );
741
		}
742
743
		// Track that we've begun verifying the previously generated secret.
744
		add_action( 'jetpack_verify_secrets_begin', array( $this, 'track_jetpack_verify_secrets_begin' ), 10, 2 );
745
		add_action( 'jetpack_verify_secrets_success', array( $this, 'track_jetpack_verify_secrets_success' ), 10, 2 );
746
		add_action( 'jetpack_verify_secrets_fail', array( $this, 'track_jetpack_verify_secrets_fail' ), 10, 3 );
747
	}
748
749
	function initialize_rest_api_registration_connector() {
750
		new REST_Connector( $this->connection_manager );
751
	}
752
753
	/**
754
	 * This is ported over from the manage module, which has been deprecated and baked in here.
755
	 *
756
	 * @param $domains
757
	 */
758
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
759
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
760
	}
761
762
	/**
763
	 * Return $domains, with 'wordpress.com' appended.
764
	 * This is ported over from the manage module, which has been deprecated and baked in here.
765
	 *
766
	 * @param $domains
767
	 * @return array
768
	 */
769
	function allow_wpcom_domain( $domains ) {
770
		if ( empty( $domains ) ) {
771
			$domains = array();
772
		}
773
		$domains[] = 'wordpress.com';
774
		return array_unique( $domains );
775
	}
776
777
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
778
		$post = get_post( $post_id );
779
780
		if ( empty( $post ) ) {
781
			return $default_url;
782
		}
783
784
		$post_type = $post->post_type;
785
786
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
787
		// https://en.support.wordpress.com/custom-post-types/
788
		$allowed_post_types = array(
789
			'post' => 'post',
790
			'page' => 'page',
791
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
792
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
793
		);
794
795
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
796
			return $default_url;
797
		}
798
799
		$path_prefix = $allowed_post_types[ $post_type ];
800
801
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
802
803
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
804
	}
805
806
	function point_edit_comment_links_to_calypso( $url ) {
807
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
808
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
809
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
810
			Jetpack::build_raw_urls( get_home_url() ),
811
			$query_args['amp;c']
812
		) );
813
	}
814
815
	function jetpack_track_last_sync_callback( $params ) {
816
		/**
817
		 * Filter to turn off jitm caching
818
		 *
819
		 * @since 5.4.0
820
		 *
821
		 * @param bool false Whether to cache just in time messages
822
		 */
823
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
824
			return $params;
825
		}
826
827
		if ( is_array( $params ) && isset( $params[0] ) ) {
828
			$option = $params[0];
829
			if ( 'active_plugins' === $option ) {
830
				// use the cache if we can, but not terribly important if it gets evicted
831
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
832
			}
833
		}
834
835
		return $params;
836
	}
837
838
	function jetpack_connection_banner_callback() {
839
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
840
841
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
842
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
843
			wp_send_json_success();
844
		}
845
846
		wp_die();
847
	}
848
849
	/**
850
	 * Removes all XML-RPC methods that are not `jetpack.*`.
851
	 * Only used in our alternate XML-RPC endpoint, where we want to
852
	 * ensure that Core and other plugins' methods are not exposed.
853
	 *
854
	 * @param array $methods
855
	 * @return array filtered $methods
856
	 */
857
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
858
		$jetpack_methods = array();
859
860
		foreach ( $methods as $method => $callback ) {
861
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
862
				$jetpack_methods[ $method ] = $callback;
863
			}
864
		}
865
866
		return $jetpack_methods;
867
	}
868
869
	/**
870
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
871
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
872
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
873
	 * which is accessible via a different URI. Most of the below is copied directly
874
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
875
	 */
876
	function alternate_xmlrpc() {
877
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
878
		global $HTTP_RAW_POST_DATA;
879
880
		// Some browser-embedded clients send cookies. We don't want them.
881
		$_COOKIE = array();
882
883
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
884
		// but we can do it ourself.
885
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
886
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
887
		}
888
889
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
890
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
891
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
892
		}
893
894
		// phpcs:enable
895
896
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
897
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
898
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
899
900
		/**
901
		 * Filters the class used for handling XML-RPC requests.
902
		 *
903
		 * @since 3.1.0
904
		 *
905
		 * @param string $class The name of the XML-RPC server class.
906
		 */
907
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
908
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
909
910
		// Fire off the request
911
		nocache_headers();
912
		$wp_xmlrpc_server->serve_request();
913
914
		exit;
915
	}
916
917
	/**
918
	 * The callback for the JITM ajax requests.
919
	 */
920
	function jetpack_jitm_ajax_callback() {
921
		// Check for nonce
922
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
923
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
924
		}
925
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
926
			$module_slug = $_REQUEST['jitmModule'];
927
			Jetpack::log( 'activate', $module_slug );
928
			Jetpack::activate_module( $module_slug, false, false );
929
			Jetpack::state( 'message', 'no_message' );
930
931
			//A Jetpack module is being activated through a JITM, track it
932
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
933
			$this->do_stats( 'server_side' );
934
935
			wp_send_json_success();
936
		}
937
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
938
			// get the hide_jitm options array
939
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
940
			$module_slug = $_REQUEST['jitmModule'];
941
942
			if( ! $jetpack_hide_jitm ) {
943
				$jetpack_hide_jitm = array(
944
					$module_slug => 'hide'
945
				);
946
			} else {
947
				$jetpack_hide_jitm[$module_slug] = 'hide';
948
			}
949
950
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
951
952
			//jitm is being dismissed forever, track it
953
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
954
			$this->do_stats( 'server_side' );
955
956
			wp_send_json_success();
957
		}
958 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
959
			$module_slug = $_REQUEST['jitmModule'];
960
961
			// User went to WordPress.com, track this
962
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
963
			$this->do_stats( 'server_side' );
964
965
			wp_send_json_success();
966
		}
967 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
968
			$track = $_REQUEST['jitmModule'];
969
970
			// User is viewing JITM, track it.
971
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
972
			$this->do_stats( 'server_side' );
973
974
			wp_send_json_success();
975
		}
976
	}
977
978
	/**
979
	 * If there are any stats that need to be pushed, but haven't been, push them now.
980
	 */
981
	function push_stats() {
982
		if ( ! empty( $this->stats ) ) {
983
			$this->do_stats( 'server_side' );
984
		}
985
	}
986
987
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
988
		switch( $cap ) {
989
			case 'jetpack_connect' :
990
			case 'jetpack_reconnect' :
991
				if ( Jetpack::is_development_mode() ) {
992
					$caps = array( 'do_not_allow' );
993
					break;
994
				}
995
				/**
996
				 * Pass through. If it's not development mode, these should match disconnect.
997
				 * Let users disconnect if it's development mode, just in case things glitch.
998
				 */
999
			case 'jetpack_disconnect' :
1000
				/**
1001
				 * In multisite, can individual site admins manage their own connection?
1002
				 *
1003
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1004
				 */
1005
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1006
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1007
						/**
1008
						 * We need to update the option name -- it's terribly unclear which
1009
						 * direction the override goes.
1010
						 *
1011
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1012
						 */
1013
						$caps = array( 'do_not_allow' );
1014
						break;
1015
					}
1016
				}
1017
1018
				$caps = array( 'manage_options' );
1019
				break;
1020
			case 'jetpack_manage_modules' :
1021
			case 'jetpack_activate_modules' :
1022
			case 'jetpack_deactivate_modules' :
1023
				$caps = array( 'manage_options' );
1024
				break;
1025
			case 'jetpack_configure_modules' :
1026
				$caps = array( 'manage_options' );
1027
				break;
1028
			case 'jetpack_manage_autoupdates' :
1029
				$caps = array(
1030
					'manage_options',
1031
					'update_plugins',
1032
				);
1033
				break;
1034
			case 'jetpack_network_admin_page':
1035
			case 'jetpack_network_settings_page':
1036
				$caps = array( 'manage_network_plugins' );
1037
				break;
1038
			case 'jetpack_network_sites_page':
1039
				$caps = array( 'manage_sites' );
1040
				break;
1041
			case 'jetpack_admin_page' :
1042
				if ( Jetpack::is_development_mode() ) {
1043
					$caps = array( 'manage_options' );
1044
					break;
1045
				} else {
1046
					$caps = array( 'read' );
1047
				}
1048
				break;
1049
			case 'jetpack_connect_user' :
1050
				if ( Jetpack::is_development_mode() ) {
1051
					$caps = array( 'do_not_allow' );
1052
					break;
1053
				}
1054
				$caps = array( 'read' );
1055
				break;
1056
		}
1057
		return $caps;
1058
	}
1059
1060
	function require_jetpack_authentication() {
1061
		// Don't let anyone authenticate
1062
		$_COOKIE = array();
1063
		remove_all_filters( 'authenticate' );
1064
		remove_all_actions( 'wp_login_failed' );
1065
1066
		if ( Jetpack::is_active() ) {
1067
			// Allow Jetpack authentication
1068
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1069
		}
1070
	}
1071
1072
	/**
1073
	 * Load language files
1074
	 * @action plugins_loaded
1075
	 */
1076
	public static function plugin_textdomain() {
1077
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1078
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1079
	}
1080
1081
	/**
1082
	 * Register assets for use in various modules and the Jetpack admin page.
1083
	 *
1084
	 * @uses wp_script_is, wp_register_script, plugins_url
1085
	 * @action wp_loaded
1086
	 * @return null
1087
	 */
1088
	public function register_assets() {
1089
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1090
			wp_register_script(
1091
				'spin',
1092
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1093
				false,
1094
				'1.3'
1095
			);
1096
		}
1097
1098
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1099
			wp_register_script(
1100
				'jquery.spin',
1101
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1102
				array( 'jquery', 'spin' ),
1103
				'1.3'
1104
			);
1105
		}
1106
1107 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1108
			wp_register_script(
1109
				'jetpack-gallery-settings',
1110
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1111
				array( 'media-views' ),
1112
				'20121225'
1113
			);
1114
		}
1115
1116
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1117
			wp_register_script(
1118
				'jetpack-twitter-timeline',
1119
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1120
				array( 'jquery' ),
1121
				'4.0.0',
1122
				true
1123
			);
1124
		}
1125
1126
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1127
			wp_register_script(
1128
				'jetpack-facebook-embed',
1129
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1130
				array( 'jquery' ),
1131
				null,
1132
				true
1133
			);
1134
1135
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1136
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1137
			if ( ! is_numeric( $fb_app_id ) ) {
1138
				$fb_app_id = '';
1139
			}
1140
			wp_localize_script(
1141
				'jetpack-facebook-embed',
1142
				'jpfbembed',
1143
				array(
1144
					'appid' => $fb_app_id,
1145
					'locale' => $this->get_locale(),
1146
				)
1147
			);
1148
		}
1149
1150
		/**
1151
		 * As jetpack_register_genericons is by default fired off a hook,
1152
		 * the hook may have already fired by this point.
1153
		 * So, let's just trigger it manually.
1154
		 */
1155
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1156
		jetpack_register_genericons();
1157
1158
		/**
1159
		 * Register the social logos
1160
		 */
1161
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1162
		jetpack_register_social_logos();
1163
1164 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1165
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1166
	}
1167
1168
	/**
1169
	 * Guess locale from language code.
1170
	 *
1171
	 * @param string $lang Language code.
1172
	 * @return string|bool
1173
	 */
1174 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1175
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1176
			return 'en_US';
1177
		}
1178
1179
		if ( ! class_exists( 'GP_Locales' ) ) {
1180
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1181
				return false;
1182
			}
1183
1184
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1185
		}
1186
1187
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1188
			// WP.com: get_locale() returns 'it'
1189
			$locale = GP_Locales::by_slug( $lang );
1190
		} else {
1191
			// Jetpack: get_locale() returns 'it_IT';
1192
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1193
		}
1194
1195
		if ( ! $locale ) {
1196
			return false;
1197
		}
1198
1199
		if ( empty( $locale->facebook_locale ) ) {
1200
			if ( empty( $locale->wp_locale ) ) {
1201
				return false;
1202
			} else {
1203
				// Facebook SDK is smart enough to fall back to en_US if a
1204
				// locale isn't supported. Since supported Facebook locales
1205
				// can fall out of sync, we'll attempt to use the known
1206
				// wp_locale value and rely on said fallback.
1207
				return $locale->wp_locale;
1208
			}
1209
		}
1210
1211
		return $locale->facebook_locale;
1212
	}
1213
1214
	/**
1215
	 * Get the locale.
1216
	 *
1217
	 * @return string|bool
1218
	 */
1219
	function get_locale() {
1220
		$locale = $this->guess_locale_from_lang( get_locale() );
1221
1222
		if ( ! $locale ) {
1223
			$locale = 'en_US';
1224
		}
1225
1226
		return $locale;
1227
	}
1228
1229
	/**
1230
	 * Device Pixels support
1231
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1232
	 */
1233
	function devicepx() {
1234
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1235
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1236
		}
1237
	}
1238
1239
	/**
1240
	 * Return the network_site_url so that .com knows what network this site is a part of.
1241
	 * @param  bool $option
1242
	 * @return string
1243
	 */
1244
	public function jetpack_main_network_site_option( $option ) {
1245
		return network_site_url();
1246
	}
1247
	/**
1248
	 * Network Name.
1249
	 */
1250
	static function network_name( $option = null ) {
1251
		global $current_site;
1252
		return $current_site->site_name;
1253
	}
1254
	/**
1255
	 * Does the network allow new user and site registrations.
1256
	 * @return string
1257
	 */
1258
	static function network_allow_new_registrations( $option = null ) {
1259
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1260
	}
1261
	/**
1262
	 * Does the network allow admins to add new users.
1263
	 * @return boolian
1264
	 */
1265
	static function network_add_new_users( $option = null ) {
1266
		return (bool) get_site_option( 'add_new_users' );
1267
	}
1268
	/**
1269
	 * File upload psace left per site in MB.
1270
	 *  -1 means NO LIMIT.
1271
	 * @return number
1272
	 */
1273
	static function network_site_upload_space( $option = null ) {
1274
		// value in MB
1275
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1276
	}
1277
1278
	/**
1279
	 * Network allowed file types.
1280
	 * @return string
1281
	 */
1282
	static function network_upload_file_types( $option = null ) {
1283
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1284
	}
1285
1286
	/**
1287
	 * Maximum file upload size set by the network.
1288
	 * @return number
1289
	 */
1290
	static function network_max_upload_file_size( $option = null ) {
1291
		// value in KB
1292
		return get_site_option( 'fileupload_maxk', 300 );
1293
	}
1294
1295
	/**
1296
	 * Lets us know if a site allows admins to manage the network.
1297
	 * @return array
1298
	 */
1299
	static function network_enable_administration_menus( $option = null ) {
1300
		return get_site_option( 'menu_items' );
1301
	}
1302
1303
	/**
1304
	 * If a user has been promoted to or demoted from admin, we need to clear the
1305
	 * jetpack_other_linked_admins transient.
1306
	 *
1307
	 * @since 4.3.2
1308
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1309
	 *
1310
	 * @param int    $user_id   The user ID whose role changed.
1311
	 * @param string $role      The new role.
1312
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|null?

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

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

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

Loading history...
1313
	 */
1314
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1315
		if ( 'administrator' == $role
1316
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1317
			|| is_null( $old_roles )
1318
		) {
1319
			delete_transient( 'jetpack_other_linked_admins' );
1320
		}
1321
	}
1322
1323
	/**
1324
	 * Checks to see if there are any other users available to become primary
1325
	 * Users must both:
1326
	 * - Be linked to wpcom
1327
	 * - Be an admin
1328
	 *
1329
	 * @return mixed False if no other users are linked, Int if there are.
1330
	 */
1331
	static function get_other_linked_admins() {
1332
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1333
1334
		if ( false === $other_linked_users ) {
1335
			$admins = get_users( array( 'role' => 'administrator' ) );
1336
			if ( count( $admins ) > 1 ) {
1337
				$available = array();
1338
				foreach ( $admins as $admin ) {
1339
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1340
						$available[] = $admin->ID;
1341
					}
1342
				}
1343
1344
				$count_connected_admins = count( $available );
1345
				if ( count( $available ) > 1 ) {
1346
					$other_linked_users = $count_connected_admins;
1347
				} else {
1348
					$other_linked_users = 0;
1349
				}
1350
			} else {
1351
				$other_linked_users = 0;
1352
			}
1353
1354
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1355
		}
1356
1357
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1358
	}
1359
1360
	/**
1361
	 * Return whether we are dealing with a multi network setup or not.
1362
	 * The reason we are type casting this is because we want to avoid the situation where
1363
	 * the result is false since when is_main_network_option return false it cases
1364
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1365
	 * database which could be set to anything as opposed to what this function returns.
1366
	 * @param  bool  $option
1367
	 *
1368
	 * @return boolean
1369
	 */
1370
	public function is_main_network_option( $option ) {
1371
		// return '1' or ''
1372
		return (string) (bool) Jetpack::is_multi_network();
1373
	}
1374
1375
	/**
1376
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1377
	 *
1378
	 * @param  string  $option
1379
	 * @return boolean
1380
	 */
1381
	public function is_multisite( $option ) {
1382
		return (string) (bool) is_multisite();
1383
	}
1384
1385
	/**
1386
	 * Implemented since there is no core is multi network function
1387
	 * Right now there is no way to tell if we which network is the dominant network on the system
1388
	 *
1389
	 * @since  3.3
1390
	 * @return boolean
1391
	 */
1392
	public static function is_multi_network() {
1393
		global  $wpdb;
1394
1395
		// if we don't have a multi site setup no need to do any more
1396
		if ( ! is_multisite() ) {
1397
			return false;
1398
		}
1399
1400
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1401
		if ( $num_sites > 1 ) {
1402
			return true;
1403
		} else {
1404
			return false;
1405
		}
1406
	}
1407
1408
	/**
1409
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1410
	 * @return null
1411
	 */
1412
	function update_jetpack_main_network_site_option() {
1413
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1414
	}
1415
	/**
1416
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1417
	 *
1418
	 */
1419
	function update_jetpack_network_settings() {
1420
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1421
		// Only sync this info for the main network site.
1422
	}
1423
1424
	/**
1425
	 * Get back if the current site is single user site.
1426
	 *
1427
	 * @return bool
1428
	 */
1429
	public static function is_single_user_site() {
1430
		global $wpdb;
1431
1432 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1433
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1434
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1435
		}
1436
		return 1 === (int) $some_users;
1437
	}
1438
1439
	/**
1440
	 * Returns true if the site has file write access false otherwise.
1441
	 * @return string ( '1' | '0' )
1442
	 **/
1443
	public static function file_system_write_access() {
1444
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1445
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1446
		}
1447
1448
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1449
1450
		$filesystem_method = get_filesystem_method();
1451
		if ( $filesystem_method === 'direct' ) {
1452
			return 1;
1453
		}
1454
1455
		ob_start();
1456
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1457
		ob_end_clean();
1458
		if ( $filesystem_credentials_are_stored ) {
1459
			return 1;
1460
		}
1461
		return 0;
1462
	}
1463
1464
	/**
1465
	 * Finds out if a site is using a version control system.
1466
	 * @return string ( '1' | '0' )
1467
	 **/
1468
	public static function is_version_controlled() {
1469
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1470
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1471
	}
1472
1473
	/**
1474
	 * Determines whether the current theme supports featured images or not.
1475
	 * @return string ( '1' | '0' )
1476
	 */
1477
	public static function featured_images_enabled() {
1478
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1479
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1480
	}
1481
1482
	/**
1483
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1484
	 *
1485
	 * @deprecated 4.7 use get_avatar_url instead.
1486
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1487
	 * @param int $size Size of the avatar image
1488
	 * @param string $default URL to a default image to use if no avatar is available
1489
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1490
	 *
1491
	 * @return array
1492
	 */
1493
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1494
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1495
		return get_avatar_url( $id_or_email, array(
1496
			'size' => $size,
1497
			'default' => $default,
1498
			'force_default' => $force_display,
1499
		) );
1500
	}
1501
1502
	/**
1503
	 * jetpack_updates is saved in the following schema:
1504
	 *
1505
	 * array (
1506
	 *      'plugins'                       => (int) Number of plugin updates available.
1507
	 *      'themes'                        => (int) Number of theme updates available.
1508
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1509
	 *      'translations'                  => (int) Number of translation updates available.
1510
	 *      'total'                         => (int) Total of all available updates.
1511
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1512
	 * )
1513
	 * @return array
1514
	 */
1515
	public static function get_updates() {
1516
		$update_data = wp_get_update_data();
1517
1518
		// Stores the individual update counts as well as the total count.
1519
		if ( isset( $update_data['counts'] ) ) {
1520
			$updates = $update_data['counts'];
1521
		}
1522
1523
		// If we need to update WordPress core, let's find the latest version number.
1524 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1525
			$cur = get_preferred_from_update_core();
1526
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1527
				$updates['wp_update_version'] = $cur->current;
1528
			}
1529
		}
1530
		return isset( $updates ) ? $updates : array();
1531
	}
1532
1533
	public static function get_update_details() {
1534
		$update_details = array(
1535
			'update_core' => get_site_transient( 'update_core' ),
1536
			'update_plugins' => get_site_transient( 'update_plugins' ),
1537
			'update_themes' => get_site_transient( 'update_themes' ),
1538
		);
1539
		return $update_details;
1540
	}
1541
1542
	public static function refresh_update_data() {
1543
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1544
1545
	}
1546
1547
	public static function refresh_theme_data() {
1548
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1549
	}
1550
1551
	/**
1552
	 * Is Jetpack active?
1553
	 */
1554
	public static function is_active() {
1555
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

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

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

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

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

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

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

Loading history...
1776
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1777
	}
1778
1779
	/**
1780
	 * Gets current user IP address.
1781
	 *
1782
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1783
	 *
1784
	 * @return string                  Current user IP address.
1785
	 */
1786
	public static function current_user_ip( $check_all_headers = false ) {
1787
		if ( $check_all_headers ) {
1788
			foreach ( array(
1789
				'HTTP_CF_CONNECTING_IP',
1790
				'HTTP_CLIENT_IP',
1791
				'HTTP_X_FORWARDED_FOR',
1792
				'HTTP_X_FORWARDED',
1793
				'HTTP_X_CLUSTER_CLIENT_IP',
1794
				'HTTP_FORWARDED_FOR',
1795
				'HTTP_FORWARDED',
1796
				'HTTP_VIA',
1797
			) as $key ) {
1798
				if ( ! empty( $_SERVER[ $key ] ) ) {
1799
					return $_SERVER[ $key ];
1800
				}
1801
			}
1802
		}
1803
1804
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1805
	}
1806
1807
	/**
1808
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1809
	 */
1810
	function extra_oembed_providers() {
1811
		// Cloudup: https://dev.cloudup.com/#oembed
1812
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1813
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1814
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1815
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1816
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1817
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1818
	}
1819
1820
	/**
1821
	 * Synchronize connected user role changes
1822
	 */
1823
	function user_role_change( $user_id ) {
1824
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1825
		Jetpack_Sync_Users::user_role_change( $user_id );
1826
	}
1827
1828
	/**
1829
	 * Loads the currently active modules.
1830
	 */
1831
	public static function load_modules() {
1832
		if (
1833
			! self::is_active()
1834
			&& ! self::is_development_mode()
1835
			&& ! self::is_onboarding()
1836
			&& (
1837
				! is_multisite()
1838
				|| ! get_site_option( 'jetpack_protect_active' )
1839
			)
1840
		) {
1841
			return;
1842
		}
1843
1844
		$version = Jetpack_Options::get_option( 'version' );
1845 View Code Duplication
		if ( ! $version ) {
1846
			$version = $old_version = JETPACK__VERSION . ':' . time();
1847
			/** This action is documented in class.jetpack.php */
1848
			do_action( 'updating_jetpack_version', $version, false );
1849
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1850
		}
1851
		list( $version ) = explode( ':', $version );
1852
1853
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1854
1855
		$modules_data = array();
1856
1857
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1858
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1859
			$updated_modules = array();
1860
			foreach ( $modules as $module ) {
1861
				$modules_data[ $module ] = Jetpack::get_module( $module );
1862
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1863
					continue;
1864
				}
1865
1866
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1867
					continue;
1868
				}
1869
1870
				$updated_modules[] = $module;
1871
			}
1872
1873
			$modules = array_diff( $modules, $updated_modules );
1874
		}
1875
1876
		$is_development_mode = Jetpack::is_development_mode();
1877
1878
		foreach ( $modules as $index => $module ) {
1879
			// If we're in dev mode, disable modules requiring a connection
1880
			if ( $is_development_mode ) {
1881
				// Prime the pump if we need to
1882
				if ( empty( $modules_data[ $module ] ) ) {
1883
					$modules_data[ $module ] = Jetpack::get_module( $module );
1884
				}
1885
				// If the module requires a connection, but we're in local mode, don't include it.
1886
				if ( $modules_data[ $module ]['requires_connection'] ) {
1887
					continue;
1888
				}
1889
			}
1890
1891
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1892
				continue;
1893
			}
1894
1895
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1896
				unset( $modules[ $index ] );
1897
				self::update_active_modules( array_values( $modules ) );
1898
				continue;
1899
			}
1900
1901
			/**
1902
			 * Fires when a specific module is loaded.
1903
			 * The dynamic part of the hook, $module, is the module slug.
1904
			 *
1905
			 * @since 1.1.0
1906
			 */
1907
			do_action( 'jetpack_module_loaded_' . $module );
1908
		}
1909
1910
		/**
1911
		 * Fires when all the modules are loaded.
1912
		 *
1913
		 * @since 1.1.0
1914
		 */
1915
		do_action( 'jetpack_modules_loaded' );
1916
1917
		// 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.
1918
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1919
	}
1920
1921
	/**
1922
	 * Check if Jetpack's REST API compat file should be included
1923
	 * @action plugins_loaded
1924
	 * @return null
1925
	 */
1926
	public function check_rest_api_compat() {
1927
		/**
1928
		 * Filters the list of REST API compat files to be included.
1929
		 *
1930
		 * @since 2.2.5
1931
		 *
1932
		 * @param array $args Array of REST API compat files to include.
1933
		 */
1934
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1935
1936
		if ( function_exists( 'bbpress' ) )
1937
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1938
1939
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1940
			require_once $_jetpack_rest_api_compat_include;
1941
	}
1942
1943
	/**
1944
	 * Gets all plugins currently active in values, regardless of whether they're
1945
	 * traditionally activated or network activated.
1946
	 *
1947
	 * @todo Store the result in core's object cache maybe?
1948
	 */
1949
	public static function get_active_plugins() {
1950
		$active_plugins = (array) get_option( 'active_plugins', array() );
1951
1952
		if ( is_multisite() ) {
1953
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1954
			// whereas active_plugins stores them in the values.
1955
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1956
			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...
1957
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1958
			}
1959
		}
1960
1961
		sort( $active_plugins );
1962
1963
		return array_unique( $active_plugins );
1964
	}
1965
1966
	/**
1967
	 * Gets and parses additional plugin data to send with the heartbeat data
1968
	 *
1969
	 * @since 3.8.1
1970
	 *
1971
	 * @return array Array of plugin data
1972
	 */
1973
	public static function get_parsed_plugin_data() {
1974
		if ( ! function_exists( 'get_plugins' ) ) {
1975
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1976
		}
1977
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1978
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1979
		$active_plugins = Jetpack::get_active_plugins();
1980
1981
		$plugins = array();
1982
		foreach ( $all_plugins as $path => $plugin_data ) {
1983
			$plugins[ $path ] = array(
1984
					'is_active' => in_array( $path, $active_plugins ),
1985
					'file'      => $path,
1986
					'name'      => $plugin_data['Name'],
1987
					'version'   => $plugin_data['Version'],
1988
					'author'    => $plugin_data['Author'],
1989
			);
1990
		}
1991
1992
		return $plugins;
1993
	}
1994
1995
	/**
1996
	 * Gets and parses theme data to send with the heartbeat data
1997
	 *
1998
	 * @since 3.8.1
1999
	 *
2000
	 * @return array Array of theme data
2001
	 */
2002
	public static function get_parsed_theme_data() {
2003
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2004
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2005
2006
		$themes = array();
2007
		foreach ( $all_themes as $slug => $theme_data ) {
2008
			$theme_headers = array();
2009
			foreach ( $header_keys as $header_key ) {
2010
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2011
			}
2012
2013
			$themes[ $slug ] = array(
2014
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2015
					'slug' => $slug,
2016
					'theme_root' => $theme_data->get_theme_root_uri(),
2017
					'parent' => $theme_data->parent(),
2018
					'headers' => $theme_headers
2019
			);
2020
		}
2021
2022
		return $themes;
2023
	}
2024
2025
	/**
2026
	 * Checks whether a specific plugin is active.
2027
	 *
2028
	 * We don't want to store these in a static variable, in case
2029
	 * there are switch_to_blog() calls involved.
2030
	 */
2031
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2032
		return in_array( $plugin, self::get_active_plugins() );
2033
	}
2034
2035
	/**
2036
	 * Check if Jetpack's Open Graph tags should be used.
2037
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2038
	 *
2039
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2040
	 * @action plugins_loaded
2041
	 * @return null
2042
	 */
2043
	public function check_open_graph() {
2044
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2045
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2046
		}
2047
2048
		$active_plugins = self::get_active_plugins();
2049
2050
		if ( ! empty( $active_plugins ) ) {
2051
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2052
				if ( in_array( $plugin, $active_plugins ) ) {
2053
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2054
					break;
2055
				}
2056
			}
2057
		}
2058
2059
		/**
2060
		 * Allow the addition of Open Graph Meta Tags to all pages.
2061
		 *
2062
		 * @since 2.0.3
2063
		 *
2064
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2065
		 */
2066
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2067
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2068
		}
2069
	}
2070
2071
	/**
2072
	 * Check if Jetpack's Twitter tags should be used.
2073
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2074
	 *
2075
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2076
	 * @action plugins_loaded
2077
	 * @return null
2078
	 */
2079
	public function check_twitter_tags() {
2080
2081
		$active_plugins = self::get_active_plugins();
2082
2083
		if ( ! empty( $active_plugins ) ) {
2084
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2085
				if ( in_array( $plugin, $active_plugins ) ) {
2086
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2087
					break;
2088
				}
2089
			}
2090
		}
2091
2092
		/**
2093
		 * Allow Twitter Card Meta tags to be disabled.
2094
		 *
2095
		 * @since 2.6.0
2096
		 *
2097
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2098
		 */
2099
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2100
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2101
		}
2102
	}
2103
2104
	/**
2105
	 * Allows plugins to submit security reports.
2106
 	 *
2107
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2108
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2109
	 * @param array   $args         See definitions above
2110
	 */
2111
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2112
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2113
	}
2114
2115
/* Jetpack Options API */
2116
2117
	public static function get_option_names( $type = 'compact' ) {
2118
		return Jetpack_Options::get_option_names( $type );
2119
	}
2120
2121
	/**
2122
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2123
 	 *
2124
	 * @param string $name    Option name
2125
	 * @param mixed  $default (optional)
2126
	 */
2127
	public static function get_option( $name, $default = false ) {
2128
		return Jetpack_Options::get_option( $name, $default );
2129
	}
2130
2131
	/**
2132
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2133
 	 *
2134
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2135
	 * @param string $name  Option name
2136
	 * @param mixed  $value Option value
2137
	 */
2138
	public static function update_option( $name, $value ) {
2139
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2140
		return Jetpack_Options::update_option( $name, $value );
2141
	}
2142
2143
	/**
2144
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2145
 	 *
2146
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2147
	 * @param array $array array( option name => option value, ... )
2148
	 */
2149
	public static function update_options( $array ) {
2150
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2151
		return Jetpack_Options::update_options( $array );
2152
	}
2153
2154
	/**
2155
	 * Deletes the given option.  May be passed multiple option names as an array.
2156
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2157
	 *
2158
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2159
	 * @param string|array $names
2160
	 */
2161
	public static function delete_option( $names ) {
2162
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2163
		return Jetpack_Options::delete_option( $names );
2164
	}
2165
2166
	/**
2167
	 * Enters a user token into the user_tokens option
2168
	 *
2169
	 * @param int $user_id
2170
	 * @param string $token
2171
	 * return bool
2172
	 */
2173
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2174
		// not designed for concurrent updates
2175
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2176
		if ( ! is_array( $user_tokens ) )
2177
			$user_tokens = array();
2178
		$user_tokens[$user_id] = $token;
2179
		if ( $is_master_user ) {
2180
			$master_user = $user_id;
2181
			$options     = compact( 'user_tokens', 'master_user' );
2182
		} else {
2183
			$options = compact( 'user_tokens' );
2184
		}
2185
		return Jetpack_Options::update_options( $options );
2186
	}
2187
2188
	/**
2189
	 * Returns an array of all PHP files in the specified absolute path.
2190
	 * Equivalent to glob( "$absolute_path/*.php" ).
2191
	 *
2192
	 * @param string $absolute_path The absolute path of the directory to search.
2193
	 * @return array Array of absolute paths to the PHP files.
2194
	 */
2195
	public static function glob_php( $absolute_path ) {
2196
		if ( function_exists( 'glob' ) ) {
2197
			return glob( "$absolute_path/*.php" );
2198
		}
2199
2200
		$absolute_path = untrailingslashit( $absolute_path );
2201
		$files = array();
2202
		if ( ! $dir = @opendir( $absolute_path ) ) {
2203
			return $files;
2204
		}
2205
2206
		while ( false !== $file = readdir( $dir ) ) {
2207
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2208
				continue;
2209
			}
2210
2211
			$file = "$absolute_path/$file";
2212
2213
			if ( ! is_file( $file ) ) {
2214
				continue;
2215
			}
2216
2217
			$files[] = $file;
2218
		}
2219
2220
		closedir( $dir );
2221
2222
		return $files;
2223
	}
2224
2225
	public static function activate_new_modules( $redirect = false ) {
2226
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2227
			return;
2228
		}
2229
2230
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2231 View Code Duplication
		if ( ! $jetpack_old_version ) {
2232
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2233
			/** This action is documented in class.jetpack.php */
2234
			do_action( 'updating_jetpack_version', $version, false );
2235
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2236
		}
2237
2238
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2239
2240
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2241
			return;
2242
		}
2243
2244
		$active_modules     = Jetpack::get_active_modules();
2245
		$reactivate_modules = array();
2246
		foreach ( $active_modules as $active_module ) {
2247
			$module = Jetpack::get_module( $active_module );
2248
			if ( ! isset( $module['changed'] ) ) {
2249
				continue;
2250
			}
2251
2252
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2253
				continue;
2254
			}
2255
2256
			$reactivate_modules[] = $active_module;
2257
			Jetpack::deactivate_module( $active_module );
2258
		}
2259
2260
		$new_version = JETPACK__VERSION . ':' . time();
2261
		/** This action is documented in class.jetpack.php */
2262
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2263
		Jetpack_Options::update_options(
2264
			array(
2265
				'version'     => $new_version,
2266
				'old_version' => $jetpack_old_version,
2267
			)
2268
		);
2269
2270
		Jetpack::state( 'message', 'modules_activated' );
2271
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2272
2273
		if ( $redirect ) {
2274
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2275
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2276
				$page = $_GET['page'];
2277
			}
2278
2279
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2280
			exit;
2281
		}
2282
	}
2283
2284
	/**
2285
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2286
	 * Make sure to tuck away module "library" files in a sub-directory.
2287
	 */
2288
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2289
		static $modules = null;
2290
2291
		if ( ! isset( $modules ) ) {
2292
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2293
			// Use the cache if we're on the front-end and it's available...
2294
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2295
				$modules = $available_modules_option[ JETPACK__VERSION ];
2296
			} else {
2297
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2298
2299
				$modules = array();
2300
2301
				foreach ( $files as $file ) {
2302
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2303
						continue;
2304
					}
2305
2306
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2307
				}
2308
2309
				Jetpack_Options::update_option( 'available_modules', array(
2310
					JETPACK__VERSION => $modules,
2311
				) );
2312
			}
2313
		}
2314
2315
		/**
2316
		 * Filters the array of modules available to be activated.
2317
		 *
2318
		 * @since 2.4.0
2319
		 *
2320
		 * @param array $modules Array of available modules.
2321
		 * @param string $min_version Minimum version number required to use modules.
2322
		 * @param string $max_version Maximum version number required to use modules.
2323
		 */
2324
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2325
2326
		if ( ! $min_version && ! $max_version ) {
2327
			return array_keys( $mods );
2328
		}
2329
2330
		$r = array();
2331
		foreach ( $mods as $slug => $introduced ) {
2332
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2333
				continue;
2334
			}
2335
2336
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2337
				continue;
2338
			}
2339
2340
			$r[] = $slug;
2341
		}
2342
2343
		return $r;
2344
	}
2345
2346
	/**
2347
	 * Default modules loaded on activation.
2348
	 */
2349
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2350
		$return = array();
2351
2352
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2353
			$module_data = Jetpack::get_module( $module );
2354
2355
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2356
				case 'yes' :
2357
					$return[] = $module;
2358
					break;
2359
				case 'public' :
2360
					if ( Jetpack_Options::get_option( 'public' ) ) {
2361
						$return[] = $module;
2362
					}
2363
					break;
2364
				case 'no' :
2365
				default :
2366
					break;
2367
			}
2368
		}
2369
		/**
2370
		 * Filters the array of default modules.
2371
		 *
2372
		 * @since 2.5.0
2373
		 *
2374
		 * @param array $return Array of default modules.
2375
		 * @param string $min_version Minimum version number required to use modules.
2376
		 * @param string $max_version Maximum version number required to use modules.
2377
		 */
2378
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2379
	}
2380
2381
	/**
2382
	 * Checks activated modules during auto-activation to determine
2383
	 * if any of those modules are being deprecated.  If so, close
2384
	 * them out, and add any replacement modules.
2385
	 *
2386
	 * Runs at priority 99 by default.
2387
	 *
2388
	 * This is run late, so that it can still activate a module if
2389
	 * the new module is a replacement for another that the user
2390
	 * currently has active, even if something at the normal priority
2391
	 * would kibosh everything.
2392
	 *
2393
	 * @since 2.6
2394
	 * @uses jetpack_get_default_modules filter
2395
	 * @param array $modules
2396
	 * @return array
2397
	 */
2398
	function handle_deprecated_modules( $modules ) {
2399
		$deprecated_modules = array(
2400
			'debug'            => null,  // Closed out and moved to the debugger library.
2401
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2402
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2403
		);
2404
2405
		// Don't activate SSO if they never completed activating WPCC.
2406
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2407
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2408
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2409
				$deprecated_modules['wpcc'] = null;
2410
			}
2411
		}
2412
2413
		foreach ( $deprecated_modules as $module => $replacement ) {
2414
			if ( Jetpack::is_module_active( $module ) ) {
2415
				self::deactivate_module( $module );
2416
				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...
2417
					$modules[] = $replacement;
2418
				}
2419
			}
2420
		}
2421
2422
		return array_unique( $modules );
2423
	}
2424
2425
	/**
2426
	 * Checks activated plugins during auto-activation to determine
2427
	 * if any of those plugins are in the list with a corresponding module
2428
	 * that is not compatible with the plugin. The module will not be allowed
2429
	 * to auto-activate.
2430
	 *
2431
	 * @since 2.6
2432
	 * @uses jetpack_get_default_modules filter
2433
	 * @param array $modules
2434
	 * @return array
2435
	 */
2436
	function filter_default_modules( $modules ) {
2437
2438
		$active_plugins = self::get_active_plugins();
2439
2440
		if ( ! empty( $active_plugins ) ) {
2441
2442
			// For each module we'd like to auto-activate...
2443
			foreach ( $modules as $key => $module ) {
2444
				// If there are potential conflicts for it...
2445
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2446
					// For each potential conflict...
2447
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2448
						// If that conflicting plugin is active...
2449
						if ( in_array( $plugin, $active_plugins ) ) {
2450
							// Remove that item from being auto-activated.
2451
							unset( $modules[ $key ] );
2452
						}
2453
					}
2454
				}
2455
			}
2456
		}
2457
2458
		return $modules;
2459
	}
2460
2461
	/**
2462
	 * Extract a module's slug from its full path.
2463
	 */
2464
	public static function get_module_slug( $file ) {
2465
		return str_replace( '.php', '', basename( $file ) );
2466
	}
2467
2468
	/**
2469
	 * Generate a module's path from its slug.
2470
	 */
2471
	public static function get_module_path( $slug ) {
2472
		/**
2473
		 * Filters the path of a modules.
2474
		 *
2475
		 * @since 7.4.0
2476
		 *
2477
		 * @param array $return The absolute path to a module's root php file
2478
		 * @param string $slug The module slug
2479
		 */
2480
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2481
	}
2482
2483
	/**
2484
	 * Load module data from module file. Headers differ from WordPress
2485
	 * plugin headers to avoid them being identified as standalone
2486
	 * plugins on the WordPress plugins page.
2487
	 */
2488
	public static function get_module( $module ) {
2489
		$headers = array(
2490
			'name'                      => 'Module Name',
2491
			'description'               => 'Module Description',
2492
			'jumpstart_desc'            => 'Jumpstart Description',
2493
			'sort'                      => 'Sort Order',
2494
			'recommendation_order'      => 'Recommendation Order',
2495
			'introduced'                => 'First Introduced',
2496
			'changed'                   => 'Major Changes In',
2497
			'deactivate'                => 'Deactivate',
2498
			'free'                      => 'Free',
2499
			'requires_connection'       => 'Requires Connection',
2500
			'auto_activate'             => 'Auto Activate',
2501
			'module_tags'               => 'Module Tags',
2502
			'feature'                   => 'Feature',
2503
			'additional_search_queries' => 'Additional Search Queries',
2504
			'plan_classes'              => 'Plans',
2505
		);
2506
2507
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2508
2509
		$mod = Jetpack::get_file_data( $file, $headers );
2510
		if ( empty( $mod['name'] ) ) {
2511
			return false;
2512
		}
2513
2514
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2515
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2516
		$mod['deactivate']              = empty( $mod['deactivate'] );
2517
		$mod['free']                    = empty( $mod['free'] );
2518
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2519
2520
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2521
			$mod['auto_activate'] = 'No';
2522
		} else {
2523
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2524
		}
2525
2526
		if ( $mod['module_tags'] ) {
2527
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2528
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2529
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2530
		} else {
2531
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2532
		}
2533
2534 View Code Duplication
		if ( $mod['plan_classes'] ) {
2535
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2536
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2537
		} else {
2538
			$mod['plan_classes'] = array( 'free' );
2539
		}
2540
2541 View Code Duplication
		if ( $mod['feature'] ) {
2542
			$mod['feature'] = explode( ',', $mod['feature'] );
2543
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2544
		} else {
2545
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2546
		}
2547
2548
		/**
2549
		 * Filters the feature array on a module.
2550
		 *
2551
		 * This filter allows you to control where each module is filtered: Recommended,
2552
		 * Jumpstart, and the default "Other" listing.
2553
		 *
2554
		 * @since 3.5.0
2555
		 *
2556
		 * @param array   $mod['feature'] The areas to feature this module:
2557
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2558
		 *     'Recommended' shows on the main Jetpack admin screen.
2559
		 *     'Other' should be the default if no other value is in the array.
2560
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2561
		 * @param array   $mod All the currently assembled module data.
2562
		 */
2563
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2564
2565
		/**
2566
		 * Filter the returned data about a module.
2567
		 *
2568
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2569
		 * so please be careful.
2570
		 *
2571
		 * @since 3.6.0
2572
		 *
2573
		 * @param array   $mod    The details of the requested module.
2574
		 * @param string  $module The slug of the module, e.g. sharedaddy
2575
		 * @param string  $file   The path to the module source file.
2576
		 */
2577
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2578
	}
2579
2580
	/**
2581
	 * Like core's get_file_data implementation, but caches the result.
2582
	 */
2583
	public static function get_file_data( $file, $headers ) {
2584
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2585
		$file_name = basename( $file );
2586
2587
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2588
2589
		$file_data_option = get_transient( $cache_key );
2590
2591
		if ( false === $file_data_option ) {
2592
			$file_data_option = array();
2593
		}
2594
2595
		$key           = md5( $file_name . serialize( $headers ) );
2596
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2597
2598
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2599
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2600
			return $file_data_option[ $key ];
2601
		}
2602
2603
		$data = get_file_data( $file, $headers );
2604
2605
		$file_data_option[ $key ] = $data;
2606
2607
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2608
2609
		return $data;
2610
	}
2611
2612
2613
	/**
2614
	 * Return translated module tag.
2615
	 *
2616
	 * @param string $tag Tag as it appears in each module heading.
2617
	 *
2618
	 * @return mixed
2619
	 */
2620
	public static function translate_module_tag( $tag ) {
2621
		return jetpack_get_module_i18n_tag( $tag );
2622
	}
2623
2624
	/**
2625
	 * Get i18n strings as a JSON-encoded string
2626
	 *
2627
	 * @return string The locale as JSON
2628
	 */
2629
	public static function get_i18n_data_json() {
2630
2631
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2632
		// JSON files with the file they should be included for. This is an md5
2633
		// of '_inc/build/admin.js'.
2634
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2635
2636
		$i18n_json =
2637
				   JETPACK__PLUGIN_DIR
2638
				   . 'languages/json/jetpack-'
2639
				   . get_user_locale()
2640
				   . '-'
2641
				   . $path_md5
2642
				   . '.json';
2643
2644
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2645
			$locale_data = @file_get_contents( $i18n_json );
2646
			if ( $locale_data ) {
2647
				return $locale_data;
2648
			}
2649
		}
2650
2651
		// Return valid empty Jed locale
2652
		return '{ "locale_data": { "messages": { "": {} } } }';
2653
	}
2654
2655
	/**
2656
	 * Add locale data setup to wp-i18n
2657
	 *
2658
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2659
	 *
2660
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2661
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2662
	 *
2663
	 * This method provides a safe way to request the setup multiple times but add the script at
2664
	 * most once.
2665
	 *
2666
	 * @since 6.7.0
2667
	 *
2668
	 * @return void
2669
	 */
2670
	public static function setup_wp_i18n_locale_data() {
2671
		static $script_added = false;
2672
		if ( ! $script_added ) {
2673
			$script_added = true;
2674
			wp_add_inline_script(
2675
				'wp-i18n',
2676
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2677
			);
2678
		}
2679
	}
2680
2681
	/**
2682
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2683
	 *
2684
	 * @since 3.9.2
2685
	 *
2686
	 * @param array $modules
2687
	 *
2688
	 * @return string|void
2689
	 */
2690
	public static function get_translated_modules( $modules ) {
2691
		foreach ( $modules as $index => $module ) {
2692
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2693
			if ( isset( $module['name'] ) ) {
2694
				$modules[ $index ]['name'] = $i18n_module['name'];
2695
			}
2696
			if ( isset( $module['description'] ) ) {
2697
				$modules[ $index ]['description'] = $i18n_module['description'];
2698
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2699
			}
2700
		}
2701
		return $modules;
2702
	}
2703
2704
	/**
2705
	 * Get a list of activated modules as an array of module slugs.
2706
	 */
2707
	public static function get_active_modules() {
2708
		$active = Jetpack_Options::get_option( 'active_modules' );
2709
2710
		if ( ! is_array( $active ) ) {
2711
			$active = array();
2712
		}
2713
2714
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2715
			$active[] = 'vaultpress';
2716
		} else {
2717
			$active = array_diff( $active, array( 'vaultpress' ) );
2718
		}
2719
2720
		//If protect is active on the main site of a multisite, it should be active on all sites.
2721
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2722
			$active[] = 'protect';
2723
		}
2724
2725
		/**
2726
		 * Allow filtering of the active modules.
2727
		 *
2728
		 * Gives theme and plugin developers the power to alter the modules that
2729
		 * are activated on the fly.
2730
		 *
2731
		 * @since 5.8.0
2732
		 *
2733
		 * @param array $active Array of active module slugs.
2734
		 */
2735
		$active = apply_filters( 'jetpack_active_modules', $active );
2736
2737
		return array_unique( $active );
2738
	}
2739
2740
	/**
2741
	 * Check whether or not a Jetpack module is active.
2742
	 *
2743
	 * @param string $module The slug of a Jetpack module.
2744
	 * @return bool
2745
	 *
2746
	 * @static
2747
	 */
2748
	public static function is_module_active( $module ) {
2749
		return in_array( $module, self::get_active_modules() );
2750
	}
2751
2752
	public static function is_module( $module ) {
2753
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2754
	}
2755
2756
	/**
2757
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2758
	 *
2759
	 * @param bool $catch True to start catching, False to stop.
2760
	 *
2761
	 * @static
2762
	 */
2763
	public static function catch_errors( $catch ) {
2764
		static $display_errors, $error_reporting;
2765
2766
		if ( $catch ) {
2767
			$display_errors  = @ini_set( 'display_errors', 1 );
2768
			$error_reporting = @error_reporting( E_ALL );
2769
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2770
		} else {
2771
			@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...
2772
			@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...
2773
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2774
		}
2775
	}
2776
2777
	/**
2778
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2779
	 */
2780
	public static function catch_errors_on_shutdown() {
2781
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2782
	}
2783
2784
	/**
2785
	 * Rewrite any string to make paths easier to read.
2786
	 *
2787
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2788
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2789
	 *
2790
	 * @param $string
2791
	 * @return mixed
2792
	 */
2793
	public static function alias_directories( $string ) {
2794
		// ABSPATH has a trailing slash.
2795
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2796
		// WP_CONTENT_DIR does not have a trailing slash.
2797
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2798
2799
		return $string;
2800
	}
2801
2802
	public static function activate_default_modules(
2803
		$min_version = false,
2804
		$max_version = false,
2805
		$other_modules = array(),
2806
		$redirect = true,
2807
		$send_state_messages = true
2808
	) {
2809
		$jetpack = Jetpack::init();
2810
2811
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2812
		$modules = array_merge( $other_modules, $modules );
2813
2814
		// Look for standalone plugins and disable if active.
2815
2816
		$to_deactivate = array();
2817
		foreach ( $modules as $module ) {
2818
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2819
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2820
			}
2821
		}
2822
2823
		$deactivated = array();
2824
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2825
			list( $probable_file, $probable_title ) = $deactivate_me;
2826
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2827
				$deactivated[] = $module;
2828
			}
2829
		}
2830
2831
		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...
2832
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2833
2834
			$url = add_query_arg(
2835
				array(
2836
					'action'   => 'activate_default_modules',
2837
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2838
				),
2839
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2840
			);
2841
			wp_safe_redirect( $url );
2842
			exit;
2843
		}
2844
2845
		/**
2846
		 * Fires before default modules are activated.
2847
		 *
2848
		 * @since 1.9.0
2849
		 *
2850
		 * @param string $min_version Minimum version number required to use modules.
2851
		 * @param string $max_version Maximum version number required to use modules.
2852
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2853
		 */
2854
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2855
2856
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2857
		if ( $send_state_messages ) {
2858
			Jetpack::restate();
2859
			Jetpack::catch_errors( true );
2860
		}
2861
2862
		$active = Jetpack::get_active_modules();
2863
2864
		foreach ( $modules as $module ) {
2865
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2866
				$active[] = $module;
2867
				self::update_active_modules( $active );
2868
				continue;
2869
			}
2870
2871
			if ( $send_state_messages && in_array( $module, $active ) ) {
2872
				$module_info = Jetpack::get_module( $module );
2873 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2874
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2875
					if ( $active_state = Jetpack::state( $state ) ) {
2876
						$active_state = explode( ',', $active_state );
2877
					} else {
2878
						$active_state = array();
2879
					}
2880
					$active_state[] = $module;
2881
					Jetpack::state( $state, implode( ',', $active_state ) );
2882
				}
2883
				continue;
2884
			}
2885
2886
			$file = Jetpack::get_module_path( $module );
2887
			if ( ! file_exists( $file ) ) {
2888
				continue;
2889
			}
2890
2891
			// we'll override this later if the plugin can be included without fatal error
2892
			if ( $redirect ) {
2893
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2894
			}
2895
2896
			if ( $send_state_messages ) {
2897
				Jetpack::state( 'error', 'module_activation_failed' );
2898
				Jetpack::state( 'module', $module );
2899
			}
2900
2901
			ob_start();
2902
			require_once $file;
2903
2904
			$active[] = $module;
2905
2906 View Code Duplication
			if ( $send_state_messages ) {
2907
2908
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2909
				if ( $active_state = Jetpack::state( $state ) ) {
2910
					$active_state = explode( ',', $active_state );
2911
				} else {
2912
					$active_state = array();
2913
				}
2914
				$active_state[] = $module;
2915
				Jetpack::state( $state, implode( ',', $active_state ) );
2916
			}
2917
2918
			Jetpack::update_active_modules( $active );
2919
2920
			ob_end_clean();
2921
		}
2922
2923
		if ( $send_state_messages ) {
2924
			Jetpack::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2925
			Jetpack::state( 'module', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2926
		}
2927
2928
		Jetpack::catch_errors( false );
2929
		/**
2930
		 * Fires when default modules are activated.
2931
		 *
2932
		 * @since 1.9.0
2933
		 *
2934
		 * @param string $min_version Minimum version number required to use modules.
2935
		 * @param string $max_version Maximum version number required to use modules.
2936
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2937
		 */
2938
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2939
	}
2940
2941
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2942
		/**
2943
		 * Fires before a module is activated.
2944
		 *
2945
		 * @since 2.6.0
2946
		 *
2947
		 * @param string $module Module slug.
2948
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2949
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2950
		 */
2951
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2952
2953
		$jetpack = Jetpack::init();
2954
2955
		if ( ! strlen( $module ) )
2956
			return false;
2957
2958
		if ( ! Jetpack::is_module( $module ) )
2959
			return false;
2960
2961
		// If it's already active, then don't do it again
2962
		$active = Jetpack::get_active_modules();
2963
		foreach ( $active as $act ) {
2964
			if ( $act == $module )
2965
				return true;
2966
		}
2967
2968
		$module_data = Jetpack::get_module( $module );
2969
2970
		if ( ! Jetpack::is_active() ) {
2971
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2972
				return false;
2973
2974
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2975
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2976
				return false;
2977
		}
2978
2979
		// Check and see if the old plugin is active
2980
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2981
			// Deactivate the old plugin
2982
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2983
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2984
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2985
				Jetpack::state( 'deactivated_plugins', $module );
2986
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2987
				exit;
2988
			}
2989
		}
2990
2991
		// Protect won't work with mis-configured IPs
2992
		if ( 'protect' === $module ) {
2993
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2994
			if ( ! jetpack_protect_get_ip() ) {
2995
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2996
				return false;
2997
			}
2998
		}
2999
3000
		if ( ! Jetpack_Plan::supports( $module ) ) {
3001
			return false;
3002
		}
3003
3004
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3005
		Jetpack::state( 'module', $module );
3006
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3007
3008
		Jetpack::catch_errors( true );
3009
		ob_start();
3010
		require Jetpack::get_module_path( $module );
3011
		/** This action is documented in class.jetpack.php */
3012
		do_action( 'jetpack_activate_module', $module );
3013
		$active[] = $module;
3014
		Jetpack::update_active_modules( $active );
3015
3016
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3017
		ob_end_clean();
3018
		Jetpack::catch_errors( false );
3019
3020
		if ( $redirect ) {
3021
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3022
		}
3023
		if ( $exit ) {
3024
			exit;
3025
		}
3026
		return true;
3027
	}
3028
3029
	function activate_module_actions( $module ) {
3030
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3031
	}
3032
3033
	public static function deactivate_module( $module ) {
3034
		/**
3035
		 * Fires when a module is deactivated.
3036
		 *
3037
		 * @since 1.9.0
3038
		 *
3039
		 * @param string $module Module slug.
3040
		 */
3041
		do_action( 'jetpack_pre_deactivate_module', $module );
3042
3043
		$jetpack = Jetpack::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3044
3045
		$active = Jetpack::get_active_modules();
3046
		$new    = array_filter( array_diff( $active, (array) $module ) );
3047
3048
		return self::update_active_modules( $new );
3049
	}
3050
3051
	public static function enable_module_configurable( $module ) {
3052
		$module = Jetpack::get_module_slug( $module );
3053
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3054
	}
3055
3056
	/**
3057
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3058
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3059
	 *
3060
	 * @param string $module Module slug
3061
	 * @return string $url module configuration URL
3062
	 */
3063
	public static function module_configuration_url( $module ) {
3064
		$module = Jetpack::get_module_slug( $module );
3065
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3066
		/**
3067
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3068
		 *
3069
		 * @since 6.9.0
3070
		 *
3071
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3072
		 */
3073
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3074
3075
		return $url;
3076
	}
3077
3078
/* Installation */
3079
	public static function bail_on_activation( $message, $deactivate = true ) {
3080
?>
3081
<!doctype html>
3082
<html>
3083
<head>
3084
<meta charset="<?php bloginfo( 'charset' ); ?>">
3085
<style>
3086
* {
3087
	text-align: center;
3088
	margin: 0;
3089
	padding: 0;
3090
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3091
}
3092
p {
3093
	margin-top: 1em;
3094
	font-size: 18px;
3095
}
3096
</style>
3097
<body>
3098
<p><?php echo esc_html( $message ); ?></p>
3099
</body>
3100
</html>
3101
<?php
3102
		if ( $deactivate ) {
3103
			$plugins = get_option( 'active_plugins' );
3104
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3105
			$update  = false;
3106
			foreach ( $plugins as $i => $plugin ) {
3107
				if ( $plugin === $jetpack ) {
3108
					$plugins[$i] = false;
3109
					$update = true;
3110
				}
3111
			}
3112
3113
			if ( $update ) {
3114
				update_option( 'active_plugins', array_filter( $plugins ) );
3115
			}
3116
		}
3117
		exit;
3118
	}
3119
3120
	/**
3121
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3122
	 * @static
3123
	 */
3124
	public static function plugin_activation( $network_wide ) {
3125
		Jetpack_Options::update_option( 'activated', 1 );
3126
3127
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3128
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3129
		}
3130
3131
		if ( $network_wide )
3132
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3133
3134
		// For firing one-off events (notices) immediately after activation
3135
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3136
3137
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3138
3139
		Jetpack::plugin_initialize();
3140
	}
3141
3142
	public static function get_activation_source( $referer_url ) {
3143
3144
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3145
			return array( 'wp-cli', null );
3146
		}
3147
3148
		$referer = parse_url( $referer_url );
3149
3150
		$source_type = 'unknown';
3151
		$source_query = null;
3152
3153
		if ( ! is_array( $referer ) ) {
3154
			return array( $source_type, $source_query );
3155
		}
3156
3157
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3158
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3159
3160
		if ( isset( $referer['query'] ) ) {
3161
			parse_str( $referer['query'], $query_parts );
3162
		} else {
3163
			$query_parts = array();
3164
		}
3165
3166
		if ( $plugins_path === $referer['path'] ) {
3167
			$source_type = 'list';
3168
		} elseif ( $plugins_install_path === $referer['path'] ) {
3169
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3170
			switch( $tab ) {
3171
				case 'popular':
3172
					$source_type = 'popular';
3173
					break;
3174
				case 'recommended':
3175
					$source_type = 'recommended';
3176
					break;
3177
				case 'favorites':
3178
					$source_type = 'favorites';
3179
					break;
3180
				case 'search':
3181
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3182
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3183
					break;
3184
				default:
3185
					$source_type = 'featured';
3186
			}
3187
		}
3188
3189
		return array( $source_type, $source_query );
3190
	}
3191
3192
	/**
3193
	 * Runs before bumping version numbers up to a new version
3194
	 * @param  string $version    Version:timestamp
3195
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3196
	 * @return null              [description]
3197
	 */
3198
	public static function do_version_bump( $version, $old_version ) {
3199
		if ( ! $old_version ) { // For new sites
3200
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3201
		}
3202
	}
3203
3204
	/**
3205
	 * Sets the internal version number and activation state.
3206
	 * @static
3207
	 */
3208
	public static function plugin_initialize() {
3209
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3210
			Jetpack_Options::update_option( 'activated', 2 );
3211
		}
3212
3213 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3214
			$version = $old_version = JETPACK__VERSION . ':' . time();
3215
			/** This action is documented in class.jetpack.php */
3216
			do_action( 'updating_jetpack_version', $version, false );
3217
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3218
		}
3219
3220
		Jetpack::load_modules();
3221
3222
		Jetpack_Options::delete_option( 'do_activate' );
3223
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3224
	}
3225
3226
	/**
3227
	 * Removes all connection options
3228
	 * @static
3229
	 */
3230
	public static function plugin_deactivation( ) {
3231
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3232
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3233
			Jetpack_Network::init()->deactivate();
3234
		} else {
3235
			Jetpack::disconnect( false );
3236
			//Jetpack_Heartbeat::init()->deactivate();
3237
		}
3238
	}
3239
3240
	/**
3241
	 * Disconnects from the Jetpack servers.
3242
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3243
	 * @static
3244
	 */
3245
	public static function disconnect( $update_activated_state = true ) {
3246
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3247
		Jetpack::clean_nonces( true );
3248
3249
		// If the site is in an IDC because sync is not allowed,
3250
		// let's make sure to not disconnect the production site.
3251
		if ( ! self::validate_sync_error_idc_option() ) {
3252
			$tracking = new Tracking();
3253
			$tracking->record_user_event( 'disconnect_site', array() );
3254
			Jetpack::load_xml_rpc_client();
3255
			$xml = new Jetpack_IXR_Client();
3256
			$xml->query( 'jetpack.deregister' );
3257
		}
3258
3259
		Jetpack_Options::delete_option(
3260
			array(
3261
				'blog_token',
3262
				'user_token',
3263
				'user_tokens',
3264
				'master_user',
3265
				'time_diff',
3266
				'fallback_no_verify_ssl_certs',
3267
			)
3268
		);
3269
3270
		Jetpack_IDC::clear_all_idc_options();
3271
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3272
3273
		if ( $update_activated_state ) {
3274
			Jetpack_Options::update_option( 'activated', 4 );
3275
		}
3276
3277
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3278
			// Check then record unique disconnection if site has never been disconnected previously
3279
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3280
				$jetpack_unique_connection['disconnected'] = 1;
3281
			} else {
3282
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3283
					//track unique disconnect
3284
					$jetpack = Jetpack::init();
3285
3286
					$jetpack->stat( 'connections', 'unique-disconnect' );
3287
					$jetpack->do_stats( 'server_side' );
3288
				}
3289
				// increment number of times disconnected
3290
				$jetpack_unique_connection['disconnected'] += 1;
3291
			}
3292
3293
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3294
		}
3295
3296
		// Delete cached connected user data
3297
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3298
		delete_transient( $transient_key );
3299
3300
		// Delete all the sync related data. Since it could be taking up space.
3301
		Jetpack_Sync_Sender::get_instance()->uninstall();
3302
3303
		// Disable the Heartbeat cron
3304
		Jetpack_Heartbeat::init()->deactivate();
3305
	}
3306
3307
	/**
3308
	 * Unlinks the current user from the linked WordPress.com user
3309
	 */
3310
	public static function unlink_user( $user_id = null ) {
3311
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3312
			return false;
3313
3314
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3315
3316
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3317
			return false;
3318
3319
		if ( ! isset( $tokens[ $user_id ] ) )
3320
			return false;
3321
3322
		Jetpack::load_xml_rpc_client();
3323
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3324
		$xml->query( 'jetpack.unlink_user', $user_id );
3325
3326
		unset( $tokens[ $user_id ] );
3327
3328
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3329
3330
		/**
3331
		 * Fires after the current user has been unlinked from WordPress.com.
3332
		 *
3333
		 * @since 4.1.0
3334
		 *
3335
		 * @param int $user_id The current user's ID.
3336
		 */
3337
		do_action( 'jetpack_unlinked_user', $user_id );
3338
3339
		return true;
3340
	}
3341
3342
	/**
3343
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3344
	 */
3345
	public static function try_registration() {
3346
		// The user has agreed to the TOS at some point by now.
3347
		Jetpack_Options::update_option( 'tos_agreed', true );
3348
3349
		// Let's get some testing in beta versions and such.
3350
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3351
			// Before attempting to connect, let's make sure that the domains are viable.
3352
			$domains_to_check = array_unique( array(
3353
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3354
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3355
			) );
3356
			foreach ( $domains_to_check as $domain ) {
3357
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3356 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

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

Consider the follow example

<?php

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

    return false;
}

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

Loading history...
3358
				if ( is_wp_error( $result ) ) {
3359
					return $result;
3360
				}
3361
			}
3362
		}
3363
3364
		$result = Jetpack::register();
3365
3366
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3367
		if ( ! $result || is_wp_error( $result ) ) {
3368
			return $result;
3369
		} else {
3370
			return true;
3371
		}
3372
	}
3373
3374
	/**
3375
	 * Tracking an internal event log. Try not to put too much chaff in here.
3376
	 *
3377
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3378
	 */
3379
	public static function log( $code, $data = null ) {
3380
		// only grab the latest 200 entries
3381
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3382
3383
		// Append our event to the log
3384
		$log_entry = array(
3385
			'time'    => time(),
3386
			'user_id' => get_current_user_id(),
3387
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3388
			'code'    => $code,
3389
		);
3390
		// Don't bother storing it unless we've got some.
3391
		if ( ! is_null( $data ) ) {
3392
			$log_entry['data'] = $data;
3393
		}
3394
		$log[] = $log_entry;
3395
3396
		// Try add_option first, to make sure it's not autoloaded.
3397
		// @todo: Add an add_option method to Jetpack_Options
3398
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3399
			Jetpack_Options::update_option( 'log', $log );
3400
		}
3401
3402
		/**
3403
		 * Fires when Jetpack logs an internal event.
3404
		 *
3405
		 * @since 3.0.0
3406
		 *
3407
		 * @param array $log_entry {
3408
		 *	Array of details about the log entry.
3409
		 *
3410
		 *	@param string time Time of the event.
3411
		 *	@param int user_id ID of the user who trigerred the event.
3412
		 *	@param int blog_id Jetpack Blog ID.
3413
		 *	@param string code Unique name for the event.
3414
		 *	@param string data Data about the event.
3415
		 * }
3416
		 */
3417
		do_action( 'jetpack_log_entry', $log_entry );
3418
	}
3419
3420
	/**
3421
	 * Get the internal event log.
3422
	 *
3423
	 * @param $event (string) - only return the specific log events
3424
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3425
	 *
3426
	 * @return array of log events || WP_Error for invalid params
3427
	 */
3428
	public static function get_log( $event = false, $num = false ) {
3429
		if ( $event && ! is_string( $event ) ) {
3430
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3431
		}
3432
3433
		if ( $num && ! is_numeric( $num ) ) {
3434
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3435
		}
3436
3437
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3438
3439
		// If nothing set - act as it did before, otherwise let's start customizing the output
3440
		if ( ! $num && ! $event ) {
3441
			return $entire_log;
3442
		} else {
3443
			$entire_log = array_reverse( $entire_log );
3444
		}
3445
3446
		$custom_log_output = array();
3447
3448
		if ( $event ) {
3449
			foreach ( $entire_log as $log_event ) {
3450
				if ( $event == $log_event[ 'code' ] ) {
3451
					$custom_log_output[] = $log_event;
3452
				}
3453
			}
3454
		} else {
3455
			$custom_log_output = $entire_log;
3456
		}
3457
3458
		if ( $num ) {
3459
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3460
		}
3461
3462
		return $custom_log_output;
3463
	}
3464
3465
	/**
3466
	 * Log modification of important settings.
3467
	 */
3468
	public static function log_settings_change( $option, $old_value, $value ) {
3469
		switch( $option ) {
3470
			case 'jetpack_sync_non_public_post_stati':
3471
				self::log( $option, $value );
3472
				break;
3473
		}
3474
	}
3475
3476
	/**
3477
	 * Return stat data for WPCOM sync
3478
	 */
3479
	public static function get_stat_data( $encode = true, $extended = true ) {
3480
		$data = Jetpack_Heartbeat::generate_stats_array();
3481
3482
		if ( $extended ) {
3483
			$additional_data = self::get_additional_stat_data();
3484
			$data = array_merge( $data, $additional_data );
3485
		}
3486
3487
		if ( $encode ) {
3488
			return json_encode( $data );
3489
		}
3490
3491
		return $data;
3492
	}
3493
3494
	/**
3495
	 * Get additional stat data to sync to WPCOM
3496
	 */
3497
	public static function get_additional_stat_data( $prefix = '' ) {
3498
		$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...
3499
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3500
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3501
		$return["{$prefix}site-count"]     = 0;
3502
3503
		if ( function_exists( 'get_blog_count' ) ) {
3504
			$return["{$prefix}site-count"] = get_blog_count();
3505
		}
3506
		return $return;
3507
	}
3508
3509
	private static function get_site_user_count() {
3510
		global $wpdb;
3511
3512
		if ( function_exists( 'wp_is_large_network' ) ) {
3513
			if ( wp_is_large_network( 'users' ) ) {
3514
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3515
			}
3516
		}
3517 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3518
			// It wasn't there, so regenerate the data and save the transient
3519
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3520
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3521
		}
3522
		return $user_count;
3523
	}
3524
3525
	/* Admin Pages */
3526
3527
	function admin_init() {
3528
		// If the plugin is not connected, display a connect message.
3529
		if (
3530
			// the plugin was auto-activated and needs its candy
3531
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3532
		||
3533
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3534
			! Jetpack_Options::get_option( 'activated' )
3535
		) {
3536
			Jetpack::plugin_initialize();
3537
		}
3538
3539
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3540
			Jetpack_Connection_Banner::init();
3541
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3542
			// Upgrade: 1.1 -> 1.1.1
3543
			// Check and see if host can verify the Jetpack servers' SSL certificate
3544
			$args = array();
3545
			Jetpack_Client::_wp_remote_request(
3546
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3547
				$args,
3548
				true
3549
			);
3550
		}
3551
3552
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3553
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3554
		}
3555
3556
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3557
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3558
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3559
3560
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3561
			// Artificially throw errors in certain whitelisted cases during plugin activation
3562
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3563
		}
3564
3565
		// Add custom column in wp-admin/users.php to show whether user is linked.
3566
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3567
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3568
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3569
	}
3570
3571
	function admin_body_class( $admin_body_class = '' ) {
3572
		$classes = explode( ' ', trim( $admin_body_class ) );
3573
3574
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3575
3576
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3577
		return " $admin_body_class ";
3578
	}
3579
3580
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3581
		return $admin_body_class . ' jetpack-pagestyles ';
3582
	}
3583
3584
	/**
3585
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3586
	 * This function artificially throws errors for such cases (whitelisted).
3587
	 *
3588
	 * @param string $plugin The activated plugin.
3589
	 */
3590
	function throw_error_on_activate_plugin( $plugin ) {
3591
		$active_modules = Jetpack::get_active_modules();
3592
3593
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3594
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3595
			$throw = false;
3596
3597
			// Try and make sure it really was the stats plugin
3598
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3599
				if ( 'stats.php' == basename( $plugin ) ) {
3600
					$throw = true;
3601
				}
3602
			} else {
3603
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3604
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3605
					$throw = true;
3606
				}
3607
			}
3608
3609
			if ( $throw ) {
3610
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3611
			}
3612
		}
3613
	}
3614
3615
	function intercept_plugin_error_scrape_init() {
3616
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3617
	}
3618
3619
	function intercept_plugin_error_scrape( $action, $result ) {
3620
		if ( ! $result ) {
3621
			return;
3622
		}
3623
3624
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3625
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3626
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3627
			}
3628
		}
3629
	}
3630
3631
	function add_remote_request_handlers() {
3632
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3633
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3634
	}
3635
3636
	function remote_request_handlers() {
3637
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3638
3639
		switch ( current_filter() ) {
3640
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3641
			$response = $this->upload_handler();
3642
			break;
3643
3644
		case 'wp_ajax_nopriv_jetpack_update_file' :
3645
			$response = $this->upload_handler( true );
3646
			break;
3647
		default :
3648
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3649
			break;
3650
		}
3651
3652
		if ( ! $response ) {
3653
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3654
		}
3655
3656
		if ( is_wp_error( $response ) ) {
3657
			$status_code       = $response->get_error_data();
3658
			$error             = $response->get_error_code();
3659
			$error_description = $response->get_error_message();
3660
3661
			if ( ! is_int( $status_code ) ) {
3662
				$status_code = 400;
3663
			}
3664
3665
			status_header( $status_code );
3666
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3667
		}
3668
3669
		status_header( 200 );
3670
		if ( true === $response ) {
3671
			exit;
3672
		}
3673
3674
		die( json_encode( (object) $response ) );
3675
	}
3676
3677
	/**
3678
	 * Uploads a file gotten from the global $_FILES.
3679
	 * If `$update_media_item` is true and `post_id` is defined
3680
	 * the attachment file of the media item (gotten through of the post_id)
3681
	 * will be updated instead of add a new one.
3682
	 *
3683
	 * @param  boolean $update_media_item - update media attachment
3684
	 * @return array - An array describing the uploadind files process
3685
	 */
3686
	function upload_handler( $update_media_item = false ) {
3687
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3688
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3689
		}
3690
3691
		$user = wp_authenticate( '', '' );
3692
		if ( ! $user || is_wp_error( $user ) ) {
3693
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3694
		}
3695
3696
		wp_set_current_user( $user->ID );
3697
3698
		if ( ! current_user_can( 'upload_files' ) ) {
3699
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3700
		}
3701
3702
		if ( empty( $_FILES ) ) {
3703
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3704
		}
3705
3706
		foreach ( array_keys( $_FILES ) as $files_key ) {
3707
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3708
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3709
			}
3710
		}
3711
3712
		$media_keys = array_keys( $_FILES['media'] );
3713
3714
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
3715
		if ( ! $token || is_wp_error( $token ) ) {
3716
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3717
		}
3718
3719
		$uploaded_files = array();
3720
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3721
		unset( $GLOBALS['post'] );
3722
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3723
			$file = array();
3724
			foreach ( $media_keys as $media_key ) {
3725
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3726
			}
3727
3728
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3729
3730
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3731
			if ( $hmac_provided !== $hmac_file ) {
3732
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3733
				continue;
3734
			}
3735
3736
			$_FILES['.jetpack.upload.'] = $file;
3737
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3738
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3739
				$post_id = 0;
3740
			}
3741
3742
			if ( $update_media_item ) {
3743
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3744
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3745
				}
3746
3747
				$media_array = $_FILES['media'];
3748
3749
				$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...
3750
				$file_array['type'] = $media_array['type'][0];
3751
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3752
				$file_array['error'] = $media_array['error'][0];
3753
				$file_array['size'] = $media_array['size'][0];
3754
3755
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3756
3757
				if ( is_wp_error( $edited_media_item ) ) {
3758
					return $edited_media_item;
3759
				}
3760
3761
				$response = (object) array(
3762
					'id'   => (string) $post_id,
3763
					'file' => (string) $edited_media_item->post_title,
3764
					'url'  => (string) wp_get_attachment_url( $post_id ),
3765
					'type' => (string) $edited_media_item->post_mime_type,
3766
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3767
				);
3768
3769
				return (array) array( $response );
3770
			}
3771
3772
			$attachment_id = media_handle_upload(
3773
				'.jetpack.upload.',
3774
				$post_id,
3775
				array(),
3776
				array(
3777
					'action' => 'jetpack_upload_file',
3778
				)
3779
			);
3780
3781
			if ( ! $attachment_id ) {
3782
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3783
			} elseif ( is_wp_error( $attachment_id ) ) {
3784
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3785
			} else {
3786
				$attachment = get_post( $attachment_id );
3787
				$uploaded_files[$index] = (object) array(
3788
					'id'   => (string) $attachment_id,
3789
					'file' => $attachment->post_title,
3790
					'url'  => wp_get_attachment_url( $attachment_id ),
3791
					'type' => $attachment->post_mime_type,
3792
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3793
				);
3794
				// Zip files uploads are not supported unless they are done for installation purposed
3795
				// lets delete them in case something goes wrong in this whole process
3796
				if ( 'application/zip' === $attachment->post_mime_type ) {
3797
					// Schedule a cleanup for 2 hours from now in case of failed install.
3798
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3799
				}
3800
			}
3801
		}
3802
		if ( ! is_null( $global_post ) ) {
3803
			$GLOBALS['post'] = $global_post;
3804
		}
3805
3806
		return $uploaded_files;
3807
	}
3808
3809
	/**
3810
	 * Add help to the Jetpack page
3811
	 *
3812
	 * @since Jetpack (1.2.3)
3813
	 * @return false if not the Jetpack page
3814
	 */
3815
	function admin_help() {
3816
		$current_screen = get_current_screen();
3817
3818
		// Overview
3819
		$current_screen->add_help_tab(
3820
			array(
3821
				'id'		=> 'home',
3822
				'title'		=> __( 'Home', 'jetpack' ),
3823
				'content'	=>
3824
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3825
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3826
					'<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>',
3827
			)
3828
		);
3829
3830
		// Screen Content
3831
		if ( current_user_can( 'manage_options' ) ) {
3832
			$current_screen->add_help_tab(
3833
				array(
3834
					'id'		=> 'settings',
3835
					'title'		=> __( 'Settings', 'jetpack' ),
3836
					'content'	=>
3837
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3838
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3839
						'<ol>' .
3840
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3841
							'<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>' .
3842
						'</ol>' .
3843
						'<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>'
3844
				)
3845
			);
3846
		}
3847
3848
		// Help Sidebar
3849
		$current_screen->set_help_sidebar(
3850
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3851
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3852
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3853
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3854
		);
3855
	}
3856
3857
	function admin_menu_css() {
3858
		wp_enqueue_style( 'jetpack-icons' );
3859
	}
3860
3861
	function admin_menu_order() {
3862
		return true;
3863
	}
3864
3865 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3866
		$jp_menu_order = array();
3867
3868
		foreach ( $menu_order as $index => $item ) {
3869
			if ( $item != 'jetpack' ) {
3870
				$jp_menu_order[] = $item;
3871
			}
3872
3873
			if ( $index == 0 ) {
3874
				$jp_menu_order[] = 'jetpack';
3875
			}
3876
		}
3877
3878
		return $jp_menu_order;
3879
	}
3880
3881
	function admin_banner_styles() {
3882
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3883
3884
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3885
			wp_register_style(
3886
				'jetpack-dops-style',
3887
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3888
				array(),
3889
				JETPACK__VERSION
3890
			);
3891
		}
3892
3893
		wp_enqueue_style(
3894
			'jetpack',
3895
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3896
			array( 'jetpack-dops-style' ),
3897
			 JETPACK__VERSION . '-20121016'
3898
		);
3899
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3900
		wp_style_add_data( 'jetpack', 'suffix', $min );
3901
	}
3902
3903
	function plugin_action_links( $actions ) {
3904
3905
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3906
3907
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3908
			return array_merge(
3909
				$jetpack_home,
3910
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3911
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3912
				$actions
3913
				);
3914
			}
3915
3916
		return array_merge( $jetpack_home, $actions );
3917
	}
3918
3919
	/*
3920
	 * Registration flow:
3921
	 * 1 - ::admin_page_load() action=register
3922
	 * 2 - ::try_registration()
3923
	 * 3 - ::register()
3924
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3925
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3926
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3927
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3928
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3929
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3930
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3931
	 *       jetpack_id, jetpack_secret, jetpack_public
3932
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3933
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3934
	 * 5 - user logs in with WP.com account
3935
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3936
	 *		- Jetpack_Client_Server::authorize()
3937
	 *		- Jetpack_Client_Server::get_token()
3938
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3939
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3940
	 *			- which responds with access_token, token_type, scope
3941
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3942
	 *		- Jetpack::activate_default_modules()
3943
	 *     		- Deactivates deprecated plugins
3944
	 *     		- Activates all default modules
3945
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3946
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3947
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3948
	 *     Done!
3949
	 */
3950
3951
	/**
3952
	 * Handles the page load events for the Jetpack admin page
3953
	 */
3954
	function admin_page_load() {
3955
		$error = false;
3956
3957
		// Make sure we have the right body class to hook stylings for subpages off of.
3958
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3959
3960
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3961
			// Should only be used in intermediate redirects to preserve state across redirects
3962
			Jetpack::restate();
3963
		}
3964
3965
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3966
			// @todo: Add validation against a known whitelist
3967
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3968
			// User clicked in the iframe to link their accounts
3969
			if ( ! Jetpack::is_user_connected() ) {
3970
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3971
3972
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3973
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3974
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3975
3976
				if ( isset( $_GET['notes_iframe'] ) )
3977
					$connect_url .= '&notes_iframe';
3978
				wp_redirect( $connect_url );
3979
				exit;
3980
			} else {
3981
				if ( ! isset( $_GET['calypso_env'] ) ) {
3982
					Jetpack::state( 'message', 'already_authorized' );
3983
					wp_safe_redirect( Jetpack::admin_url() );
3984
					exit;
3985
				} else {
3986
					$connect_url = $this->build_connect_url( true, false, $from );
3987
					$connect_url .= '&already_authorized=true';
3988
					wp_redirect( $connect_url );
3989
					exit;
3990
				}
3991
			}
3992
		}
3993
3994
3995
		if ( isset( $_GET['action'] ) ) {
3996
			switch ( $_GET['action'] ) {
3997
			case 'authorize':
3998
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3999
					Jetpack::state( 'message', 'already_authorized' );
4000
					wp_safe_redirect( Jetpack::admin_url() );
4001
					exit;
4002
				}
4003
				Jetpack::log( 'authorize' );
4004
				$client_server = new Jetpack_Client_Server;
4005
				$client_server->client_authorize();
4006
				exit;
4007
			case 'register' :
4008
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4009
					$error = 'cheatin';
4010
					break;
4011
				}
4012
				check_admin_referer( 'jetpack-register' );
4013
				Jetpack::log( 'register' );
4014
				Jetpack::maybe_set_version_option();
4015
				$registered = Jetpack::try_registration();
4016
				if ( is_wp_error( $registered ) ) {
4017
					$error = $registered->get_error_code();
4018
					Jetpack::state( 'error', $error );
4019
					Jetpack::state( 'error', $registered->get_error_message() );
4020
					do_action( 'jpc_register_fail', $error );
4021
					break;
4022
				}
4023
4024
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4025
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4026
4027
				do_action( 'jpc_register_success', $from );
4028
4029
				$url = $this->build_connect_url( true, $redirect, $from );
4030
4031
				if ( ! empty( $_GET['onboarding'] ) ) {
4032
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4033
				}
4034
4035
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4036
					$url = add_query_arg( 'auth_approved', 'true', $url );
4037
				}
4038
4039
				wp_redirect( $url );
4040
				exit;
4041
			case 'activate' :
4042
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4043
					$error = 'cheatin';
4044
					break;
4045
				}
4046
4047
				$module = stripslashes( $_GET['module'] );
4048
				check_admin_referer( "jetpack_activate-$module" );
4049
				Jetpack::log( 'activate', $module );
4050
				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...
4051
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4052
				}
4053
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4054
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4055
				exit;
4056
			case 'activate_default_modules' :
4057
				check_admin_referer( 'activate_default_modules' );
4058
				Jetpack::log( 'activate_default_modules' );
4059
				Jetpack::restate();
4060
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4061
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4062
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4063
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4064
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4065
				exit;
4066
			case 'disconnect' :
4067
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4068
					$error = 'cheatin';
4069
					break;
4070
				}
4071
4072
				check_admin_referer( 'jetpack-disconnect' );
4073
				Jetpack::log( 'disconnect' );
4074
				Jetpack::disconnect();
4075
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4076
				exit;
4077
			case 'reconnect' :
4078
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4079
					$error = 'cheatin';
4080
					break;
4081
				}
4082
4083
				check_admin_referer( 'jetpack-reconnect' );
4084
				Jetpack::log( 'reconnect' );
4085
				$this->disconnect();
4086
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4087
				exit;
4088 View Code Duplication
			case 'deactivate' :
4089
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4090
					$error = 'cheatin';
4091
					break;
4092
				}
4093
4094
				$modules = stripslashes( $_GET['module'] );
4095
				check_admin_referer( "jetpack_deactivate-$modules" );
4096
				foreach ( explode( ',', $modules ) as $module ) {
4097
					Jetpack::log( 'deactivate', $module );
4098
					Jetpack::deactivate_module( $module );
4099
					Jetpack::state( 'message', 'module_deactivated' );
4100
				}
4101
				Jetpack::state( 'module', $modules );
4102
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4103
				exit;
4104
			case 'unlink' :
4105
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4106
				check_admin_referer( 'jetpack-unlink' );
4107
				Jetpack::log( 'unlink' );
4108
				$this->unlink_user();
4109
				Jetpack::state( 'message', 'unlinked' );
4110
				if ( 'sub-unlink' == $redirect ) {
4111
					wp_safe_redirect( admin_url() );
4112
				} else {
4113
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4114
				}
4115
				exit;
4116
			case 'onboard' :
4117
				if ( ! current_user_can( 'manage_options' ) ) {
4118
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4119
				} else {
4120
					Jetpack::create_onboarding_token();
4121
					$url = $this->build_connect_url( true );
4122
4123
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4124
						$url = add_query_arg( 'onboarding', $token, $url );
4125
					}
4126
4127
					$calypso_env = $this->get_calypso_env();
4128
					if ( ! empty( $calypso_env ) ) {
4129
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4130
					}
4131
4132
					wp_redirect( $url );
4133
					exit;
4134
				}
4135
				exit;
4136
			default:
4137
				/**
4138
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4139
				 *
4140
				 * @since 2.6.0
4141
				 *
4142
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4143
				 */
4144
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4145
			}
4146
		}
4147
4148
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4149
			self::activate_new_modules( true );
4150
		}
4151
4152
		$message_code = Jetpack::state( 'message' );
4153
		if ( Jetpack::state( 'optin-manage' ) ) {
4154
			$activated_manage = $message_code;
4155
			$message_code = 'jetpack-manage';
4156
		}
4157
4158
		switch ( $message_code ) {
4159
		case 'jetpack-manage':
4160
			$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>';
4161
			if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4162
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4163
			}
4164
			break;
4165
4166
		}
4167
4168
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4169
4170
		if ( ! empty( $deactivated_plugins ) ) {
4171
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4172
			$deactivated_titles  = array();
4173
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4174
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4175
					continue;
4176
				}
4177
4178
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4179
			}
4180
4181
			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...
4182
				if ( $this->message ) {
4183
					$this->message .= "<br /><br />\n";
4184
				}
4185
4186
				$this->message .= wp_sprintf(
4187
					_n(
4188
						'Jetpack contains the most recent version of the old %l plugin.',
4189
						'Jetpack contains the most recent versions of the old %l plugins.',
4190
						count( $deactivated_titles ),
4191
						'jetpack'
4192
					),
4193
					$deactivated_titles
4194
				);
4195
4196
				$this->message .= "<br />\n";
4197
4198
				$this->message .= _n(
4199
					'The old version has been deactivated and can be removed from your site.',
4200
					'The old versions have been deactivated and can be removed from your site.',
4201
					count( $deactivated_titles ),
4202
					'jetpack'
4203
				);
4204
			}
4205
		}
4206
4207
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4208
4209
		if ( $this->message || $this->error || $this->privacy_checks ) {
4210
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4211
		}
4212
4213
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4214
	}
4215
4216
	function admin_notices() {
4217
4218
		if ( $this->error ) {
4219
?>
4220
<div id="message" class="jetpack-message jetpack-err">
4221
	<div class="squeezer">
4222
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4223
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4224
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4225
<?php	endif; ?>
4226
	</div>
4227
</div>
4228
<?php
4229
		}
4230
4231
		if ( $this->message ) {
4232
?>
4233
<div id="message" class="jetpack-message">
4234
	<div class="squeezer">
4235
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4236
	</div>
4237
</div>
4238
<?php
4239
		}
4240
4241
		if ( $this->privacy_checks ) :
4242
			$module_names = $module_slugs = array();
4243
4244
			$privacy_checks = explode( ',', $this->privacy_checks );
4245
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4246
			foreach ( $privacy_checks as $module_slug ) {
4247
				$module = Jetpack::get_module( $module_slug );
4248
				if ( ! $module ) {
4249
					continue;
4250
				}
4251
4252
				$module_slugs[] = $module_slug;
4253
				$module_names[] = "<strong>{$module['name']}</strong>";
4254
			}
4255
4256
			$module_slugs = join( ',', $module_slugs );
4257
?>
4258
<div id="message" class="jetpack-message jetpack-err">
4259
	<div class="squeezer">
4260
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4261
		<p><?php
4262
			echo wp_kses(
4263
				wptexturize(
4264
					wp_sprintf(
4265
						_nx(
4266
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4267
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4268
							count( $privacy_checks ),
4269
							'%l = list of Jetpack module/feature names',
4270
							'jetpack'
4271
						),
4272
						$module_names
4273
					)
4274
				),
4275
				array( 'strong' => true )
4276
			);
4277
4278
			echo "\n<br />\n";
4279
4280
			echo wp_kses(
4281
				sprintf(
4282
					_nx(
4283
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4284
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4285
						count( $privacy_checks ),
4286
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4287
						'jetpack'
4288
					),
4289
					wp_nonce_url(
4290
						Jetpack::admin_url(
4291
							array(
4292
								'page'   => 'jetpack',
4293
								'action' => 'deactivate',
4294
								'module' => urlencode( $module_slugs ),
4295
							)
4296
						),
4297
						"jetpack_deactivate-$module_slugs"
4298
					),
4299
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4300
				),
4301
				array( 'a' => array( 'href' => true, 'title' => true ) )
4302
			);
4303
		?></p>
4304
	</div>
4305
</div>
4306
<?php endif;
4307
	}
4308
4309
	/**
4310
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4311
	 */
4312
	function stat( $group, $detail ) {
4313
		if ( ! isset( $this->stats[ $group ] ) )
4314
			$this->stats[ $group ] = array();
4315
		$this->stats[ $group ][] = $detail;
4316
	}
4317
4318
	/**
4319
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4320
	 */
4321
	function do_stats( $method = '' ) {
4322
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4323
			foreach ( $this->stats as $group => $stats ) {
4324
				if ( is_array( $stats ) && count( $stats ) ) {
4325
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4326
					if ( 'server_side' === $method ) {
4327
						self::do_server_side_stat( $args );
4328
					} else {
4329
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4330
					}
4331
				}
4332
				unset( $this->stats[ $group ] );
4333
			}
4334
		}
4335
	}
4336
4337
	/**
4338
	 * Runs stats code for a one-off, server-side.
4339
	 *
4340
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4341
	 *
4342
	 * @return bool If it worked.
4343
	 */
4344
	static function do_server_side_stat( $args ) {
4345
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4346
		if ( is_wp_error( $response ) )
4347
			return false;
4348
4349
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4350
			return false;
4351
4352
		return true;
4353
	}
4354
4355
	/**
4356
	 * Builds the stats url.
4357
	 *
4358
	 * @param $args array|string The arguments to append to the URL.
4359
	 *
4360
	 * @return string The URL to be pinged.
4361
	 */
4362
	static function build_stats_url( $args ) {
4363
		$defaults = array(
4364
			'v'    => 'wpcom2',
4365
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4366
		);
4367
		$args     = wp_parse_args( $args, $defaults );
4368
		/**
4369
		 * Filter the URL used as the Stats tracking pixel.
4370
		 *
4371
		 * @since 2.3.2
4372
		 *
4373
		 * @param string $url Base URL used as the Stats tracking pixel.
4374
		 */
4375
		$base_url = apply_filters(
4376
			'jetpack_stats_base_url',
4377
			'https://pixel.wp.com/g.gif'
4378
		);
4379
		$url      = add_query_arg( $args, $base_url );
4380
		return $url;
4381
	}
4382
4383
	static function translate_current_user_to_role() {
4384
		foreach ( self::$capability_translations as $role => $cap ) {
4385
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4386
				return $role;
4387
			}
4388
		}
4389
4390
		return false;
4391
	}
4392
4393
	static function translate_user_to_role( $user ) {
4394
		foreach ( self::$capability_translations as $role => $cap ) {
4395
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4396
				return $role;
4397
			}
4398
		}
4399
4400
		return false;
4401
    }
4402
4403
	static function translate_role_to_cap( $role ) {
4404
		if ( ! isset( self::$capability_translations[$role] ) ) {
4405
			return false;
4406
		}
4407
4408
		return self::$capability_translations[$role];
4409
	}
4410
4411
	static function sign_role( $role, $user_id = null ) {
4412
		if ( empty( $user_id ) ) {
4413
			$user_id = (int) get_current_user_id();
4414
		}
4415
4416
		if ( ! $user_id  ) {
4417
			return false;
4418
		}
4419
4420
		$token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4421
		if ( ! $token || is_wp_error( $token ) ) {
4422
			return false;
4423
		}
4424
4425
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4426
	}
4427
4428
4429
	/**
4430
	 * Builds a URL to the Jetpack connection auth page
4431
	 *
4432
	 * @since 3.9.5
4433
	 *
4434
	 * @param bool $raw If true, URL will not be escaped.
4435
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4436
	 *                              If string, will be a custom redirect.
4437
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4438
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4439
	 *
4440
	 * @return string Connect URL
4441
	 */
4442
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4443
		$site_id = Jetpack_Options::get_option( 'id' );
4444
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

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

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
5130
	 */
5131
	public static function maybe_set_version_option() {
5132
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5133
		if ( JETPACK__VERSION != $version ) {
5134
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5135
5136
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5137
				/** This action is documented in class.jetpack.php */
5138
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5139
			}
5140
5141
			return true;
5142
		}
5143
		return false;
5144
	}
5145
5146
/* Client Server API */
5147
5148
	/**
5149
	 * Loads the Jetpack XML-RPC client
5150
	 */
5151
	public static function load_xml_rpc_client() {
5152
		require_once ABSPATH . WPINC . '/class-IXR.php';
5153
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5154
	}
5155
5156
	/**
5157
	 * Resets the saved authentication state in between testing requests.
5158
	 */
5159
	public function reset_saved_auth_state() {
5160
		$this->xmlrpc_verification = null;
5161
		$this->rest_authentication_status = null;
5162
	}
5163
5164
	function verify_xml_rpc_signature() {
5165
		if ( $this->xmlrpc_verification ) {
5166
			return $this->xmlrpc_verification;
5167
		}
5168
5169
		// It's not for us
5170
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5171
			return false;
5172
		}
5173
5174
		@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...
5175
		if (
5176
			empty( $token_key )
5177
		||
5178
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5179
		) {
5180
			return false;
5181
		}
5182
5183
		if ( '0' === $user_id ) {
5184
			$token_type = 'blog';
5185
			$user_id = 0;
5186
		} else {
5187
			$token_type = 'user';
5188
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5189
				return false;
5190
			}
5191
			$user_id = (int) $user_id;
5192
5193
			$user = new WP_User( $user_id );
5194
			if ( ! $user || ! $user->exists() ) {
5195
				return false;
5196
			}
5197
		}
5198
5199
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
0 ignored issues
show
Documentation introduced by
$user_id is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
5200
		if ( ! $token ) {
5201
			return false;
5202
		}
5203
5204
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5205
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5206
			$post_data   = $_POST;
5207
			$file_hashes = array();
5208
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5209
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5210
					continue;
5211
				}
5212
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5213
				$file_hashes[$post_data_key] = $post_data_value;
5214
			}
5215
5216
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5217
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5218
				$post_data[$post_data_key] = $post_data_value;
5219
			}
5220
5221
			ksort( $post_data );
5222
5223
			$body = http_build_query( stripslashes_deep( $post_data ) );
5224
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5225
			$body = file_get_contents( 'php://input' );
5226
		} else {
5227
			$body = null;
5228
		}
5229
5230
		$signature = $jetpack_signature->sign_current_request(
5231
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5232
		);
5233
5234
		if ( ! $signature ) {
5235
			return false;
5236
		} else if ( is_wp_error( $signature ) ) {
5237
			return $signature;
5238
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5239
			return false;
5240
		}
5241
5242
		$timestamp = (int) $_GET['timestamp'];
5243
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5244
5245
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5246
			return false;
5247
		}
5248
5249
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5250
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5251
			if ( ! empty( $_GET['onboarding'] ) ) {
5252
				$jpo = $_GET;
5253
			} else {
5254
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5255
			}
5256
5257
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5258
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5259
5260
			if (
5261
				isset( $jpo_user ) && isset( $jpo_token ) &&
5262
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5263
				isset( $_GET['rest_route'] ) &&
5264
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5265
			) {
5266
				$jpUser = get_user_by( 'email', $jpo_user );
5267
				if ( is_a( $jpUser, 'WP_User' ) ) {
5268
					wp_set_current_user( $jpUser->ID );
5269
					$user_can = is_multisite()
5270
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5271
						: current_user_can( 'manage_options' );
5272
					if ( $user_can ) {
5273
						$token_type = 'user';
5274
						$token->external_user_id = $jpUser->ID;
5275
					}
5276
				}
5277
			}
5278
		}
5279
5280
		$this->xmlrpc_verification = array(
5281
			'type'      => $token_type,
5282
			'token_key' => $token_key,
5283
			'user_id'   => $token->external_user_id,
5284
		);
5285
5286
		return $this->xmlrpc_verification;
5287
	}
5288
5289
	/**
5290
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5291
	 */
5292
	function authenticate_jetpack( $user, $username, $password ) {
5293
		if ( is_a( $user, 'WP_User' ) ) {
5294
			return $user;
5295
		}
5296
5297
		$token_details = $this->verify_xml_rpc_signature();
5298
5299
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5300
			return $user;
5301
		}
5302
5303
		if ( 'user' !== $token_details['type'] ) {
5304
			return $user;
5305
		}
5306
5307
		if ( ! $token_details['user_id'] ) {
5308
			return $user;
5309
		}
5310
5311
		nocache_headers();
5312
5313
		return new WP_User( $token_details['user_id'] );
5314
	}
5315
5316
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5317
	// Uses the existing XMLRPC request signing implementation.
5318
	function wp_rest_authenticate( $user ) {
5319
		if ( ! empty( $user ) ) {
5320
			// Another authentication method is in effect.
5321
			return $user;
5322
		}
5323
5324
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5325
			// Nothing to do for this authentication method.
5326
			return null;
5327
		}
5328
5329
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5330
			// Nothing to do for this authentication method.
5331
			return null;
5332
		}
5333
5334
		// Ensure that we always have the request body available.  At this
5335
		// point, the WP REST API code to determine the request body has not
5336
		// run yet.  That code may try to read from 'php://input' later, but
5337
		// this can only be done once per request in PHP versions prior to 5.6.
5338
		// So we will go ahead and perform this read now if needed, and save
5339
		// the request body where both the Jetpack signature verification code
5340
		// and the WP REST API code can see it.
5341
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5342
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5343
		}
5344
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5345
5346
		// Only support specific request parameters that have been tested and
5347
		// are known to work with signature verification.  A different method
5348
		// can be passed to the WP REST API via the '?_method=' parameter if
5349
		// needed.
5350
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5351
			$this->rest_authentication_status = new WP_Error(
5352
				'rest_invalid_request',
5353
				__( 'This request method is not supported.', 'jetpack' ),
5354
				array( 'status' => 400 )
5355
			);
5356
			return null;
5357
		}
5358
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5359
			$this->rest_authentication_status = new WP_Error(
5360
				'rest_invalid_request',
5361
				__( 'This request method does not support body parameters.', 'jetpack' ),
5362
				array( 'status' => 400 )
5363
			);
5364
			return null;
5365
		}
5366
5367
		$verified = $this->verify_xml_rpc_signature();
5368
5369
		if ( is_wp_error( $verified ) ) {
5370
			$this->rest_authentication_status = $verified;
5371
			return null;
5372
		}
5373
5374
		if (
5375
			$verified &&
5376
			isset( $verified['type'] ) &&
5377
			'user' === $verified['type'] &&
5378
			! empty( $verified['user_id'] )
5379
		) {
5380
			// Authentication successful.
5381
			$this->rest_authentication_status = true;
5382
			return $verified['user_id'];
5383
		}
5384
5385
		// Something else went wrong.  Probably a signature error.
5386
		$this->rest_authentication_status = new WP_Error(
5387
			'rest_invalid_signature',
5388
			__( 'The request is not signed correctly.', 'jetpack' ),
5389
			array( 'status' => 400 )
5390
		);
5391
		return null;
5392
	}
5393
5394
	/**
5395
	 * Report authentication status to the WP REST API.
5396
	 *
5397
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
5398
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5399
	 */
5400
	public function wp_rest_authentication_errors( $value ) {
5401
		if ( $value !== null ) {
5402
			return $value;
5403
		}
5404
		return $this->rest_authentication_status;
5405
	}
5406
5407
	function add_nonce( $timestamp, $nonce ) {
5408
		global $wpdb;
5409
		static $nonces_used_this_request = array();
5410
5411
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5412
			return $nonces_used_this_request["$timestamp:$nonce"];
5413
		}
5414
5415
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5416
		$timestamp = (int) $timestamp;
5417
		$nonce     = esc_sql( $nonce );
5418
5419
		// Raw query so we can avoid races: add_option will also update
5420
		$show_errors = $wpdb->show_errors( false );
5421
5422
		$old_nonce = $wpdb->get_row(
5423
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5424
		);
5425
5426
		if ( is_null( $old_nonce ) ) {
5427
			$return = $wpdb->query(
5428
				$wpdb->prepare(
5429
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5430
					"jetpack_nonce_{$timestamp}_{$nonce}",
5431
					time(),
5432
					'no'
5433
				)
5434
			);
5435
		} else {
5436
			$return = false;
5437
		}
5438
5439
		$wpdb->show_errors( $show_errors );
5440
5441
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5442
5443
		return $return;
5444
	}
5445
5446
	/**
5447
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5448
	 * Capture it here so we can verify the signature later.
5449
	 */
5450
	function xmlrpc_methods( $methods ) {
5451
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5452
		return $methods;
5453
	}
5454
5455
	function public_xmlrpc_methods( $methods ) {
5456
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5457
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5458
		}
5459
		return $methods;
5460
	}
5461
5462
	function jetpack_getOptions( $args ) {
5463
		global $wp_xmlrpc_server;
5464
5465
		$wp_xmlrpc_server->escape( $args );
5466
5467
		$username	= $args[1];
5468
		$password	= $args[2];
5469
5470
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5471
			return $wp_xmlrpc_server->error;
5472
		}
5473
5474
		$options = array();
5475
		$user_data = $this->get_connected_user_data();
5476
		if ( is_array( $user_data ) ) {
5477
			$options['jetpack_user_id'] = array(
5478
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5479
				'readonly'      => true,
5480
				'value'         => $user_data['ID'],
5481
			);
5482
			$options['jetpack_user_login'] = array(
5483
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5484
				'readonly'      => true,
5485
				'value'         => $user_data['login'],
5486
			);
5487
			$options['jetpack_user_email'] = array(
5488
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5489
				'readonly'      => true,
5490
				'value'         => $user_data['email'],
5491
			);
5492
			$options['jetpack_user_site_count'] = array(
5493
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5494
				'readonly'      => true,
5495
				'value'         => $user_data['site_count'],
5496
			);
5497
		}
5498
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5499
		$args = stripslashes_deep( $args );
5500
		return $wp_xmlrpc_server->wp_getOptions( $args );
5501
	}
5502
5503
	function xmlrpc_options( $options ) {
5504
		$jetpack_client_id = false;
5505
		if ( self::is_active() ) {
5506
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5507
		}
5508
		$options['jetpack_version'] = array(
5509
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5510
				'readonly'      => true,
5511
				'value'         => JETPACK__VERSION,
5512
		);
5513
5514
		$options['jetpack_client_id'] = array(
5515
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5516
				'readonly'      => true,
5517
				'value'         => $jetpack_client_id,
5518
		);
5519
		return $options;
5520
	}
5521
5522
	public static function clean_nonces( $all = false ) {
5523
		global $wpdb;
5524
5525
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5526
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5527
5528
		if ( true !== $all ) {
5529
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5530
			$sql_args[] = time() - 3600;
5531
		}
5532
5533
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5534
5535
		$sql = $wpdb->prepare( $sql, $sql_args );
5536
5537
		for ( $i = 0; $i < 1000; $i++ ) {
5538
			if ( ! $wpdb->query( $sql ) ) {
5539
				break;
5540
			}
5541
		}
5542
	}
5543
5544
	/**
5545
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5546
	 * SET: state( $key, $value );
5547
	 * GET: $value = state( $key );
5548
	 *
5549
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

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

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

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

Loading history...
5550
	 * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

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

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

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

Loading history...
5551
	 * @param bool $restate private
5552
	 */
5553
	public static function state( $key = null, $value = null, $restate = false ) {
5554
		static $state = array();
5555
		static $path, $domain;
5556
		if ( ! isset( $path ) ) {
5557
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5558
			$admin_url = Jetpack::admin_url();
5559
			$bits      = wp_parse_url( $admin_url );
5560
5561
			if ( is_array( $bits ) ) {
5562
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5563
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5564
			} else {
5565
				$path = $domain = null;
5566
			}
5567
		}
5568
5569
		// Extract state from cookies and delete cookies
5570
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5571
			$yum = $_COOKIE[ 'jetpackState' ];
5572
			unset( $_COOKIE[ 'jetpackState' ] );
5573
			foreach ( $yum as $k => $v ) {
5574
				if ( strlen( $v ) )
5575
					$state[ $k ] = $v;
5576
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5577
			}
5578
		}
5579
5580
		if ( $restate ) {
5581
			foreach ( $state as $k => $v ) {
5582
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5583
			}
5584
			return;
5585
		}
5586
5587
		// Get a state variable
5588
		if ( isset( $key ) && ! isset( $value ) ) {
5589
			if ( array_key_exists( $key, $state ) )
5590
				return $state[ $key ];
5591
			return null;
5592
		}
5593
5594
		// Set a state variable
5595
		if ( isset ( $key ) && isset( $value ) ) {
5596
			if( is_array( $value ) && isset( $value[0] ) ) {
5597
				$value = $value[0];
5598
			}
5599
			$state[ $key ] = $value;
5600
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5601
		}
5602
	}
5603
5604
	public static function restate() {
5605
		Jetpack::state( null, null, true );
5606
	}
5607
5608
	public static function check_privacy( $file ) {
5609
		static $is_site_publicly_accessible = null;
5610
5611
		if ( is_null( $is_site_publicly_accessible ) ) {
5612
			$is_site_publicly_accessible = false;
5613
5614
			Jetpack::load_xml_rpc_client();
5615
			$rpc = new Jetpack_IXR_Client();
5616
5617
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5618
			if ( $success ) {
5619
				$response = $rpc->getResponse();
5620
				if ( $response ) {
5621
					$is_site_publicly_accessible = true;
5622
				}
5623
			}
5624
5625
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5626
		}
5627
5628
		if ( $is_site_publicly_accessible ) {
5629
			return;
5630
		}
5631
5632
		$module_slug = self::get_module_slug( $file );
5633
5634
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5635
		if ( ! $privacy_checks ) {
5636
			$privacy_checks = $module_slug;
5637
		} else {
5638
			$privacy_checks .= ",$module_slug";
5639
		}
5640
5641
		Jetpack::state( 'privacy_checks', $privacy_checks );
5642
	}
5643
5644
	/**
5645
	 * Helper method for multicall XMLRPC.
5646
	 */
5647
	public static function xmlrpc_async_call() {
5648
		global $blog_id;
5649
		static $clients = array();
5650
5651
		$client_blog_id = is_multisite() ? $blog_id : 0;
5652
5653
		if ( ! isset( $clients[$client_blog_id] ) ) {
5654
			Jetpack::load_xml_rpc_client();
5655
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5656
			if ( function_exists( 'ignore_user_abort' ) ) {
5657
				ignore_user_abort( true );
5658
			}
5659
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5660
		}
5661
5662
		$args = func_get_args();
5663
5664
		if ( ! empty( $args[0] ) ) {
5665
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5666
		} elseif ( is_multisite() ) {
5667
			foreach ( $clients as $client_blog_id => $client ) {
5668
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5669
					continue;
5670
				}
5671
5672
				$switch_success = switch_to_blog( $client_blog_id, true );
5673
				if ( ! $switch_success ) {
5674
					continue;
5675
				}
5676
5677
				flush();
5678
				$client->query();
5679
5680
				restore_current_blog();
5681
			}
5682
		} else {
5683
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5684
				flush();
5685
				$clients[0]->query();
5686
			}
5687
		}
5688
	}
5689
5690
	public static function staticize_subdomain( $url ) {
5691
5692
		// Extract hostname from URL
5693
		$host = parse_url( $url, PHP_URL_HOST );
5694
5695
		// Explode hostname on '.'
5696
		$exploded_host = explode( '.', $host );
5697
5698
		// Retrieve the name and TLD
5699
		if ( count( $exploded_host ) > 1 ) {
5700
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5701
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5702
			// Rebuild domain excluding subdomains
5703
			$domain = $name . '.' . $tld;
5704
		} else {
5705
			$domain = $host;
5706
		}
5707
		// Array of Automattic domains
5708
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5709
5710
		// Return $url if not an Automattic domain
5711
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5712
			return $url;
5713
		}
5714
5715
		if ( is_ssl() ) {
5716
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5717
		}
5718
5719
		srand( crc32( basename( $url ) ) );
5720
		$static_counter = rand( 0, 2 );
5721
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5722
5723
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5724
	}
5725
5726
/* JSON API Authorization */
5727
5728
	/**
5729
	 * Handles the login action for Authorizing the JSON API
5730
	 */
5731
	function login_form_json_api_authorization() {
5732
		$this->verify_json_api_authorization_request();
5733
5734
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5735
5736
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5737
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5738
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5739
	}
5740
5741
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5742
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5743
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5744
			return $url;
5745
		}
5746
5747
		$parsed_url = parse_url( $url );
5748
		$url = strtok( $url, '?' );
5749
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5750
		if ( ! empty( $parsed_url['query'] ) )
5751
			$url .= "&{$parsed_url['query']}";
5752
5753
		return $url;
5754
	}
5755
5756
	// Make sure the POSTed request is handled by the same action
5757
	function preserve_action_in_login_form_for_json_api_authorization() {
5758
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5759
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5760
	}
5761
5762
	// If someone logs in to approve API access, store the Access Code in usermeta
5763
	function store_json_api_authorization_token( $user_login, $user ) {
5764
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5765
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5766
		$token = wp_generate_password( 32, false );
5767
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5768
	}
5769
5770
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5771
	function allow_wpcom_public_api_domain( $domains ) {
5772
		$domains[] = 'public-api.wordpress.com';
5773
		return $domains;
5774
	}
5775
5776
	static function is_redirect_encoded( $redirect_url ) {
5777
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5778
	}
5779
5780
	// Add all wordpress.com environments to the safe redirect whitelist
5781
	function allow_wpcom_environments( $domains ) {
5782
		$domains[] = 'wordpress.com';
5783
		$domains[] = 'wpcalypso.wordpress.com';
5784
		$domains[] = 'horizon.wordpress.com';
5785
		$domains[] = 'calypso.localhost';
5786
		return $domains;
5787
	}
5788
5789
	// Add the Access Code details to the public-api.wordpress.com redirect
5790
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5791
		return add_query_arg(
5792
			urlencode_deep(
5793
				array(
5794
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5795
					'jetpack-user-id' => (int) $user->ID,
5796
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5797
				)
5798
			),
5799
			$redirect_to
5800
		);
5801
	}
5802
5803
5804
	/**
5805
	 * Verifies the request by checking the signature
5806
	 *
5807
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5808
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5809
	 *
5810
	 * @param null|array $environment
5811
	 */
5812
	function verify_json_api_authorization_request( $environment = null ) {
5813
		$environment = is_null( $environment )
5814
			? $_REQUEST
5815
			: $environment;
5816
5817
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

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

Loading history...
5819
		if ( ! $token || empty( $token->secret ) ) {
5820
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5821
		}
5822
5823
		$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' );
5824
5825
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5826
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5827
		    do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
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
				'#\.stage\.site$#i'             // DreamPress
5991
			),
5992
			'constants' => array(
5993
				'IS_WPE_SNAPSHOT',      // WP Engine
5994
				'KINSTA_DEV_ENV',       // Kinsta.com
5995
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5996
				'JETPACK_STAGING_MODE', // Generic
5997
			)
5998
		);
5999
		/**
6000
		 * Filters the flags of known staging sites.
6001
		 *
6002
		 * @since 3.9.0
6003
		 *
6004
		 * @param array $known_staging {
6005
		 *     An array of arrays that each are used to check if the current site is staging.
6006
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6007
		 *     @type array $constants PHP constants of known staging/developement environments.
6008
		 *  }
6009
		 */
6010
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6011
6012
		if ( isset( $known_staging['urls'] ) ) {
6013
			foreach ( $known_staging['urls'] as $url ){
6014
				if ( preg_match( $url, site_url() ) ) {
6015
					$is_staging = true;
6016
					break;
6017
				}
6018
			}
6019
		}
6020
6021
		if ( isset( $known_staging['constants'] ) ) {
6022
			foreach ( $known_staging['constants'] as $constant ) {
6023
				if ( defined( $constant ) && constant( $constant ) ) {
6024
					$is_staging = true;
6025
				}
6026
			}
6027
		}
6028
6029
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6030
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6031
			$is_staging = true;
6032
		}
6033
6034
		/**
6035
		 * Filters is_staging_site check.
6036
		 *
6037
		 * @since 3.9.0
6038
		 *
6039
		 * @param bool $is_staging If the current site is a staging site.
6040
		 */
6041
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6042
	}
6043
6044
	/**
6045
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6046
	 *
6047
	 * @since 4.4.0
6048
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6049
	 *
6050
	 * @return bool
6051
	 */
6052
	public static function validate_sync_error_idc_option() {
6053
		$is_valid = false;
6054
6055
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6056
		if ( false === $idc_allowed ) {
6057
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6058
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6059
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6060
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6061
				$transient_duration = HOUR_IN_SECONDS;
6062
			} else {
6063
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6064
				$idc_allowed = '1';
6065
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6066
			}
6067
6068
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6069
		}
6070
6071
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6072
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6073
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6074
			$local_options = self::get_sync_error_idc_option();
6075
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6076
				$is_valid = true;
6077
			}
6078
		}
6079
6080
		/**
6081
		 * Filters whether the sync_error_idc option is valid.
6082
		 *
6083
		 * @since 4.4.0
6084
		 *
6085
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6086
		 */
6087
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6088
6089
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6090
			// Since the option exists, and did not validate, delete it
6091
			Jetpack_Options::delete_option( 'sync_error_idc' );
6092
		}
6093
6094
		return $is_valid;
6095
	}
6096
6097
	/**
6098
	 * Normalizes a url by doing three things:
6099
	 *  - Strips protocol
6100
	 *  - Strips www
6101
	 *  - Adds a trailing slash
6102
	 *
6103
	 * @since 4.4.0
6104
	 * @param string $url
6105
	 * @return WP_Error|string
6106
	 */
6107
	public static function normalize_url_protocol_agnostic( $url ) {
6108
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6109
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6110
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6111
		}
6112
6113
		// Strip www and protocols
6114
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6115
		return $url;
6116
	}
6117
6118
	/**
6119
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6120
	 *
6121
	 * @since 4.4.0
6122
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6123
	 *
6124
	 * @param array $response
6125
	 * @return array Array of the local urls, wpcom urls, and error code
6126
	 */
6127
	public static function get_sync_error_idc_option( $response = array() ) {
6128
		// Since the local options will hit the database directly, store the values
6129
		// in a transient to allow for autoloading and caching on subsequent views.
6130
		$local_options = get_transient( 'jetpack_idc_local' );
6131
		if ( false === $local_options ) {
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::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6169
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6170
		} else {
6171
			$default = ! Constants::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
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
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
Bug introduced by
There is no parameter named $href. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
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
			$jetpack_logo = new Jetpack_Logo();
6699
			$widget_title = sprintf(
6700
				wp_kses(
6701
					/* translators: Placeholder is a Jetpack logo. */
6702
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6703
					array( 'span' => array() )
6704
				),
6705
				$jetpack_logo->get_jp_emblem( true )
6706
			);
6707
6708
			wp_add_dashboard_widget(
6709
				'jetpack_summary_widget',
6710
				$widget_title,
6711
				array( __CLASS__, 'dashboard_widget' )
6712
			);
6713
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6714
6715
			// If we're inactive and not in development mode, sort our box to the top.
6716
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6717
				global $wp_meta_boxes;
6718
6719
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6720
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6721
6722
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6723
			}
6724
		}
6725
	}
6726
6727
	/**
6728
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6729
	 * @return mixed
6730
	 */
6731
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6732
		if ( ! is_array( $sorted ) ) {
6733
			return $sorted;
6734
		}
6735
6736
		foreach ( $sorted as $box_context => $ids ) {
6737
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6738
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6739
				continue;
6740
			}
6741
6742
			$ids_array = explode( ',', $ids );
6743
			$key = array_search( 'dashboard_stats', $ids_array );
6744
6745
			if ( false !== $key ) {
6746
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6747
				$ids_array[ $key ] = 'jetpack_summary_widget';
6748
				$sorted[ $box_context ] = implode( ',', $ids_array );
6749
				// We've found it, stop searching, and just return.
6750
				break;
6751
			}
6752
		}
6753
6754
		return $sorted;
6755
	}
6756
6757
	public static function dashboard_widget() {
6758
		/**
6759
		 * Fires when the dashboard is loaded.
6760
		 *
6761
		 * @since 3.4.0
6762
		 */
6763
		do_action( 'jetpack_dashboard_widget' );
6764
	}
6765
6766
	public static function dashboard_widget_footer() {
6767
		?>
6768
		<footer>
6769
6770
		<div class="protect">
6771
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6772
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6773
				<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>
6774
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6775
				<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' ); ?>">
6776
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6777
				</a>
6778
			<?php else : ?>
6779
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6780
			<?php endif; ?>
6781
		</div>
6782
6783
		<div class="akismet">
6784
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6785
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6786
				<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>
6787
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6788
				<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">
6789
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6790
				</a>
6791
			<?php else : ?>
6792
				<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>
6793
			<?php endif; ?>
6794
		</div>
6795
6796
		</footer>
6797
		<?php
6798
	}
6799
6800
	/*
6801
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6802
	 */
6803
	function jetpack_icon_user_connected( $columns ) {
6804
		$columns['user_jetpack'] = '';
6805
		return $columns;
6806
	}
6807
6808
	/*
6809
	 * Show Jetpack icon if the user is linked.
6810
	 */
6811
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6812
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6813
			$jetpack_logo = new Jetpack_Logo();
6814
			$emblem_html = sprintf(
6815
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6816
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6817
				$jetpack_logo->get_jp_emblem()
6818
			);
6819
			return $emblem_html;
6820
		}
6821
6822
		return $val;
6823
	}
6824
6825
	/*
6826
	 * Style the Jetpack user column
6827
	 */
6828
	function jetpack_user_col_style() {
6829
		global $current_screen;
6830
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6831
			<style>
6832
				.fixed .column-user_jetpack {
6833
					width: 21px;
6834
				}
6835
				.jp-emblem-user-admin svg {
6836
					width: 20px;
6837
					height: 20px;
6838
				}
6839
				.jp-emblem-user-admin path {
6840
					fill: #00BE28;
6841
				}
6842
			</style>
6843
		<?php }
6844
	}
6845
6846
	/**
6847
	 * Checks if Akismet is active and working.
6848
	 *
6849
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6850
	 * that implied usage of methods present since more recent version.
6851
	 * See https://github.com/Automattic/jetpack/pull/9585
6852
	 *
6853
	 * @since  5.1.0
6854
	 *
6855
	 * @return bool True = Akismet available. False = Aksimet not available.
6856
	 */
6857
	public static function is_akismet_active() {
6858
		static $status = null;
6859
6860
		if ( ! is_null( $status ) ) {
6861
			return $status;
6862
		}
6863
6864
		// Check if a modern version of Akismet is active.
6865
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6866
			$status = false;
6867
			return $status;
6868
		}
6869
6870
		// Make sure there is a key known to Akismet at all before verifying key.
6871
		$akismet_key = Akismet::get_api_key();
6872
		if ( ! $akismet_key ) {
6873
			$status = false;
6874
			return $status;
6875
		}
6876
6877
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6878
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6879
6880
		// 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.
6881
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6882
		// We cache the result of the Akismet key verification for ten minutes.
6883
		if ( ! $akismet_key_state || $recheck ) {
6884
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6885
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6886
		}
6887
6888
		$status = 'valid' === $akismet_key_state;
6889
6890
		return $status;
6891
	}
6892
6893
	/**
6894
	 * Checks if one or more function names is in debug_backtrace
6895
	 *
6896
	 * @param $names Mixed string name of function or array of string names of functions
6897
	 *
6898
	 * @return bool
6899
	 */
6900
	public static function is_function_in_backtrace( $names ) {
6901
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6902
		if ( ! is_array( $names ) ) {
6903
			$names = array( $names );
6904
		}
6905
		$names_as_keys = array_flip( $names );
6906
6907
		//Do check in constant O(1) time for PHP5.5+
6908
		if ( function_exists( 'array_column' ) ) {
6909
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6910
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6911
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6912
			return ! empty ( $intersection );
6913
		}
6914
6915
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6916
		foreach ( $backtrace as $call ) {
6917
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6918
				return true;
6919
			}
6920
		}
6921
		return false;
6922
	}
6923
6924
	/**
6925
	 * Given a minified path, and a non-minified path, will return
6926
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6927
	 *
6928
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6929
	 * root Jetpack directory.
6930
	 *
6931
	 * @since 5.6.0
6932
	 *
6933
	 * @param string $min_path
6934
	 * @param string $non_min_path
6935
	 * @return string The URL to the file
6936
	 */
6937
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6938
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
6939
			? $non_min_path
6940
			: $min_path;
6941
6942
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6943
	}
6944
6945
	/**
6946
	 * Checks for whether Jetpack Backup & Scan is enabled.
6947
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6948
	 * @return bool|int|mixed
6949
	 */
6950
	public static function is_rewind_enabled() {
6951
		if ( ! Jetpack::is_active() ) {
6952
			return false;
6953
		}
6954
6955
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6956
		if ( false === $rewind_enabled ) {
6957
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6958
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6959
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6960
				&& ! empty( $rewind_data['state'] )
6961
				&& 'active' === $rewind_data['state'] )
6962
				? 1
6963
				: 0;
6964
6965
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6966
		}
6967
		return $rewind_enabled;
6968
	}
6969
6970
	/**
6971
	 * Return Calypso environment value; used for developing Jetpack and pairing
6972
	 * it with different Calypso enrionments, such as localhost.
6973
	 *
6974
	 * @since 7.4.0
6975
	 *
6976
	 * @return string Calypso environment
6977
	 */
6978
	public static function get_calypso_env() {
6979
		if ( isset( $_GET['calypso_env'] ) ) {
6980
			return sanitize_key( $_GET['calypso_env'] );
6981
		}
6982
6983
		if ( getenv( 'CALYPSO_ENV' ) ) {
6984
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6985
		}
6986
6987
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6988
			return sanitize_key( CALYPSO_ENV );
6989
		}
6990
6991
		return '';
6992
	}
6993
6994
	/**
6995
	 * Checks whether or not TOS has been agreed upon.
6996
	 * Will return true if a user has clicked to register, or is already connected.
6997
	 */
6998
	public static function jetpack_tos_agreed() {
6999
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7000
	}
7001
7002
	/**
7003
	 * Handles activating default modules as well general cleanup for the new connection.
7004
	 *
7005
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7006
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7007
	 * @param boolean $send_state_messages          Whether to send state messages.
7008
	 * @return void
7009
	 */
7010
	public static function handle_post_authorization_actions(
7011
		$activate_sso = false,
7012
		$redirect_on_activation_error = false,
7013
		$send_state_messages = true
7014
	) {
7015
		$other_modules = $activate_sso
7016
			? array( 'sso' )
7017
			: array();
7018
7019
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7020
			Jetpack::delete_active_modules();
7021
7022
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7023
		} else {
7024
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7025
		}
7026
7027
		// Since this is a fresh connection, be sure to clear out IDC options
7028
		Jetpack_IDC::clear_all_idc_options();
7029
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7030
7031
		// Start nonce cleaner
7032
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7033
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7034
7035
		if ( $send_state_messages ) {
7036
			Jetpack::state( 'message', 'authorized' );
7037
		}
7038
	}
7039
7040
	/**
7041
	 * Returns a boolean for whether backups UI should be displayed or not.
7042
	 *
7043
	 * @return bool Should backups UI be displayed?
7044
	 */
7045
	public static function show_backups_ui() {
7046
		/**
7047
		 * Whether UI for backups should be displayed.
7048
		 *
7049
		 * @since 6.5.0
7050
		 *
7051
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7052
		 */
7053
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7054
	}
7055
7056
	/*
7057
	 * Deprecated manage functions
7058
	 */
7059
	function prepare_manage_jetpack_notice() {
7060
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7061
	}
7062
	function manage_activate_screen() {
7063
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7064
	}
7065
	function admin_jetpack_manage_notice() {
7066
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7067
	}
7068
	function opt_out_jetpack_manage_url() {
7069
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7070
	}
7071
	function opt_in_jetpack_manage_url() {
7072
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7073
	}
7074
	function opt_in_jetpack_manage_notice() {
7075
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7076
	}
7077
	function can_display_jetpack_manage_notice() {
7078
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7079
	}
7080
7081
	/**
7082
	 * Clean leftoveruser meta.
7083
	 *
7084
	 * Delete Jetpack-related user meta when it is no longer needed.
7085
	 *
7086
	 * @since 7.3.0
7087
	 *
7088
	 * @param int $user_id User ID being updated.
7089
	 */
7090
	public static function user_meta_cleanup( $user_id ) {
7091
		$meta_keys = array(
7092
			// AtD removed from Jetpack 7.3
7093
			'AtD_options',
7094
			'AtD_check_when',
7095
			'AtD_guess_lang',
7096
			'AtD_ignored_phrases',
7097
		);
7098
7099
		foreach ( $meta_keys as $meta_key ) {
7100
			if ( get_user_meta( $user_id, $meta_key ) ) {
7101
				delete_user_meta( $user_id, $meta_key );
7102
			}
7103
		}
7104
	}
7105
7106
	function is_active_and_not_development_mode( $maybe ) {
7107
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7108
			return false;
7109
		}
7110
		return true;
7111
	}
7112
7113
}
7114