Completed
Push — update/unify-remote-request-ha... ( 5fd84e )
by Marin
26:06 queued 18:44
created

Jetpack::add_remote_request_handlers()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 4
nop 0
dl 0
loc 25
rs 8.8977
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $rest_authentication_status = null;
44
45
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
46
47
	private $tracking;
48
49
	/**
50
	 * @var array The handles of styles that are concatenated into jetpack.css.
51
	 *
52
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
53
	 */
54
	public $concatenated_style_handles = array(
55
		'jetpack-carousel',
56
		'grunion.css',
57
		'the-neverending-homepage',
58
		'jetpack_likes',
59
		'jetpack_related-posts',
60
		'sharedaddy',
61
		'jetpack-slideshow',
62
		'presentations',
63
		'quiz',
64
		'jetpack-subscriptions',
65
		'jetpack-responsive-videos-style',
66
		'jetpack-social-menu',
67
		'tiled-gallery',
68
		'jetpack_display_posts_widget',
69
		'gravatar-profile-widget',
70
		'goodreads-widget',
71
		'jetpack_social_media_icons_widget',
72
		'jetpack-top-posts-widget',
73
		'jetpack_image_widget',
74
		'jetpack-my-community-widget',
75
		'jetpack-authors-widget',
76
		'wordads',
77
		'eu-cookie-law-style',
78
		'flickr-widget-style',
79
		'jetpack-search-widget',
80
		'jetpack-simple-payments-widget-style',
81
		'jetpack-widget-social-icons-styles',
82
	);
83
84
	/**
85
	 * The handles of scripts that can be loaded asynchronously.
86
	 *
87
	 * @var array
88
	 */
89
	public $async_script_handles = array(
90
		'woocommerce-analytics',
91
	);
92
93
	/**
94
	 * Contains all assets that have had their URL rewritten to minified versions.
95
	 *
96
	 * @var array
97
	 */
98
	static $min_assets = array();
99
100
	public $plugins_to_deactivate = array(
101
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
102
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
103
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
104
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
105
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
106
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
107
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
108
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
109
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
110
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
111
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
112
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
113
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
114
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
115
	);
116
117
	/**
118
	 * Map of roles we care about, and their corresponding minimum capabilities.
119
	 *
120
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
121
	 *
122
	 * @access public
123
	 * @static
124
	 *
125
	 * @var array
126
	 */
127
	public static $capability_translations = array(
128
		'administrator' => 'manage_options',
129
		'editor'        => 'edit_others_posts',
130
		'author'        => 'publish_posts',
131
		'contributor'   => 'edit_posts',
132
		'subscriber'    => 'read',
133
	);
134
135
	/**
136
	 * Map of modules that have conflicts with plugins and should not be auto-activated
137
	 * if the plugins are active.  Used by filter_default_modules
138
	 *
139
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
140
	 * change `module-slug` and add this to your plugin:
141
	 *
142
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
143
	 * function my_jetpack_get_default_modules( $modules ) {
144
	 *     return array_diff( $modules, array( 'module-slug' ) );
145
	 * }
146
	 *
147
	 * @var array
148
	 */
149
	private $conflicting_plugins = array(
150
		'comments'          => array(
151
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
152
			'Disqus'                               => 'disqus-comment-system/disqus.php',
153
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
154
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
155
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
156
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
157
		),
158
		'comment-likes' => array(
159
			'Epoch'                                => 'epoch/plugincore.php',
160
		),
161
		'contact-form'      => array(
162
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
163
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
164
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
165
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
166
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
167
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
168
		),
169
		'minileven'         => array(
170
			'WPtouch'                              => 'wptouch/wptouch.php',
171
		),
172
		'latex'             => array(
173
			'LaTeX for WordPress'                  => 'latex/latex.php',
174
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
175
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
176
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
177
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
178
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
179
		),
180
		'protect'           => array(
181
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
182
			'Captcha'                              => 'captcha/captcha.php',
183
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
184
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
185
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
186
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
187
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
188
			'Security-protection'                  => 'security-protection/security-protection.php',
189
			'Login Security'                       => 'login-security/login-security.php',
190
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
191
			'Wordfence Security'                   => 'wordfence/wordfence.php',
192
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
193
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
194
		),
195
		'random-redirect'   => array(
196
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
197
		),
198
		'related-posts'     => array(
199
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
200
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
201
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
202
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
203
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
204
			'outbrain'                             => 'outbrain/outbrain.php',
205
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
206
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
207
		),
208
		'sharedaddy'        => array(
209
			'AddThis'                              => 'addthis/addthis_social_widget.php',
210
			'Add To Any'                           => 'add-to-any/add-to-any.php',
211
			'ShareThis'                            => 'share-this/sharethis.php',
212
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
213
		),
214
		'seo-tools' => array(
215
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
216
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
217
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
218
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
219
			'The SEO Framework'                    => 'autodescription/autodescription.php',
220
		),
221
		'verification-tools' => array(
222
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
223
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
224
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
225
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
226
			'The SEO Framework'                    => 'autodescription/autodescription.php',
227
		),
228
		'widget-visibility' => array(
229
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
230
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
231
		),
232
		'sitemaps' => array(
233
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
234
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
235
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
236
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
237
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
238
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
239
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
240
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
241
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
242
			'The SEO Framework'                    => 'autodescription/autodescription.php',
243
			'Sitemap'                              => 'sitemap/sitemap.php',
244
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
245
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
246
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
247
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
248
		),
249
		'lazy-images' => array(
250
			'Lazy Load'              => 'lazy-load/lazy-load.php',
251
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
252
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
253
		),
254
	);
255
256
	/**
257
	 * Plugins for which we turn off our Facebook OG Tags implementation.
258
	 *
259
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
260
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
261
	 *
262
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
263
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
264
	 */
265
	private $open_graph_conflicting_plugins = array(
266
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
267
		                                                         // 2 Click Social Media Buttons
268
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
269
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
270
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
271
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
272
		                                                         // Open Graph Meta Tags by Heateor
273
		'facebook/facebook.php',                                 // Facebook (official plugin)
274
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
275
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
276
		                                                         // Facebook Featured Image & OG Meta Tags
277
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
278
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
279
		                                                         // Facebook Open Graph Meta Tags for WordPress
280
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
281
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
282
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
283
		                                                         // Fedmich's Facebook Open Graph Meta
284
		'network-publisher/networkpub.php',                      // Network Publisher
285
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
286
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
287
		                                                         // NextScripts SNAP
288
		'og-tags/og-tags.php',                                   // OG Tags
289
		'opengraph/opengraph.php',                               // Open Graph
290
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
291
		                                                         // Open Graph Protocol Framework
292
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
293
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
294
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
295
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
296
		'sharepress/sharepress.php',                             // SharePress
297
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
298
		'social-discussions/social-discussions.php',             // Social Discussions
299
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
300
		'socialize/socialize.php',                               // Socialize
301
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
302
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
303
		                                                         // Tweet, Like, Google +1 and Share
304
		'wordbooker/wordbooker.php',                             // Wordbooker
305
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
306
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
307
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
308
		                                                         // WP Facebook Like Send & Open Graph Meta
309
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
310
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
311
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
312
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
313
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
314
	);
315
316
	/**
317
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
318
	 */
319
	private $twitter_cards_conflicting_plugins = array(
320
	//	'twitter/twitter.php',                       // The official one handles this on its own.
321
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
322
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
323
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
324
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
325
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
326
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
327
		'twitter-cards/twitter-cards.php',           // Twitter Cards
328
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
329
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
330
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
331
	);
332
333
	/**
334
	 * Message to display in admin_notice
335
	 * @var string
336
	 */
337
	public $message = '';
338
339
	/**
340
	 * Error to display in admin_notice
341
	 * @var string
342
	 */
343
	public $error = '';
344
345
	/**
346
	 * Modules that need more privacy description.
347
	 * @var string
348
	 */
349
	public $privacy_checks = '';
350
351
	/**
352
	 * Stats to record once the page loads
353
	 *
354
	 * @var array
355
	 */
356
	public $stats = array();
357
358
	/**
359
	 * Jetpack_Sync object
360
	 */
361
	public $sync;
362
363
	/**
364
	 * Verified data for JSON authorization request
365
	 */
366
	public $json_api_authorization_request = array();
367
368
	/**
369
	 * @var \Automattic\Jetpack\Connection\Manager
370
	 */
371
	protected $connection_manager;
372
373
	/**
374
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
375
	 */
376
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
377
378
	/**
379
	 * Holds the singleton instance of this class
380
	 * @since 2.3.3
381
	 * @var Jetpack
382
	 */
383
	static $instance = false;
384
385
	/**
386
	 * Singleton
387
	 * @static
388
	 */
389
	public static function init() {
390
		if ( ! self::$instance ) {
391
			self::$instance = new Jetpack;
392
393
			self::$instance->plugin_upgrade();
394
		}
395
396
		return self::$instance;
397
	}
398
399
	/**
400
	 * Must never be called statically
401
	 */
402
	function plugin_upgrade() {
403
		if ( Jetpack::is_active() ) {
404
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
405
			if ( JETPACK__VERSION != $version ) {
406
				// Prevent multiple upgrades at once - only a single process should trigger
407
				// an upgrade to avoid stampedes
408
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
409
					return;
410
				}
411
412
				// Set a short lock to prevent multiple instances of the upgrade
413
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
414
415
				// check which active modules actually exist and remove others from active_modules list
416
				$unfiltered_modules = Jetpack::get_active_modules();
417
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
418
				if ( array_diff( $unfiltered_modules, $modules ) ) {
419
					Jetpack::update_active_modules( $modules );
420
				}
421
422
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
423
424
				// Upgrade to 4.3.0
425
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
426
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
427
				}
428
429
				// Make sure Markdown for posts gets turned back on
430
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
431
					update_option( 'wpcom_publish_posts_with_markdown', true );
432
				}
433
434
				if ( did_action( 'wp_loaded' ) ) {
435
					self::upgrade_on_load();
436
				} else {
437
					add_action(
438
						'wp_loaded',
439
						array( __CLASS__, 'upgrade_on_load' )
440
					);
441
				}
442
			}
443
		}
444
	}
445
446
	/**
447
	 * Runs upgrade routines that need to have modules loaded.
448
	 */
449
	static function upgrade_on_load() {
450
451
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
452
		// This can happen in case Jetpack has been just upgraded and is
453
		// being initialized late during the page load. In this case we wait
454
		// until the next proper admin page load with Jetpack active.
455
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
456
			delete_transient( self::$plugin_upgrade_lock_key );
457
458
			return;
459
		}
460
461
		Jetpack::maybe_set_version_option();
462
463
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
464
			Jetpack_Widget_Conditions::migrate_post_type_rules();
465
		}
466
467
		if (
468
			class_exists( 'Jetpack_Sitemap_Manager' )
469
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
470
		) {
471
			do_action( 'jetpack_sitemaps_purge_data' );
472
		}
473
474
		// Delete old stats cache
475
		delete_option( 'jetpack_restapi_stats_cache' );
476
477
		delete_transient( self::$plugin_upgrade_lock_key );
478
	}
479
480
	/**
481
	 * Saves all the currently active modules to options.
482
	 * Also fires Action hooks for each newly activated and deactivated module.
483
	 *
484
	 * @param $modules Array Array of active modules to be saved in options.
485
	 *
486
	 * @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...
487
	 */
488
	static function update_active_modules( $modules ) {
489
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
490
		$active_modules       = Jetpack::get_active_modules();
491
		$new_active_modules   = array_diff( $modules, $current_modules );
492
		$new_inactive_modules = array_diff( $active_modules, $modules );
493
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
494
		$reindexed_modules    = array_values( $new_current_modules );
495
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
496
497
		foreach ( $new_active_modules as $module ) {
498
			/**
499
			 * Fires when a specific module is activated.
500
			 *
501
			 * @since 1.9.0
502
			 *
503
			 * @param string $module Module slug.
504
			 * @param boolean $success whether the module was activated. @since 4.2
505
			 */
506
			do_action( 'jetpack_activate_module', $module, $success );
507
			/**
508
			 * Fires when a module is activated.
509
			 * The dynamic part of the filter, $module, is the module slug.
510
			 *
511
			 * @since 1.9.0
512
			 *
513
			 * @param string $module Module slug.
514
			 */
515
			do_action( "jetpack_activate_module_$module", $module );
516
		}
517
518
		foreach ( $new_inactive_modules as $module ) {
519
			/**
520
			 * Fired after a module has been deactivated.
521
			 *
522
			 * @since 4.2.0
523
			 *
524
			 * @param string $module Module slug.
525
			 * @param boolean $success whether the module was deactivated.
526
			 */
527
			do_action( 'jetpack_deactivate_module', $module, $success );
528
			/**
529
			 * Fires when a module is deactivated.
530
			 * The dynamic part of the filter, $module, is the module slug.
531
			 *
532
			 * @since 1.9.0
533
			 *
534
			 * @param string $module Module slug.
535
			 */
536
			do_action( "jetpack_deactivate_module_$module", $module );
537
		}
538
539
		return $success;
540
	}
541
542
	static function delete_active_modules() {
543
		self::update_active_modules( array() );
544
	}
545
546
	/**
547
	 * Constructor.  Initializes WordPress hooks
548
	 */
549
	private function __construct() {
550
		/*
551
		 * Check for and alert any deprecated hooks
552
		 */
553
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
554
555
		/*
556
		 * Enable enhanced handling of previewing sites in Calypso
557
		 */
558
		if ( Jetpack::is_active() ) {
559
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
560
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
561
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
562
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
563
		}
564
565
		if ( self::jetpack_tos_agreed() ) {
566
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
567
			add_action( 'init', array( $tracking, 'init' ) );
568
		}
569
570
571
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
572
			return function() {
573
				return wp_generate_password( 32, false );
574
			};
575
		} );
576
577
		$this->connection_manager = new Connection_Manager();
578
		$this->connection_manager->init();
579
580
		/*
581
		 * Load things that should only be in Network Admin.
582
		 *
583
		 * For now blow away everything else until a more full
584
		 * understanding of what is needed at the network level is
585
		 * available
586
		 */
587
		if ( is_multisite() ) {
588
			$network = Jetpack_Network::init();
589
			$network->set_connection( $this->connection_manager );
590
		}
591
592
		add_filter(
593
			'jetpack_signature_check_token',
594
			array( __CLASS__, 'verify_onboarding_token' ),
595
			10,
596
			3
597
		);
598
599
		/**
600
		 * Prepare Gutenberg Editor functionality
601
		 */
602
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
603
		Jetpack_Gutenberg::init();
604
		Jetpack_Gutenberg::load_independent_blocks();
605
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
606
607
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
608
609
		// Unlink user before deleting the user from WP.com.
610
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
611
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
612
613
		// Initialize remote file upload request handlers.
614
		$this->add_remote_request_handlers();
615
616
		if ( Jetpack::is_active() ) {
617
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
618
619
			Jetpack_Heartbeat::init();
620
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
621
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
622
				Jetpack_Search_Performance_Logger::init();
623
			}
624
		}
625
626
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
627
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
628
629
		add_action( 'admin_init', array( $this, 'admin_init' ) );
630
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
631
632
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
633
634
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
635
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
636
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
637
638
		// returns HTTPS support status
639
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
640
641
		// JITM AJAX callback function
642
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
643
644
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
645
646
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
647
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
648
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
649
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
650
651
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
652
653
		/**
654
		 * These actions run checks to load additional files.
655
		 * They check for external files or plugins, so they need to run as late as possible.
656
		 */
657
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
658
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
659
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
660
661
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
662
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
663
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
664
665
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
666
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
667
668
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
669
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
670
671
		// A filter to control all just in time messages
672
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
673
674
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
675
676
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
677
		// We should make sure to only do this for front end links.
678
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
679
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
680
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
681
682
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
683
			//so they point moderation links on emails to Calypso
684
			jetpack_require_lib( 'functions.wp-notify' );
685
		}
686
687
		// Hide edit post link if mobile app.
688
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
689
			add_filter( 'edit_post_link', '__return_empty_string' );
690
		}
691
692
		// Update the Jetpack plan from API on heartbeats
693
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
694
695
		/**
696
		 * This is the hack to concatenate all css files into one.
697
		 * For description and reasoning see the implode_frontend_css method
698
		 *
699
		 * Super late priority so we catch all the registered styles
700
		 */
701
		if( !is_admin() ) {
702
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
703
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
704
		}
705
706
707
		/**
708
		 * These are sync actions that we need to keep track of for jitms
709
		 */
710
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
711
712
		// Actually push the stats on shutdown.
713
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
714
			add_action( 'shutdown', array( $this, 'push_stats' ) );
715
		}
716
717
		/*
718
		 * Load some scripts asynchronously.
719
		 */
720
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
721
	}
722
723
	/**
724
	 * Sets up the XMLRPC request handlers.
725
	 *
726
	 * @deprecated since 7.7.0
727
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
728
	 *
729
	 * @param Array                 $request_params Incoming request parameters.
730
	 * @param Boolean               $is_active      Whether the connection is currently active.
731
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
732
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

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

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

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

Loading history...
733
	 */
734
	public function setup_xmlrpc_handlers(
735
		$request_params,
736
		$is_active,
737
		$is_signed,
738
		Jetpack_XMLRPC_Server $xmlrpc_server = null
739
	) {
740
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
741
		return $this->connection_manager->setup_xmlrpc_handlers(
742
			$request_params,
743
			$is_active,
744
			$is_signed,
745
			$xmlrpc_server
746
		);
747
	}
748
749
	/**
750
	 * Initialize REST API registration connector.
751
	 *
752
	 * @deprecated since 7.7.0
753
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
754
	 */
755
	public function initialize_rest_api_registration_connector() {
756
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
757
		$this->connection_manager->initialize_rest_api_registration_connector();
758
	}
759
760
	/**
761
	 * This is ported over from the manage module, which has been deprecated and baked in here.
762
	 *
763
	 * @param $domains
764
	 */
765
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
766
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
767
	}
768
769
	/**
770
	 * Return $domains, with 'wordpress.com' appended.
771
	 * This is ported over from the manage module, which has been deprecated and baked in here.
772
	 *
773
	 * @param $domains
774
	 * @return array
775
	 */
776
	function allow_wpcom_domain( $domains ) {
777
		if ( empty( $domains ) ) {
778
			$domains = array();
779
		}
780
		$domains[] = 'wordpress.com';
781
		return array_unique( $domains );
782
	}
783
784
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
785
		$post = get_post( $post_id );
786
787
		if ( empty( $post ) ) {
788
			return $default_url;
789
		}
790
791
		$post_type = $post->post_type;
792
793
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
794
		// https://en.support.wordpress.com/custom-post-types/
795
		$allowed_post_types = array(
796
			'post' => 'post',
797
			'page' => 'page',
798
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
799
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
800
		);
801
802
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
803
			return $default_url;
804
		}
805
806
		$path_prefix = $allowed_post_types[ $post_type ];
807
808
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
809
810
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
811
	}
812
813
	function point_edit_comment_links_to_calypso( $url ) {
814
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
815
		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...
816
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
817
			Jetpack::build_raw_urls( get_home_url() ),
818
			$query_args['amp;c']
819
		) );
820
	}
821
822
	function jetpack_track_last_sync_callback( $params ) {
823
		/**
824
		 * Filter to turn off jitm caching
825
		 *
826
		 * @since 5.4.0
827
		 *
828
		 * @param bool false Whether to cache just in time messages
829
		 */
830
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
831
			return $params;
832
		}
833
834
		if ( is_array( $params ) && isset( $params[0] ) ) {
835
			$option = $params[0];
836
			if ( 'active_plugins' === $option ) {
837
				// use the cache if we can, but not terribly important if it gets evicted
838
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
839
			}
840
		}
841
842
		return $params;
843
	}
844
845
	function jetpack_connection_banner_callback() {
846
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
847
848
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
849
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
850
			wp_send_json_success();
851
		}
852
853
		wp_die();
854
	}
855
856
	/**
857
	 * Removes all XML-RPC methods that are not `jetpack.*`.
858
	 * Only used in our alternate XML-RPC endpoint, where we want to
859
	 * ensure that Core and other plugins' methods are not exposed.
860
	 *
861
	 * @deprecated since 7.7.0
862
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
863
	 *
864
	 * @param array $methods A list of registered WordPress XMLRPC methods.
865
	 * @return array Filtered $methods
866
	 */
867
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
868
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
869
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
870
	}
871
872
	/**
873
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
874
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
875
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
876
	 * which is accessible via a different URI. Most of the below is copied directly
877
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
878
	 *
879
	 * @deprecated since 7.7.0
880
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
881
	 */
882
	public function alternate_xmlrpc() {
883
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
884
		$this->connection_manager->alternate_xmlrpc();
885
	}
886
887
	/**
888
	 * The callback for the JITM ajax requests.
889
	 */
890
	function jetpack_jitm_ajax_callback() {
891
		// Check for nonce
892
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
893
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
894
		}
895
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
896
			$module_slug = $_REQUEST['jitmModule'];
897
			Jetpack::log( 'activate', $module_slug );
898
			Jetpack::activate_module( $module_slug, false, false );
899
			Jetpack::state( 'message', 'no_message' );
900
901
			//A Jetpack module is being activated through a JITM, track it
902
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
903
			$this->do_stats( 'server_side' );
904
905
			wp_send_json_success();
906
		}
907
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
908
			// get the hide_jitm options array
909
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
910
			$module_slug = $_REQUEST['jitmModule'];
911
912
			if( ! $jetpack_hide_jitm ) {
913
				$jetpack_hide_jitm = array(
914
					$module_slug => 'hide'
915
				);
916
			} else {
917
				$jetpack_hide_jitm[$module_slug] = 'hide';
918
			}
919
920
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
921
922
			//jitm is being dismissed forever, track it
923
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
924
			$this->do_stats( 'server_side' );
925
926
			wp_send_json_success();
927
		}
928 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
929
			$module_slug = $_REQUEST['jitmModule'];
930
931
			// User went to WordPress.com, track this
932
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
933
			$this->do_stats( 'server_side' );
934
935
			wp_send_json_success();
936
		}
937 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
938
			$track = $_REQUEST['jitmModule'];
939
940
			// User is viewing JITM, track it.
941
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
942
			$this->do_stats( 'server_side' );
943
944
			wp_send_json_success();
945
		}
946
	}
947
948
	/**
949
	 * If there are any stats that need to be pushed, but haven't been, push them now.
950
	 */
951
	function push_stats() {
952
		if ( ! empty( $this->stats ) ) {
953
			$this->do_stats( 'server_side' );
954
		}
955
	}
956
957
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
958
		switch( $cap ) {
959
			case 'jetpack_connect' :
960
			case 'jetpack_reconnect' :
961
				if ( Jetpack::is_development_mode() ) {
962
					$caps = array( 'do_not_allow' );
963
					break;
964
				}
965
				/**
966
				 * Pass through. If it's not development mode, these should match disconnect.
967
				 * Let users disconnect if it's development mode, just in case things glitch.
968
				 */
969
			case 'jetpack_disconnect' :
970
				/**
971
				 * In multisite, can individual site admins manage their own connection?
972
				 *
973
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
974
				 */
975
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
976
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
977
						/**
978
						 * We need to update the option name -- it's terribly unclear which
979
						 * direction the override goes.
980
						 *
981
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
982
						 */
983
						$caps = array( 'do_not_allow' );
984
						break;
985
					}
986
				}
987
988
				$caps = array( 'manage_options' );
989
				break;
990
			case 'jetpack_manage_modules' :
991
			case 'jetpack_activate_modules' :
992
			case 'jetpack_deactivate_modules' :
993
				$caps = array( 'manage_options' );
994
				break;
995
			case 'jetpack_configure_modules' :
996
				$caps = array( 'manage_options' );
997
				break;
998
			case 'jetpack_manage_autoupdates' :
999
				$caps = array(
1000
					'manage_options',
1001
					'update_plugins',
1002
				);
1003
				break;
1004
			case 'jetpack_network_admin_page':
1005
			case 'jetpack_network_settings_page':
1006
				$caps = array( 'manage_network_plugins' );
1007
				break;
1008
			case 'jetpack_network_sites_page':
1009
				$caps = array( 'manage_sites' );
1010
				break;
1011
			case 'jetpack_admin_page' :
1012
				if ( Jetpack::is_development_mode() ) {
1013
					$caps = array( 'manage_options' );
1014
					break;
1015
				} else {
1016
					$caps = array( 'read' );
1017
				}
1018
				break;
1019
			case 'jetpack_connect_user' :
1020
				if ( Jetpack::is_development_mode() ) {
1021
					$caps = array( 'do_not_allow' );
1022
					break;
1023
				}
1024
				$caps = array( 'read' );
1025
				break;
1026
		}
1027
		return $caps;
1028
	}
1029
1030
	/**
1031
	 * Require a Jetpack authentication.
1032
	 *
1033
	 * @deprecated since 7.7.0
1034
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1035
	 */
1036
	public function require_jetpack_authentication() {
1037
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1038
		$this->connection_manager->require_jetpack_authentication();
1039
	}
1040
1041
	/**
1042
	 * Load language files
1043
	 * @action plugins_loaded
1044
	 */
1045
	public static function plugin_textdomain() {
1046
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1047
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1048
	}
1049
1050
	/**
1051
	 * Register assets for use in various modules and the Jetpack admin page.
1052
	 *
1053
	 * @uses wp_script_is, wp_register_script, plugins_url
1054
	 * @action wp_loaded
1055
	 * @return null
1056
	 */
1057
	public function register_assets() {
1058
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1059
			wp_register_script(
1060
				'spin',
1061
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1062
				false,
1063
				'1.3'
1064
			);
1065
		}
1066
1067 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1068
			wp_register_script(
1069
				'jquery.spin',
1070
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1071
				array( 'jquery', 'spin' ),
1072
				'1.3'
1073
			);
1074
		}
1075
1076 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1077
			wp_register_script(
1078
				'jetpack-gallery-settings',
1079
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1080
				array( 'media-views' ),
1081
				'20121225'
1082
			);
1083
		}
1084
1085 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1086
			wp_register_script(
1087
				'jetpack-twitter-timeline',
1088
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1089
				array( 'jquery' ),
1090
				'4.0.0',
1091
				true
1092
			);
1093
		}
1094
1095
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1096
			wp_register_script(
1097
				'jetpack-facebook-embed',
1098
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1099
				array( 'jquery' ),
1100
				null,
1101
				true
1102
			);
1103
1104
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1105
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1106
			if ( ! is_numeric( $fb_app_id ) ) {
1107
				$fb_app_id = '';
1108
			}
1109
			wp_localize_script(
1110
				'jetpack-facebook-embed',
1111
				'jpfbembed',
1112
				array(
1113
					'appid' => $fb_app_id,
1114
					'locale' => $this->get_locale(),
1115
				)
1116
			);
1117
		}
1118
1119
		/**
1120
		 * As jetpack_register_genericons is by default fired off a hook,
1121
		 * the hook may have already fired by this point.
1122
		 * So, let's just trigger it manually.
1123
		 */
1124
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1125
		jetpack_register_genericons();
1126
1127
		/**
1128
		 * Register the social logos
1129
		 */
1130
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1131
		jetpack_register_social_logos();
1132
1133 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1134
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1135
	}
1136
1137
	/**
1138
	 * Guess locale from language code.
1139
	 *
1140
	 * @param string $lang Language code.
1141
	 * @return string|bool
1142
	 */
1143 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1144
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1145
			return 'en_US';
1146
		}
1147
1148
		if ( ! class_exists( 'GP_Locales' ) ) {
1149
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1150
				return false;
1151
			}
1152
1153
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1154
		}
1155
1156
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1157
			// WP.com: get_locale() returns 'it'
1158
			$locale = GP_Locales::by_slug( $lang );
1159
		} else {
1160
			// Jetpack: get_locale() returns 'it_IT';
1161
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1162
		}
1163
1164
		if ( ! $locale ) {
1165
			return false;
1166
		}
1167
1168
		if ( empty( $locale->facebook_locale ) ) {
1169
			if ( empty( $locale->wp_locale ) ) {
1170
				return false;
1171
			} else {
1172
				// Facebook SDK is smart enough to fall back to en_US if a
1173
				// locale isn't supported. Since supported Facebook locales
1174
				// can fall out of sync, we'll attempt to use the known
1175
				// wp_locale value and rely on said fallback.
1176
				return $locale->wp_locale;
1177
			}
1178
		}
1179
1180
		return $locale->facebook_locale;
1181
	}
1182
1183
	/**
1184
	 * Get the locale.
1185
	 *
1186
	 * @return string|bool
1187
	 */
1188
	function get_locale() {
1189
		$locale = $this->guess_locale_from_lang( get_locale() );
1190
1191
		if ( ! $locale ) {
1192
			$locale = 'en_US';
1193
		}
1194
1195
		return $locale;
1196
	}
1197
1198
	/**
1199
	 * Device Pixels support
1200
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1201
	 */
1202
	function devicepx() {
1203
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1204
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1205
		}
1206
	}
1207
1208
	/**
1209
	 * Return the network_site_url so that .com knows what network this site is a part of.
1210
	 * @param  bool $option
1211
	 * @return string
1212
	 */
1213
	public function jetpack_main_network_site_option( $option ) {
1214
		return network_site_url();
1215
	}
1216
	/**
1217
	 * Network Name.
1218
	 */
1219
	static function network_name( $option = null ) {
1220
		global $current_site;
1221
		return $current_site->site_name;
1222
	}
1223
	/**
1224
	 * Does the network allow new user and site registrations.
1225
	 * @return string
1226
	 */
1227
	static function network_allow_new_registrations( $option = null ) {
1228
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1229
	}
1230
	/**
1231
	 * Does the network allow admins to add new users.
1232
	 * @return boolian
1233
	 */
1234
	static function network_add_new_users( $option = null ) {
1235
		return (bool) get_site_option( 'add_new_users' );
1236
	}
1237
	/**
1238
	 * File upload psace left per site in MB.
1239
	 *  -1 means NO LIMIT.
1240
	 * @return number
1241
	 */
1242
	static function network_site_upload_space( $option = null ) {
1243
		// value in MB
1244
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1245
	}
1246
1247
	/**
1248
	 * Network allowed file types.
1249
	 * @return string
1250
	 */
1251
	static function network_upload_file_types( $option = null ) {
1252
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1253
	}
1254
1255
	/**
1256
	 * Maximum file upload size set by the network.
1257
	 * @return number
1258
	 */
1259
	static function network_max_upload_file_size( $option = null ) {
1260
		// value in KB
1261
		return get_site_option( 'fileupload_maxk', 300 );
1262
	}
1263
1264
	/**
1265
	 * Lets us know if a site allows admins to manage the network.
1266
	 * @return array
1267
	 */
1268
	static function network_enable_administration_menus( $option = null ) {
1269
		return get_site_option( 'menu_items' );
1270
	}
1271
1272
	/**
1273
	 * If a user has been promoted to or demoted from admin, we need to clear the
1274
	 * jetpack_other_linked_admins transient.
1275
	 *
1276
	 * @since 4.3.2
1277
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1278
	 *
1279
	 * @param int    $user_id   The user ID whose role changed.
1280
	 * @param string $role      The new role.
1281
	 * @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...
1282
	 */
1283
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1284
		if ( 'administrator' == $role
1285
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1286
			|| is_null( $old_roles )
1287
		) {
1288
			delete_transient( 'jetpack_other_linked_admins' );
1289
		}
1290
	}
1291
1292
	/**
1293
	 * Checks to see if there are any other users available to become primary
1294
	 * Users must both:
1295
	 * - Be linked to wpcom
1296
	 * - Be an admin
1297
	 *
1298
	 * @return mixed False if no other users are linked, Int if there are.
1299
	 */
1300
	static function get_other_linked_admins() {
1301
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1302
1303
		if ( false === $other_linked_users ) {
1304
			$admins = get_users( array( 'role' => 'administrator' ) );
1305
			if ( count( $admins ) > 1 ) {
1306
				$available = array();
1307
				foreach ( $admins as $admin ) {
1308
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1309
						$available[] = $admin->ID;
1310
					}
1311
				}
1312
1313
				$count_connected_admins = count( $available );
1314
				if ( count( $available ) > 1 ) {
1315
					$other_linked_users = $count_connected_admins;
1316
				} else {
1317
					$other_linked_users = 0;
1318
				}
1319
			} else {
1320
				$other_linked_users = 0;
1321
			}
1322
1323
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1324
		}
1325
1326
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1327
	}
1328
1329
	/**
1330
	 * Return whether we are dealing with a multi network setup or not.
1331
	 * The reason we are type casting this is because we want to avoid the situation where
1332
	 * the result is false since when is_main_network_option return false it cases
1333
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1334
	 * database which could be set to anything as opposed to what this function returns.
1335
	 * @param  bool  $option
1336
	 *
1337
	 * @return boolean
1338
	 */
1339
	public function is_main_network_option( $option ) {
1340
		// return '1' or ''
1341
		return (string) (bool) Jetpack::is_multi_network();
1342
	}
1343
1344
	/**
1345
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1346
	 *
1347
	 * @param  string  $option
1348
	 * @return boolean
1349
	 */
1350
	public function is_multisite( $option ) {
1351
		return (string) (bool) is_multisite();
1352
	}
1353
1354
	/**
1355
	 * Implemented since there is no core is multi network function
1356
	 * Right now there is no way to tell if we which network is the dominant network on the system
1357
	 *
1358
	 * @since  3.3
1359
	 * @return boolean
1360
	 */
1361 View Code Duplication
	public static function is_multi_network() {
1362
		global  $wpdb;
1363
1364
		// if we don't have a multi site setup no need to do any more
1365
		if ( ! is_multisite() ) {
1366
			return false;
1367
		}
1368
1369
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1370
		if ( $num_sites > 1 ) {
1371
			return true;
1372
		} else {
1373
			return false;
1374
		}
1375
	}
1376
1377
	/**
1378
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1379
	 * @return null
1380
	 */
1381
	function update_jetpack_main_network_site_option() {
1382
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1383
	}
1384
	/**
1385
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1386
	 *
1387
	 */
1388
	function update_jetpack_network_settings() {
1389
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1390
		// Only sync this info for the main network site.
1391
	}
1392
1393
	/**
1394
	 * Get back if the current site is single user site.
1395
	 *
1396
	 * @return bool
1397
	 */
1398 View Code Duplication
	public static function is_single_user_site() {
1399
		global $wpdb;
1400
1401
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1402
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1403
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1404
		}
1405
		return 1 === (int) $some_users;
1406
	}
1407
1408
	/**
1409
	 * Returns true if the site has file write access false otherwise.
1410
	 * @return string ( '1' | '0' )
1411
	 **/
1412
	public static function file_system_write_access() {
1413
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1414
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1415
		}
1416
1417
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1418
1419
		$filesystem_method = get_filesystem_method();
1420
		if ( $filesystem_method === 'direct' ) {
1421
			return 1;
1422
		}
1423
1424
		ob_start();
1425
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1426
		ob_end_clean();
1427
		if ( $filesystem_credentials_are_stored ) {
1428
			return 1;
1429
		}
1430
		return 0;
1431
	}
1432
1433
	/**
1434
	 * Finds out if a site is using a version control system.
1435
	 * @return string ( '1' | '0' )
1436
	 **/
1437
	public static function is_version_controlled() {
1438
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1439
		return (string) (int) Functions::is_version_controlled();
1440
	}
1441
1442
	/**
1443
	 * Determines whether the current theme supports featured images or not.
1444
	 * @return string ( '1' | '0' )
1445
	 */
1446
	public static function featured_images_enabled() {
1447
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1448
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1449
	}
1450
1451
	/**
1452
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1453
	 *
1454
	 * @deprecated 4.7 use get_avatar_url instead.
1455
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1456
	 * @param int $size Size of the avatar image
1457
	 * @param string $default URL to a default image to use if no avatar is available
1458
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1459
	 *
1460
	 * @return array
1461
	 */
1462
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1463
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1464
		return get_avatar_url( $id_or_email, array(
1465
			'size' => $size,
1466
			'default' => $default,
1467
			'force_default' => $force_display,
1468
		) );
1469
	}
1470
1471
	/**
1472
	 * jetpack_updates is saved in the following schema:
1473
	 *
1474
	 * array (
1475
	 *      'plugins'                       => (int) Number of plugin updates available.
1476
	 *      'themes'                        => (int) Number of theme updates available.
1477
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1478
	 *      'translations'                  => (int) Number of translation updates available.
1479
	 *      'total'                         => (int) Total of all available updates.
1480
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1481
	 * )
1482
	 * @return array
1483
	 */
1484
	public static function get_updates() {
1485
		$update_data = wp_get_update_data();
1486
1487
		// Stores the individual update counts as well as the total count.
1488
		if ( isset( $update_data['counts'] ) ) {
1489
			$updates = $update_data['counts'];
1490
		}
1491
1492
		// If we need to update WordPress core, let's find the latest version number.
1493 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1494
			$cur = get_preferred_from_update_core();
1495
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1496
				$updates['wp_update_version'] = $cur->current;
1497
			}
1498
		}
1499
		return isset( $updates ) ? $updates : array();
1500
	}
1501
1502
	public static function get_update_details() {
1503
		$update_details = array(
1504
			'update_core' => get_site_transient( 'update_core' ),
1505
			'update_plugins' => get_site_transient( 'update_plugins' ),
1506
			'update_themes' => get_site_transient( 'update_themes' ),
1507
		);
1508
		return $update_details;
1509
	}
1510
1511
	public static function refresh_update_data() {
1512
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1513
1514
	}
1515
1516
	public static function refresh_theme_data() {
1517
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1518
	}
1519
1520
	/**
1521
	 * Is Jetpack active?
1522
	 */
1523
	public static function is_active() {
1524
		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...
1525
	}
1526
1527
	/**
1528
	 * Make an API call to WordPress.com for plan status
1529
	 *
1530
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1531
	 *
1532
	 * @return bool True if plan is updated, false if no update
1533
	 */
1534
	public static function refresh_active_plan_from_wpcom() {
1535
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1536
		return Jetpack_Plan::refresh_from_wpcom();
1537
	}
1538
1539
	/**
1540
	 * Get the plan that this Jetpack site is currently using
1541
	 *
1542
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1543
	 * @return array Active Jetpack plan details.
1544
	 */
1545
	public static function get_active_plan() {
1546
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1547
		return Jetpack_Plan::get();
1548
	}
1549
1550
	/**
1551
	 * Determine whether the active plan supports a particular feature
1552
	 *
1553
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1554
	 * @return bool True if plan supports feature, false if not.
1555
	 */
1556
	public static function active_plan_supports( $feature ) {
1557
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1558
		return Jetpack_Plan::supports( $feature );
1559
	}
1560
1561
	/**
1562
	 * Is Jetpack in development (offline) mode?
1563
	 */
1564 View Code Duplication
	public static function is_development_mode() {
1565
		$development_mode = false;
1566
1567
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1568
			$development_mode = JETPACK_DEV_DEBUG;
1569
		} elseif ( $site_url = site_url() ) {
1570
			$development_mode = false === strpos( $site_url, '.' );
1571
		}
1572
1573
		/**
1574
		 * Filters Jetpack's development mode.
1575
		 *
1576
		 * @see https://jetpack.com/support/development-mode/
1577
		 *
1578
		 * @since 2.2.1
1579
		 *
1580
		 * @param bool $development_mode Is Jetpack's development mode active.
1581
		 */
1582
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1583
		return $development_mode;
1584
	}
1585
1586
	/**
1587
	 * Whether the site is currently onboarding or not.
1588
	 * A site is considered as being onboarded if it currently has an onboarding token.
1589
	 *
1590
	 * @since 5.8
1591
	 *
1592
	 * @access public
1593
	 * @static
1594
	 *
1595
	 * @return bool True if the site is currently onboarding, false otherwise
1596
	 */
1597
	public static function is_onboarding() {
1598
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1599
	}
1600
1601
	/**
1602
	 * Determines reason for Jetpack development mode.
1603
	 */
1604
	public static function development_mode_trigger_text() {
1605
		if ( ! Jetpack::is_development_mode() ) {
1606
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1607
		}
1608
1609
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1610
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1611
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1612
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1613
		} else {
1614
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1615
		}
1616
1617
		return $notice;
1618
1619
	}
1620
	/**
1621
	* Get Jetpack development mode notice text and notice class.
1622
	*
1623
	* Mirrors the checks made in Jetpack::is_development_mode
1624
	*
1625
	*/
1626
	public static function show_development_mode_notice() {
1627 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1628
			$notice = sprintf(
1629
			/* translators: %s is a URL */
1630
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1631
				'https://jetpack.com/support/development-mode/'
1632
			);
1633
1634
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1635
1636
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1637
		}
1638
1639
		// Throw up a notice if using a development version and as for feedback.
1640
		if ( Jetpack::is_development_version() ) {
1641
			/* translators: %s is a URL */
1642
			$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/' );
1643
1644
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1645
		}
1646
		// Throw up a notice if using staging mode
1647
		if ( Jetpack::is_staging_site() ) {
1648
			/* translators: %s is a URL */
1649
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1650
1651
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1652
		}
1653
	}
1654
1655
	/**
1656
	 * Whether Jetpack's version maps to a public release, or a development version.
1657
	 */
1658
	public static function is_development_version() {
1659
		/**
1660
		 * Allows filtering whether this is a development version of Jetpack.
1661
		 *
1662
		 * This filter is especially useful for tests.
1663
		 *
1664
		 * @since 4.3.0
1665
		 *
1666
		 * @param bool $development_version Is this a develoment version of Jetpack?
1667
		 */
1668
		return (bool) apply_filters(
1669
			'jetpack_development_version',
1670
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1671
		);
1672
	}
1673
1674
	/**
1675
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1676
	 */
1677
	public static function is_user_connected( $user_id = false ) {
1678
		return self::connection()->is_user_connected( $user_id );
1679
	}
1680
1681
	/**
1682
	 * Get the wpcom user data of the current|specified connected user.
1683
	 */
1684 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1685
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1686
		if ( ! $user_id ) {
1687
			$user_id = get_current_user_id();
1688
		}
1689
1690
		$transient_key = "jetpack_connected_user_data_$user_id";
1691
1692
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1693
			return $cached_user_data;
1694
		}
1695
1696
		Jetpack::load_xml_rpc_client();
1697
		$xml = new Jetpack_IXR_Client( array(
1698
			'user_id' => $user_id,
1699
		) );
1700
		$xml->query( 'wpcom.getUser' );
1701
		if ( ! $xml->isError() ) {
1702
			$user_data = $xml->getResponse();
1703
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1704
			return $user_data;
1705
		}
1706
1707
		return false;
1708
	}
1709
1710
	/**
1711
	 * Get the wpcom email of the current|specified connected user.
1712
	 */
1713 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1714
		if ( ! $user_id ) {
1715
			$user_id = get_current_user_id();
1716
		}
1717
		Jetpack::load_xml_rpc_client();
1718
		$xml = new Jetpack_IXR_Client( array(
1719
			'user_id' => $user_id,
1720
		) );
1721
		$xml->query( 'wpcom.getUserEmail' );
1722
		if ( ! $xml->isError() ) {
1723
			return $xml->getResponse();
1724
		}
1725
		return false;
1726
	}
1727
1728
	/**
1729
	 * Get the wpcom email of the master user.
1730
	 */
1731
	public static function get_master_user_email() {
1732
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1733
		if ( $master_user_id ) {
1734
			return self::get_connected_user_email( $master_user_id );
1735
		}
1736
		return '';
1737
	}
1738
1739
	/**
1740
	 * Whether the current user is the connection owner.
1741
	 *
1742
	 * @deprecated since 7.7
1743
	 *
1744
	 * @return bool Whether the current user is the connection owner.
1745
	 */
1746
	public function current_user_is_connection_owner() {
1747
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1748
		return self::connection()->is_connection_owner();
1749
	}
1750
1751
	/**
1752
	 * Gets current user IP address.
1753
	 *
1754
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1755
	 *
1756
	 * @return string                  Current user IP address.
1757
	 */
1758
	public static function current_user_ip( $check_all_headers = false ) {
1759
		if ( $check_all_headers ) {
1760
			foreach ( array(
1761
				'HTTP_CF_CONNECTING_IP',
1762
				'HTTP_CLIENT_IP',
1763
				'HTTP_X_FORWARDED_FOR',
1764
				'HTTP_X_FORWARDED',
1765
				'HTTP_X_CLUSTER_CLIENT_IP',
1766
				'HTTP_FORWARDED_FOR',
1767
				'HTTP_FORWARDED',
1768
				'HTTP_VIA',
1769
			) as $key ) {
1770
				if ( ! empty( $_SERVER[ $key ] ) ) {
1771
					return $_SERVER[ $key ];
1772
				}
1773
			}
1774
		}
1775
1776
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1777
	}
1778
1779
	/**
1780
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1781
	 */
1782
	function extra_oembed_providers() {
1783
		// Cloudup: https://dev.cloudup.com/#oembed
1784
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1785
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1786
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1787
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1788
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1789
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1790
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1791
	}
1792
1793
	/**
1794
	 * Synchronize connected user role changes
1795
	 */
1796
	function user_role_change( $user_id ) {
1797
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1798
		Users::user_role_change( $user_id );
1799
	}
1800
1801
	/**
1802
	 * Loads the currently active modules.
1803
	 */
1804
	public static function load_modules() {
1805
		if (
1806
			! self::is_active()
1807
			&& ! self::is_development_mode()
1808
			&& ! self::is_onboarding()
1809
			&& (
1810
				! is_multisite()
1811
				|| ! get_site_option( 'jetpack_protect_active' )
1812
			)
1813
		) {
1814
			return;
1815
		}
1816
1817
		$version = Jetpack_Options::get_option( 'version' );
1818 View Code Duplication
		if ( ! $version ) {
1819
			$version = $old_version = JETPACK__VERSION . ':' . time();
1820
			/** This action is documented in class.jetpack.php */
1821
			do_action( 'updating_jetpack_version', $version, false );
1822
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1823
		}
1824
		list( $version ) = explode( ':', $version );
1825
1826
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1827
1828
		$modules_data = array();
1829
1830
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1831
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1832
			$updated_modules = array();
1833
			foreach ( $modules as $module ) {
1834
				$modules_data[ $module ] = Jetpack::get_module( $module );
1835
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1836
					continue;
1837
				}
1838
1839
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1840
					continue;
1841
				}
1842
1843
				$updated_modules[] = $module;
1844
			}
1845
1846
			$modules = array_diff( $modules, $updated_modules );
1847
		}
1848
1849
		$is_development_mode = Jetpack::is_development_mode();
1850
1851
		foreach ( $modules as $index => $module ) {
1852
			// If we're in dev mode, disable modules requiring a connection
1853
			if ( $is_development_mode ) {
1854
				// Prime the pump if we need to
1855
				if ( empty( $modules_data[ $module ] ) ) {
1856
					$modules_data[ $module ] = Jetpack::get_module( $module );
1857
				}
1858
				// If the module requires a connection, but we're in local mode, don't include it.
1859
				if ( $modules_data[ $module ]['requires_connection'] ) {
1860
					continue;
1861
				}
1862
			}
1863
1864
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1865
				continue;
1866
			}
1867
1868
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1869
				unset( $modules[ $index ] );
1870
				self::update_active_modules( array_values( $modules ) );
1871
				continue;
1872
			}
1873
1874
			/**
1875
			 * Fires when a specific module is loaded.
1876
			 * The dynamic part of the hook, $module, is the module slug.
1877
			 *
1878
			 * @since 1.1.0
1879
			 */
1880
			do_action( 'jetpack_module_loaded_' . $module );
1881
		}
1882
1883
		/**
1884
		 * Fires when all the modules are loaded.
1885
		 *
1886
		 * @since 1.1.0
1887
		 */
1888
		do_action( 'jetpack_modules_loaded' );
1889
1890
		// 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.
1891
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1892
	}
1893
1894
	/**
1895
	 * Check if Jetpack's REST API compat file should be included
1896
	 * @action plugins_loaded
1897
	 * @return null
1898
	 */
1899
	public function check_rest_api_compat() {
1900
		/**
1901
		 * Filters the list of REST API compat files to be included.
1902
		 *
1903
		 * @since 2.2.5
1904
		 *
1905
		 * @param array $args Array of REST API compat files to include.
1906
		 */
1907
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1908
1909
		if ( function_exists( 'bbpress' ) )
1910
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1911
1912
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1913
			require_once $_jetpack_rest_api_compat_include;
1914
	}
1915
1916
	/**
1917
	 * Gets all plugins currently active in values, regardless of whether they're
1918
	 * traditionally activated or network activated.
1919
	 *
1920
	 * @todo Store the result in core's object cache maybe?
1921
	 */
1922
	public static function get_active_plugins() {
1923
		$active_plugins = (array) get_option( 'active_plugins', array() );
1924
1925
		if ( is_multisite() ) {
1926
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1927
			// whereas active_plugins stores them in the values.
1928
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1929
			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...
1930
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1931
			}
1932
		}
1933
1934
		sort( $active_plugins );
1935
1936
		return array_unique( $active_plugins );
1937
	}
1938
1939
	/**
1940
	 * Gets and parses additional plugin data to send with the heartbeat data
1941
	 *
1942
	 * @since 3.8.1
1943
	 *
1944
	 * @return array Array of plugin data
1945
	 */
1946
	public static function get_parsed_plugin_data() {
1947
		if ( ! function_exists( 'get_plugins' ) ) {
1948
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1949
		}
1950
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1951
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1952
		$active_plugins = Jetpack::get_active_plugins();
1953
1954
		$plugins = array();
1955
		foreach ( $all_plugins as $path => $plugin_data ) {
1956
			$plugins[ $path ] = array(
1957
					'is_active' => in_array( $path, $active_plugins ),
1958
					'file'      => $path,
1959
					'name'      => $plugin_data['Name'],
1960
					'version'   => $plugin_data['Version'],
1961
					'author'    => $plugin_data['Author'],
1962
			);
1963
		}
1964
1965
		return $plugins;
1966
	}
1967
1968
	/**
1969
	 * Gets and parses theme data to send with the heartbeat data
1970
	 *
1971
	 * @since 3.8.1
1972
	 *
1973
	 * @return array Array of theme data
1974
	 */
1975
	public static function get_parsed_theme_data() {
1976
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1977
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1978
1979
		$themes = array();
1980
		foreach ( $all_themes as $slug => $theme_data ) {
1981
			$theme_headers = array();
1982
			foreach ( $header_keys as $header_key ) {
1983
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1984
			}
1985
1986
			$themes[ $slug ] = array(
1987
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1988
					'slug' => $slug,
1989
					'theme_root' => $theme_data->get_theme_root_uri(),
1990
					'parent' => $theme_data->parent(),
1991
					'headers' => $theme_headers
1992
			);
1993
		}
1994
1995
		return $themes;
1996
	}
1997
1998
	/**
1999
	 * Checks whether a specific plugin is active.
2000
	 *
2001
	 * We don't want to store these in a static variable, in case
2002
	 * there are switch_to_blog() calls involved.
2003
	 */
2004
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2005
		return in_array( $plugin, self::get_active_plugins() );
2006
	}
2007
2008
	/**
2009
	 * Check if Jetpack's Open Graph tags should be used.
2010
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2011
	 *
2012
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2013
	 * @action plugins_loaded
2014
	 * @return null
2015
	 */
2016
	public function check_open_graph() {
2017
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2018
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2019
		}
2020
2021
		$active_plugins = self::get_active_plugins();
2022
2023
		if ( ! empty( $active_plugins ) ) {
2024
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2025
				if ( in_array( $plugin, $active_plugins ) ) {
2026
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2027
					break;
2028
				}
2029
			}
2030
		}
2031
2032
		/**
2033
		 * Allow the addition of Open Graph Meta Tags to all pages.
2034
		 *
2035
		 * @since 2.0.3
2036
		 *
2037
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2038
		 */
2039
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2040
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2041
		}
2042
	}
2043
2044
	/**
2045
	 * Check if Jetpack's Twitter tags should be used.
2046
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2047
	 *
2048
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2049
	 * @action plugins_loaded
2050
	 * @return null
2051
	 */
2052
	public function check_twitter_tags() {
2053
2054
		$active_plugins = self::get_active_plugins();
2055
2056
		if ( ! empty( $active_plugins ) ) {
2057
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2058
				if ( in_array( $plugin, $active_plugins ) ) {
2059
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2060
					break;
2061
				}
2062
			}
2063
		}
2064
2065
		/**
2066
		 * Allow Twitter Card Meta tags to be disabled.
2067
		 *
2068
		 * @since 2.6.0
2069
		 *
2070
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2071
		 */
2072
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2073
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2074
		}
2075
	}
2076
2077
	/**
2078
	 * Allows plugins to submit security reports.
2079
 	 *
2080
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2081
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2082
	 * @param array   $args         See definitions above
2083
	 */
2084
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2085
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2086
	}
2087
2088
/* Jetpack Options API */
2089
2090
	public static function get_option_names( $type = 'compact' ) {
2091
		return Jetpack_Options::get_option_names( $type );
2092
	}
2093
2094
	/**
2095
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2096
 	 *
2097
	 * @param string $name    Option name
2098
	 * @param mixed  $default (optional)
2099
	 */
2100
	public static function get_option( $name, $default = false ) {
2101
		return Jetpack_Options::get_option( $name, $default );
2102
	}
2103
2104
	/**
2105
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2106
 	 *
2107
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2108
	 * @param string $name  Option name
2109
	 * @param mixed  $value Option value
2110
	 */
2111
	public static function update_option( $name, $value ) {
2112
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2113
		return Jetpack_Options::update_option( $name, $value );
2114
	}
2115
2116
	/**
2117
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2118
 	 *
2119
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2120
	 * @param array $array array( option name => option value, ... )
2121
	 */
2122
	public static function update_options( $array ) {
2123
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2124
		return Jetpack_Options::update_options( $array );
2125
	}
2126
2127
	/**
2128
	 * Deletes the given option.  May be passed multiple option names as an array.
2129
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2130
	 *
2131
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2132
	 * @param string|array $names
2133
	 */
2134
	public static function delete_option( $names ) {
2135
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2136
		return Jetpack_Options::delete_option( $names );
2137
	}
2138
2139
	/**
2140
	 * Enters a user token into the user_tokens option
2141
	 *
2142
	 * @param int $user_id
2143
	 * @param string $token
2144
	 * return bool
2145
	 */
2146
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2147
		// not designed for concurrent updates
2148
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2149
		if ( ! is_array( $user_tokens ) )
2150
			$user_tokens = array();
2151
		$user_tokens[$user_id] = $token;
2152
		if ( $is_master_user ) {
2153
			$master_user = $user_id;
2154
			$options     = compact( 'user_tokens', 'master_user' );
2155
		} else {
2156
			$options = compact( 'user_tokens' );
2157
		}
2158
		return Jetpack_Options::update_options( $options );
2159
	}
2160
2161
	/**
2162
	 * Returns an array of all PHP files in the specified absolute path.
2163
	 * Equivalent to glob( "$absolute_path/*.php" ).
2164
	 *
2165
	 * @param string $absolute_path The absolute path of the directory to search.
2166
	 * @return array Array of absolute paths to the PHP files.
2167
	 */
2168
	public static function glob_php( $absolute_path ) {
2169
		if ( function_exists( 'glob' ) ) {
2170
			return glob( "$absolute_path/*.php" );
2171
		}
2172
2173
		$absolute_path = untrailingslashit( $absolute_path );
2174
		$files = array();
2175
		if ( ! $dir = @opendir( $absolute_path ) ) {
2176
			return $files;
2177
		}
2178
2179
		while ( false !== $file = readdir( $dir ) ) {
2180
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2181
				continue;
2182
			}
2183
2184
			$file = "$absolute_path/$file";
2185
2186
			if ( ! is_file( $file ) ) {
2187
				continue;
2188
			}
2189
2190
			$files[] = $file;
2191
		}
2192
2193
		closedir( $dir );
2194
2195
		return $files;
2196
	}
2197
2198
	public static function activate_new_modules( $redirect = false ) {
2199
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2200
			return;
2201
		}
2202
2203
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2204 View Code Duplication
		if ( ! $jetpack_old_version ) {
2205
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2206
			/** This action is documented in class.jetpack.php */
2207
			do_action( 'updating_jetpack_version', $version, false );
2208
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2209
		}
2210
2211
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2212
2213
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2214
			return;
2215
		}
2216
2217
		$active_modules     = Jetpack::get_active_modules();
2218
		$reactivate_modules = array();
2219
		foreach ( $active_modules as $active_module ) {
2220
			$module = Jetpack::get_module( $active_module );
2221
			if ( ! isset( $module['changed'] ) ) {
2222
				continue;
2223
			}
2224
2225
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2226
				continue;
2227
			}
2228
2229
			$reactivate_modules[] = $active_module;
2230
			Jetpack::deactivate_module( $active_module );
2231
		}
2232
2233
		$new_version = JETPACK__VERSION . ':' . time();
2234
		/** This action is documented in class.jetpack.php */
2235
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2236
		Jetpack_Options::update_options(
2237
			array(
2238
				'version'     => $new_version,
2239
				'old_version' => $jetpack_old_version,
2240
			)
2241
		);
2242
2243
		Jetpack::state( 'message', 'modules_activated' );
2244
		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...
2245
2246
		if ( $redirect ) {
2247
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2248
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2249
				$page = $_GET['page'];
2250
			}
2251
2252
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2253
			exit;
2254
		}
2255
	}
2256
2257
	/**
2258
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2259
	 * Make sure to tuck away module "library" files in a sub-directory.
2260
	 */
2261
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2262
		static $modules = null;
2263
2264
		if ( ! isset( $modules ) ) {
2265
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2266
			// Use the cache if we're on the front-end and it's available...
2267
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2268
				$modules = $available_modules_option[ JETPACK__VERSION ];
2269
			} else {
2270
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2271
2272
				$modules = array();
2273
2274
				foreach ( $files as $file ) {
2275
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2276
						continue;
2277
					}
2278
2279
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2280
				}
2281
2282
				Jetpack_Options::update_option( 'available_modules', array(
2283
					JETPACK__VERSION => $modules,
2284
				) );
2285
			}
2286
		}
2287
2288
		/**
2289
		 * Filters the array of modules available to be activated.
2290
		 *
2291
		 * @since 2.4.0
2292
		 *
2293
		 * @param array $modules Array of available modules.
2294
		 * @param string $min_version Minimum version number required to use modules.
2295
		 * @param string $max_version Maximum version number required to use modules.
2296
		 */
2297
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2298
2299
		if ( ! $min_version && ! $max_version ) {
2300
			return array_keys( $mods );
2301
		}
2302
2303
		$r = array();
2304
		foreach ( $mods as $slug => $introduced ) {
2305
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2306
				continue;
2307
			}
2308
2309
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2310
				continue;
2311
			}
2312
2313
			$r[] = $slug;
2314
		}
2315
2316
		return $r;
2317
	}
2318
2319
	/**
2320
	 * Default modules loaded on activation.
2321
	 */
2322
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2323
		$return = array();
2324
2325
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2326
			$module_data = Jetpack::get_module( $module );
2327
2328
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2329
				case 'yes' :
2330
					$return[] = $module;
2331
					break;
2332
				case 'public' :
2333
					if ( Jetpack_Options::get_option( 'public' ) ) {
2334
						$return[] = $module;
2335
					}
2336
					break;
2337
				case 'no' :
2338
				default :
2339
					break;
2340
			}
2341
		}
2342
		/**
2343
		 * Filters the array of default modules.
2344
		 *
2345
		 * @since 2.5.0
2346
		 *
2347
		 * @param array $return Array of default modules.
2348
		 * @param string $min_version Minimum version number required to use modules.
2349
		 * @param string $max_version Maximum version number required to use modules.
2350
		 */
2351
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2352
	}
2353
2354
	/**
2355
	 * Checks activated modules during auto-activation to determine
2356
	 * if any of those modules are being deprecated.  If so, close
2357
	 * them out, and add any replacement modules.
2358
	 *
2359
	 * Runs at priority 99 by default.
2360
	 *
2361
	 * This is run late, so that it can still activate a module if
2362
	 * the new module is a replacement for another that the user
2363
	 * currently has active, even if something at the normal priority
2364
	 * would kibosh everything.
2365
	 *
2366
	 * @since 2.6
2367
	 * @uses jetpack_get_default_modules filter
2368
	 * @param array $modules
2369
	 * @return array
2370
	 */
2371
	function handle_deprecated_modules( $modules ) {
2372
		$deprecated_modules = array(
2373
			'debug'            => null,  // Closed out and moved to the debugger library.
2374
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2375
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2376
		);
2377
2378
		// Don't activate SSO if they never completed activating WPCC.
2379
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2380
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2381
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2382
				$deprecated_modules['wpcc'] = null;
2383
			}
2384
		}
2385
2386
		foreach ( $deprecated_modules as $module => $replacement ) {
2387
			if ( Jetpack::is_module_active( $module ) ) {
2388
				self::deactivate_module( $module );
2389
				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...
2390
					$modules[] = $replacement;
2391
				}
2392
			}
2393
		}
2394
2395
		return array_unique( $modules );
2396
	}
2397
2398
	/**
2399
	 * Checks activated plugins during auto-activation to determine
2400
	 * if any of those plugins are in the list with a corresponding module
2401
	 * that is not compatible with the plugin. The module will not be allowed
2402
	 * to auto-activate.
2403
	 *
2404
	 * @since 2.6
2405
	 * @uses jetpack_get_default_modules filter
2406
	 * @param array $modules
2407
	 * @return array
2408
	 */
2409
	function filter_default_modules( $modules ) {
2410
2411
		$active_plugins = self::get_active_plugins();
2412
2413
		if ( ! empty( $active_plugins ) ) {
2414
2415
			// For each module we'd like to auto-activate...
2416
			foreach ( $modules as $key => $module ) {
2417
				// If there are potential conflicts for it...
2418
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2419
					// For each potential conflict...
2420
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2421
						// If that conflicting plugin is active...
2422
						if ( in_array( $plugin, $active_plugins ) ) {
2423
							// Remove that item from being auto-activated.
2424
							unset( $modules[ $key ] );
2425
						}
2426
					}
2427
				}
2428
			}
2429
		}
2430
2431
		return $modules;
2432
	}
2433
2434
	/**
2435
	 * Extract a module's slug from its full path.
2436
	 */
2437
	public static function get_module_slug( $file ) {
2438
		return str_replace( '.php', '', basename( $file ) );
2439
	}
2440
2441
	/**
2442
	 * Generate a module's path from its slug.
2443
	 */
2444
	public static function get_module_path( $slug ) {
2445
		/**
2446
		 * Filters the path of a modules.
2447
		 *
2448
		 * @since 7.4.0
2449
		 *
2450
		 * @param array $return The absolute path to a module's root php file
2451
		 * @param string $slug The module slug
2452
		 */
2453
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2454
	}
2455
2456
	/**
2457
	 * Load module data from module file. Headers differ from WordPress
2458
	 * plugin headers to avoid them being identified as standalone
2459
	 * plugins on the WordPress plugins page.
2460
	 */
2461
	public static function get_module( $module ) {
2462
		$headers = array(
2463
			'name'                      => 'Module Name',
2464
			'description'               => 'Module Description',
2465
			'sort'                      => 'Sort Order',
2466
			'recommendation_order'      => 'Recommendation Order',
2467
			'introduced'                => 'First Introduced',
2468
			'changed'                   => 'Major Changes In',
2469
			'deactivate'                => 'Deactivate',
2470
			'free'                      => 'Free',
2471
			'requires_connection'       => 'Requires Connection',
2472
			'auto_activate'             => 'Auto Activate',
2473
			'module_tags'               => 'Module Tags',
2474
			'feature'                   => 'Feature',
2475
			'additional_search_queries' => 'Additional Search Queries',
2476
			'plan_classes'              => 'Plans',
2477
		);
2478
2479
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2480
2481
		$mod = Jetpack::get_file_data( $file, $headers );
2482
		if ( empty( $mod['name'] ) ) {
2483
			return false;
2484
		}
2485
2486
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2487
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2488
		$mod['deactivate']              = empty( $mod['deactivate'] );
2489
		$mod['free']                    = empty( $mod['free'] );
2490
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2491
2492
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2493
			$mod['auto_activate'] = 'No';
2494
		} else {
2495
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2496
		}
2497
2498
		if ( $mod['module_tags'] ) {
2499
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2500
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2501
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2502
		} else {
2503
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2504
		}
2505
2506 View Code Duplication
		if ( $mod['plan_classes'] ) {
2507
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2508
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2509
		} else {
2510
			$mod['plan_classes'] = array( 'free' );
2511
		}
2512
2513 View Code Duplication
		if ( $mod['feature'] ) {
2514
			$mod['feature'] = explode( ',', $mod['feature'] );
2515
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2516
		} else {
2517
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2518
		}
2519
2520
		/**
2521
		 * Filters the feature array on a module.
2522
		 *
2523
		 * This filter allows you to control where each module is filtered: Recommended,
2524
		 * and the default "Other" listing.
2525
		 *
2526
		 * @since 3.5.0
2527
		 *
2528
		 * @param array   $mod['feature'] The areas to feature this module:
2529
		 *     'Recommended' shows on the main Jetpack admin screen.
2530
		 *     'Other' should be the default if no other value is in the array.
2531
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2532
		 * @param array   $mod All the currently assembled module data.
2533
		 */
2534
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2535
2536
		/**
2537
		 * Filter the returned data about a module.
2538
		 *
2539
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2540
		 * so please be careful.
2541
		 *
2542
		 * @since 3.6.0
2543
		 *
2544
		 * @param array   $mod    The details of the requested module.
2545
		 * @param string  $module The slug of the module, e.g. sharedaddy
2546
		 * @param string  $file   The path to the module source file.
2547
		 */
2548
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2549
	}
2550
2551
	/**
2552
	 * Like core's get_file_data implementation, but caches the result.
2553
	 */
2554
	public static function get_file_data( $file, $headers ) {
2555
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2556
		$file_name = basename( $file );
2557
2558
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2559
2560
		$file_data_option = get_transient( $cache_key );
2561
2562
		if ( false === $file_data_option ) {
2563
			$file_data_option = array();
2564
		}
2565
2566
		$key           = md5( $file_name . serialize( $headers ) );
2567
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2568
2569
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2570
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2571
			return $file_data_option[ $key ];
2572
		}
2573
2574
		$data = get_file_data( $file, $headers );
2575
2576
		$file_data_option[ $key ] = $data;
2577
2578
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2579
2580
		return $data;
2581
	}
2582
2583
2584
	/**
2585
	 * Return translated module tag.
2586
	 *
2587
	 * @param string $tag Tag as it appears in each module heading.
2588
	 *
2589
	 * @return mixed
2590
	 */
2591
	public static function translate_module_tag( $tag ) {
2592
		return jetpack_get_module_i18n_tag( $tag );
2593
	}
2594
2595
	/**
2596
	 * Get i18n strings as a JSON-encoded string
2597
	 *
2598
	 * @return string The locale as JSON
2599
	 */
2600
	public static function get_i18n_data_json() {
2601
2602
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2603
		// JSON files with the file they should be included for. This is an md5
2604
		// of '_inc/build/admin.js'.
2605
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2606
2607
		$i18n_json =
2608
				   JETPACK__PLUGIN_DIR
2609
				   . 'languages/json/jetpack-'
2610
				   . get_user_locale()
2611
				   . '-'
2612
				   . $path_md5
2613
				   . '.json';
2614
2615
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2616
			$locale_data = @file_get_contents( $i18n_json );
2617
			if ( $locale_data ) {
2618
				return $locale_data;
2619
			}
2620
		}
2621
2622
		// Return valid empty Jed locale
2623
		return '{ "locale_data": { "messages": { "": {} } } }';
2624
	}
2625
2626
	/**
2627
	 * Add locale data setup to wp-i18n
2628
	 *
2629
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2630
	 *
2631
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2632
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2633
	 *
2634
	 * This method provides a safe way to request the setup multiple times but add the script at
2635
	 * most once.
2636
	 *
2637
	 * @since 6.7.0
2638
	 *
2639
	 * @return void
2640
	 */
2641
	public static function setup_wp_i18n_locale_data() {
2642
		static $script_added = false;
2643
		if ( ! $script_added ) {
2644
			$script_added = true;
2645
			wp_add_inline_script(
2646
				'wp-i18n',
2647
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2648
			);
2649
		}
2650
	}
2651
2652
	/**
2653
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2654
	 *
2655
	 * @since 3.9.2
2656
	 *
2657
	 * @param array $modules
2658
	 *
2659
	 * @return string|void
2660
	 */
2661
	public static function get_translated_modules( $modules ) {
2662
		foreach ( $modules as $index => $module ) {
2663
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2664
			if ( isset( $module['name'] ) ) {
2665
				$modules[ $index ]['name'] = $i18n_module['name'];
2666
			}
2667
			if ( isset( $module['description'] ) ) {
2668
				$modules[ $index ]['description'] = $i18n_module['description'];
2669
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2670
			}
2671
		}
2672
		return $modules;
2673
	}
2674
2675
	/**
2676
	 * Get a list of activated modules as an array of module slugs.
2677
	 */
2678
	public static function get_active_modules() {
2679
		$active = Jetpack_Options::get_option( 'active_modules' );
2680
2681
		if ( ! is_array( $active ) ) {
2682
			$active = array();
2683
		}
2684
2685
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2686
			$active[] = 'vaultpress';
2687
		} else {
2688
			$active = array_diff( $active, array( 'vaultpress' ) );
2689
		}
2690
2691
		//If protect is active on the main site of a multisite, it should be active on all sites.
2692
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2693
			$active[] = 'protect';
2694
		}
2695
2696
		/**
2697
		 * Allow filtering of the active modules.
2698
		 *
2699
		 * Gives theme and plugin developers the power to alter the modules that
2700
		 * are activated on the fly.
2701
		 *
2702
		 * @since 5.8.0
2703
		 *
2704
		 * @param array $active Array of active module slugs.
2705
		 */
2706
		$active = apply_filters( 'jetpack_active_modules', $active );
2707
2708
		return array_unique( $active );
2709
	}
2710
2711
	/**
2712
	 * Check whether or not a Jetpack module is active.
2713
	 *
2714
	 * @param string $module The slug of a Jetpack module.
2715
	 * @return bool
2716
	 *
2717
	 * @static
2718
	 */
2719
	public static function is_module_active( $module ) {
2720
		return in_array( $module, self::get_active_modules() );
2721
	}
2722
2723
	public static function is_module( $module ) {
2724
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2725
	}
2726
2727
	/**
2728
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2729
	 *
2730
	 * @param bool $catch True to start catching, False to stop.
2731
	 *
2732
	 * @static
2733
	 */
2734
	public static function catch_errors( $catch ) {
2735
		static $display_errors, $error_reporting;
2736
2737
		if ( $catch ) {
2738
			$display_errors  = @ini_set( 'display_errors', 1 );
2739
			$error_reporting = @error_reporting( E_ALL );
2740
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2741
		} else {
2742
			@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...
2743
			@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...
2744
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2745
		}
2746
	}
2747
2748
	/**
2749
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2750
	 */
2751
	public static function catch_errors_on_shutdown() {
2752
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2753
	}
2754
2755
	/**
2756
	 * Rewrite any string to make paths easier to read.
2757
	 *
2758
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2759
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2760
	 *
2761
	 * @param $string
2762
	 * @return mixed
2763
	 */
2764
	public static function alias_directories( $string ) {
2765
		// ABSPATH has a trailing slash.
2766
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2767
		// WP_CONTENT_DIR does not have a trailing slash.
2768
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2769
2770
		return $string;
2771
	}
2772
2773
	public static function activate_default_modules(
2774
		$min_version = false,
2775
		$max_version = false,
2776
		$other_modules = array(),
2777
		$redirect = true,
2778
		$send_state_messages = true
2779
	) {
2780
		$jetpack = Jetpack::init();
2781
2782
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2783
		$modules = array_merge( $other_modules, $modules );
2784
2785
		// Look for standalone plugins and disable if active.
2786
2787
		$to_deactivate = array();
2788
		foreach ( $modules as $module ) {
2789
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2790
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2791
			}
2792
		}
2793
2794
		$deactivated = array();
2795
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2796
			list( $probable_file, $probable_title ) = $deactivate_me;
2797
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2798
				$deactivated[] = $module;
2799
			}
2800
		}
2801
2802
		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...
2803
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2804
2805
			$url = add_query_arg(
2806
				array(
2807
					'action'   => 'activate_default_modules',
2808
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2809
				),
2810
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2811
			);
2812
			wp_safe_redirect( $url );
2813
			exit;
2814
		}
2815
2816
		/**
2817
		 * Fires before default modules are activated.
2818
		 *
2819
		 * @since 1.9.0
2820
		 *
2821
		 * @param string $min_version Minimum version number required to use modules.
2822
		 * @param string $max_version Maximum version number required to use modules.
2823
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2824
		 */
2825
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2826
2827
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2828
		if ( $send_state_messages ) {
2829
			Jetpack::restate();
2830
			Jetpack::catch_errors( true );
2831
		}
2832
2833
		$active = Jetpack::get_active_modules();
2834
2835
		foreach ( $modules as $module ) {
2836
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2837
				$active[] = $module;
2838
				self::update_active_modules( $active );
2839
				continue;
2840
			}
2841
2842
			if ( $send_state_messages && in_array( $module, $active ) ) {
2843
				$module_info = Jetpack::get_module( $module );
2844 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2845
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2846
					if ( $active_state = Jetpack::state( $state ) ) {
2847
						$active_state = explode( ',', $active_state );
2848
					} else {
2849
						$active_state = array();
2850
					}
2851
					$active_state[] = $module;
2852
					Jetpack::state( $state, implode( ',', $active_state ) );
2853
				}
2854
				continue;
2855
			}
2856
2857
			$file = Jetpack::get_module_path( $module );
2858
			if ( ! file_exists( $file ) ) {
2859
				continue;
2860
			}
2861
2862
			// we'll override this later if the plugin can be included without fatal error
2863
			if ( $redirect ) {
2864
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2865
			}
2866
2867
			if ( $send_state_messages ) {
2868
				Jetpack::state( 'error', 'module_activation_failed' );
2869
				Jetpack::state( 'module', $module );
2870
			}
2871
2872
			ob_start();
2873
			require_once $file;
2874
2875
			$active[] = $module;
2876
2877 View Code Duplication
			if ( $send_state_messages ) {
2878
2879
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2880
				if ( $active_state = Jetpack::state( $state ) ) {
2881
					$active_state = explode( ',', $active_state );
2882
				} else {
2883
					$active_state = array();
2884
				}
2885
				$active_state[] = $module;
2886
				Jetpack::state( $state, implode( ',', $active_state ) );
2887
			}
2888
2889
			Jetpack::update_active_modules( $active );
2890
2891
			ob_end_clean();
2892
		}
2893
2894
		if ( $send_state_messages ) {
2895
			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...
2896
			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...
2897
		}
2898
2899
		Jetpack::catch_errors( false );
2900
		/**
2901
		 * Fires when default modules are activated.
2902
		 *
2903
		 * @since 1.9.0
2904
		 *
2905
		 * @param string $min_version Minimum version number required to use modules.
2906
		 * @param string $max_version Maximum version number required to use modules.
2907
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2908
		 */
2909
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2910
	}
2911
2912
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2913
		/**
2914
		 * Fires before a module is activated.
2915
		 *
2916
		 * @since 2.6.0
2917
		 *
2918
		 * @param string $module Module slug.
2919
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2920
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2921
		 */
2922
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2923
2924
		$jetpack = Jetpack::init();
2925
2926
		if ( ! strlen( $module ) )
2927
			return false;
2928
2929
		if ( ! Jetpack::is_module( $module ) )
2930
			return false;
2931
2932
		// If it's already active, then don't do it again
2933
		$active = Jetpack::get_active_modules();
2934
		foreach ( $active as $act ) {
2935
			if ( $act == $module )
2936
				return true;
2937
		}
2938
2939
		$module_data = Jetpack::get_module( $module );
2940
2941
		if ( ! Jetpack::is_active() ) {
2942
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2943
				return false;
2944
2945
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2946
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2947
				return false;
2948
		}
2949
2950
		// Check and see if the old plugin is active
2951
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2952
			// Deactivate the old plugin
2953
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2954
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2955
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2956
				Jetpack::state( 'deactivated_plugins', $module );
2957
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2958
				exit;
2959
			}
2960
		}
2961
2962
		// Protect won't work with mis-configured IPs
2963
		if ( 'protect' === $module ) {
2964
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2965
			if ( ! jetpack_protect_get_ip() ) {
2966
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2967
				return false;
2968
			}
2969
		}
2970
2971
		if ( ! Jetpack_Plan::supports( $module ) ) {
2972
			return false;
2973
		}
2974
2975
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2976
		Jetpack::state( 'module', $module );
2977
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2978
2979
		Jetpack::catch_errors( true );
2980
		ob_start();
2981
		require Jetpack::get_module_path( $module );
2982
		/** This action is documented in class.jetpack.php */
2983
		do_action( 'jetpack_activate_module', $module );
2984
		$active[] = $module;
2985
		Jetpack::update_active_modules( $active );
2986
2987
		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...
2988
		ob_end_clean();
2989
		Jetpack::catch_errors( false );
2990
2991
		if ( $redirect ) {
2992
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2993
		}
2994
		if ( $exit ) {
2995
			exit;
2996
		}
2997
		return true;
2998
	}
2999
3000
	function activate_module_actions( $module ) {
3001
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3002
	}
3003
3004
	public static function deactivate_module( $module ) {
3005
		/**
3006
		 * Fires when a module is deactivated.
3007
		 *
3008
		 * @since 1.9.0
3009
		 *
3010
		 * @param string $module Module slug.
3011
		 */
3012
		do_action( 'jetpack_pre_deactivate_module', $module );
3013
3014
		$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...
3015
3016
		$active = Jetpack::get_active_modules();
3017
		$new    = array_filter( array_diff( $active, (array) $module ) );
3018
3019
		return self::update_active_modules( $new );
3020
	}
3021
3022
	public static function enable_module_configurable( $module ) {
3023
		$module = Jetpack::get_module_slug( $module );
3024
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3025
	}
3026
3027
	/**
3028
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3029
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3030
	 *
3031
	 * @param string $module Module slug
3032
	 * @return string $url module configuration URL
3033
	 */
3034
	public static function module_configuration_url( $module ) {
3035
		$module = Jetpack::get_module_slug( $module );
3036
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3037
		/**
3038
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3039
		 *
3040
		 * @since 6.9.0
3041
		 *
3042
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3043
		 */
3044
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3045
3046
		return $url;
3047
	}
3048
3049
/* Installation */
3050
	public static function bail_on_activation( $message, $deactivate = true ) {
3051
?>
3052
<!doctype html>
3053
<html>
3054
<head>
3055
<meta charset="<?php bloginfo( 'charset' ); ?>">
3056
<style>
3057
* {
3058
	text-align: center;
3059
	margin: 0;
3060
	padding: 0;
3061
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3062
}
3063
p {
3064
	margin-top: 1em;
3065
	font-size: 18px;
3066
}
3067
</style>
3068
<body>
3069
<p><?php echo esc_html( $message ); ?></p>
3070
</body>
3071
</html>
3072
<?php
3073
		if ( $deactivate ) {
3074
			$plugins = get_option( 'active_plugins' );
3075
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3076
			$update  = false;
3077
			foreach ( $plugins as $i => $plugin ) {
3078
				if ( $plugin === $jetpack ) {
3079
					$plugins[$i] = false;
3080
					$update = true;
3081
				}
3082
			}
3083
3084
			if ( $update ) {
3085
				update_option( 'active_plugins', array_filter( $plugins ) );
3086
			}
3087
		}
3088
		exit;
3089
	}
3090
3091
	/**
3092
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3093
	 * @static
3094
	 */
3095
	public static function plugin_activation( $network_wide ) {
3096
		Jetpack_Options::update_option( 'activated', 1 );
3097
3098
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3099
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3100
		}
3101
3102
		if ( $network_wide )
3103
			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...
3104
3105
		// For firing one-off events (notices) immediately after activation
3106
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3107
3108
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3109
3110
		Jetpack::plugin_initialize();
3111
	}
3112
3113
	public static function get_activation_source( $referer_url ) {
3114
3115
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3116
			return array( 'wp-cli', null );
3117
		}
3118
3119
		$referer = parse_url( $referer_url );
3120
3121
		$source_type = 'unknown';
3122
		$source_query = null;
3123
3124
		if ( ! is_array( $referer ) ) {
3125
			return array( $source_type, $source_query );
3126
		}
3127
3128
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3129
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3130
3131
		if ( isset( $referer['query'] ) ) {
3132
			parse_str( $referer['query'], $query_parts );
3133
		} else {
3134
			$query_parts = array();
3135
		}
3136
3137
		if ( $plugins_path === $referer['path'] ) {
3138
			$source_type = 'list';
3139
		} elseif ( $plugins_install_path === $referer['path'] ) {
3140
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3141
			switch( $tab ) {
3142
				case 'popular':
3143
					$source_type = 'popular';
3144
					break;
3145
				case 'recommended':
3146
					$source_type = 'recommended';
3147
					break;
3148
				case 'favorites':
3149
					$source_type = 'favorites';
3150
					break;
3151
				case 'search':
3152
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3153
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3154
					break;
3155
				default:
3156
					$source_type = 'featured';
3157
			}
3158
		}
3159
3160
		return array( $source_type, $source_query );
3161
	}
3162
3163
	/**
3164
	 * Runs before bumping version numbers up to a new version
3165
	 * @param  string $version    Version:timestamp
3166
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3167
	 * @return null              [description]
3168
	 */
3169
	public static function do_version_bump( $version, $old_version ) {
3170
		if ( ! $old_version ) { // For new sites
3171
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3172
		}
3173
	}
3174
3175
	/**
3176
	 * Sets the internal version number and activation state.
3177
	 * @static
3178
	 */
3179
	public static function plugin_initialize() {
3180
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3181
			Jetpack_Options::update_option( 'activated', 2 );
3182
		}
3183
3184 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3185
			$version = $old_version = JETPACK__VERSION . ':' . time();
3186
			/** This action is documented in class.jetpack.php */
3187
			do_action( 'updating_jetpack_version', $version, false );
3188
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3189
		}
3190
3191
		Jetpack::load_modules();
3192
3193
		Jetpack_Options::delete_option( 'do_activate' );
3194
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3195
	}
3196
3197
	/**
3198
	 * Removes all connection options
3199
	 * @static
3200
	 */
3201
	public static function plugin_deactivation( ) {
3202
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3203
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3204
			Jetpack_Network::init()->deactivate();
3205
		} else {
3206
			Jetpack::disconnect( false );
3207
			//Jetpack_Heartbeat::init()->deactivate();
3208
		}
3209
	}
3210
3211
	/**
3212
	 * Disconnects from the Jetpack servers.
3213
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3214
	 * @static
3215
	 */
3216
	public static function disconnect( $update_activated_state = true ) {
3217
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3218
		$connection = self::connection();
3219
		$connection->clean_nonces( true );
3220
3221
		// If the site is in an IDC because sync is not allowed,
3222
		// let's make sure to not disconnect the production site.
3223
		if ( ! self::validate_sync_error_idc_option() ) {
3224
			$tracking = new Tracking();
3225
			$tracking->record_user_event( 'disconnect_site', array() );
3226
			Jetpack::load_xml_rpc_client();
3227
			$xml = new Jetpack_IXR_Client();
3228
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3229
		}
3230
3231
		Jetpack_Options::delete_option(
3232
			array(
3233
				'blog_token',
3234
				'user_token',
3235
				'user_tokens',
3236
				'master_user',
3237
				'time_diff',
3238
				'fallback_no_verify_ssl_certs',
3239
			)
3240
		);
3241
3242
		Jetpack_IDC::clear_all_idc_options();
3243
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3244
3245
		if ( $update_activated_state ) {
3246
			Jetpack_Options::update_option( 'activated', 4 );
3247
		}
3248
3249
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3250
			// Check then record unique disconnection if site has never been disconnected previously
3251
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3252
				$jetpack_unique_connection['disconnected'] = 1;
3253
			} else {
3254
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3255
					//track unique disconnect
3256
					$jetpack = Jetpack::init();
3257
3258
					$jetpack->stat( 'connections', 'unique-disconnect' );
3259
					$jetpack->do_stats( 'server_side' );
3260
				}
3261
				// increment number of times disconnected
3262
				$jetpack_unique_connection['disconnected'] += 1;
3263
			}
3264
3265
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3266
		}
3267
3268
		// Delete cached connected user data
3269
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3270
		delete_transient( $transient_key );
3271
3272
		// Delete all the sync related data. Since it could be taking up space.
3273
		Sender::get_instance()->uninstall();
3274
3275
		// Disable the Heartbeat cron
3276
		Jetpack_Heartbeat::init()->deactivate();
3277
	}
3278
3279
	/**
3280
	 * Unlinks the current user from the linked WordPress.com user.
3281
	 *
3282
	 * @deprecated since 7.7
3283
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3284
	 *
3285
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|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...
3286
	 * @return Boolean Whether the disconnection of the user was successful.
3287
	 */
3288
	public static function unlink_user( $user_id = null ) {
3289
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3290
		return Connection_Manager::disconnect_user( $user_id );
3291
	}
3292
3293
	/**
3294
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3295
	 */
3296
	public static function try_registration() {
3297
		// The user has agreed to the TOS at some point by now.
3298
		Jetpack_Options::update_option( 'tos_agreed', true );
3299
3300
		// Let's get some testing in beta versions and such.
3301
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3302
			// Before attempting to connect, let's make sure that the domains are viable.
3303
			$domains_to_check = array_unique( array(
3304
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3305
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3306
			) );
3307
			foreach ( $domains_to_check as $domain ) {
3308
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3307 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...
3309
				if ( is_wp_error( $result ) ) {
3310
					return $result;
3311
				}
3312
			}
3313
		}
3314
3315
		$result = Jetpack::register();
3316
3317
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3318
		if ( ! $result || is_wp_error( $result ) ) {
3319
			return $result;
3320
		} else {
3321
			return true;
3322
		}
3323
	}
3324
3325
	/**
3326
	 * Tracking an internal event log. Try not to put too much chaff in here.
3327
	 *
3328
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3329
	 */
3330
	public static function log( $code, $data = null ) {
3331
		// only grab the latest 200 entries
3332
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3333
3334
		// Append our event to the log
3335
		$log_entry = array(
3336
			'time'    => time(),
3337
			'user_id' => get_current_user_id(),
3338
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3339
			'code'    => $code,
3340
		);
3341
		// Don't bother storing it unless we've got some.
3342
		if ( ! is_null( $data ) ) {
3343
			$log_entry['data'] = $data;
3344
		}
3345
		$log[] = $log_entry;
3346
3347
		// Try add_option first, to make sure it's not autoloaded.
3348
		// @todo: Add an add_option method to Jetpack_Options
3349
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3350
			Jetpack_Options::update_option( 'log', $log );
3351
		}
3352
3353
		/**
3354
		 * Fires when Jetpack logs an internal event.
3355
		 *
3356
		 * @since 3.0.0
3357
		 *
3358
		 * @param array $log_entry {
3359
		 *	Array of details about the log entry.
3360
		 *
3361
		 *	@param string time Time of the event.
3362
		 *	@param int user_id ID of the user who trigerred the event.
3363
		 *	@param int blog_id Jetpack Blog ID.
3364
		 *	@param string code Unique name for the event.
3365
		 *	@param string data Data about the event.
3366
		 * }
3367
		 */
3368
		do_action( 'jetpack_log_entry', $log_entry );
3369
	}
3370
3371
	/**
3372
	 * Get the internal event log.
3373
	 *
3374
	 * @param $event (string) - only return the specific log events
3375
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3376
	 *
3377
	 * @return array of log events || WP_Error for invalid params
3378
	 */
3379
	public static function get_log( $event = false, $num = false ) {
3380
		if ( $event && ! is_string( $event ) ) {
3381
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

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

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

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

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

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

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

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

Loading history...
3386
		}
3387
3388
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3389
3390
		// If nothing set - act as it did before, otherwise let's start customizing the output
3391
		if ( ! $num && ! $event ) {
3392
			return $entire_log;
3393
		} else {
3394
			$entire_log = array_reverse( $entire_log );
3395
		}
3396
3397
		$custom_log_output = array();
3398
3399
		if ( $event ) {
3400
			foreach ( $entire_log as $log_event ) {
3401
				if ( $event == $log_event[ 'code' ] ) {
3402
					$custom_log_output[] = $log_event;
3403
				}
3404
			}
3405
		} else {
3406
			$custom_log_output = $entire_log;
3407
		}
3408
3409
		if ( $num ) {
3410
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3411
		}
3412
3413
		return $custom_log_output;
3414
	}
3415
3416
	/**
3417
	 * Log modification of important settings.
3418
	 */
3419
	public static function log_settings_change( $option, $old_value, $value ) {
3420
		switch( $option ) {
3421
			case 'jetpack_sync_non_public_post_stati':
3422
				self::log( $option, $value );
3423
				break;
3424
		}
3425
	}
3426
3427
	/**
3428
	 * Return stat data for WPCOM sync
3429
	 */
3430
	public static function get_stat_data( $encode = true, $extended = true ) {
3431
		$data = Jetpack_Heartbeat::generate_stats_array();
3432
3433
		if ( $extended ) {
3434
			$additional_data = self::get_additional_stat_data();
3435
			$data = array_merge( $data, $additional_data );
3436
		}
3437
3438
		if ( $encode ) {
3439
			return json_encode( $data );
3440
		}
3441
3442
		return $data;
3443
	}
3444
3445
	/**
3446
	 * Get additional stat data to sync to WPCOM
3447
	 */
3448
	public static function get_additional_stat_data( $prefix = '' ) {
3449
		$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...
3450
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3451
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3452
		$return["{$prefix}site-count"]     = 0;
3453
3454
		if ( function_exists( 'get_blog_count' ) ) {
3455
			$return["{$prefix}site-count"] = get_blog_count();
3456
		}
3457
		return $return;
3458
	}
3459
3460
	private static function get_site_user_count() {
3461
		global $wpdb;
3462
3463
		if ( function_exists( 'wp_is_large_network' ) ) {
3464
			if ( wp_is_large_network( 'users' ) ) {
3465
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3466
			}
3467
		}
3468
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3469
			// It wasn't there, so regenerate the data and save the transient
3470
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3471
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3472
		}
3473
		return $user_count;
3474
	}
3475
3476
	/* Admin Pages */
3477
3478
	function admin_init() {
3479
		// If the plugin is not connected, display a connect message.
3480
		if (
3481
			// the plugin was auto-activated and needs its candy
3482
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3483
		||
3484
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3485
			! Jetpack_Options::get_option( 'activated' )
3486
		) {
3487
			Jetpack::plugin_initialize();
3488
		}
3489
3490
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3491
			Jetpack_Connection_Banner::init();
3492
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3493
			// Upgrade: 1.1 -> 1.1.1
3494
			// Check and see if host can verify the Jetpack servers' SSL certificate
3495
			$args = array();
3496
			$connection = self::connection();
3497
			Client::_wp_remote_request(
3498
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3499
				$args,
3500
				true
3501
			);
3502
		}
3503
3504
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3505
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3506
		}
3507
3508
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3509
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3510
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3511
3512
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3513
			// Artificially throw errors in certain whitelisted cases during plugin activation
3514
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3515
		}
3516
3517
		// Add custom column in wp-admin/users.php to show whether user is linked.
3518
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3519
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3520
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3521
	}
3522
3523
	function admin_body_class( $admin_body_class = '' ) {
3524
		$classes = explode( ' ', trim( $admin_body_class ) );
3525
3526
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3527
3528
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3529
		return " $admin_body_class ";
3530
	}
3531
3532
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3533
		return $admin_body_class . ' jetpack-pagestyles ';
3534
	}
3535
3536
	/**
3537
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3538
	 * This function artificially throws errors for such cases (whitelisted).
3539
	 *
3540
	 * @param string $plugin The activated plugin.
3541
	 */
3542
	function throw_error_on_activate_plugin( $plugin ) {
3543
		$active_modules = Jetpack::get_active_modules();
3544
3545
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3546
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3547
			$throw = false;
3548
3549
			// Try and make sure it really was the stats plugin
3550
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3551
				if ( 'stats.php' == basename( $plugin ) ) {
3552
					$throw = true;
3553
				}
3554
			} else {
3555
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3556
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3557
					$throw = true;
3558
				}
3559
			}
3560
3561
			if ( $throw ) {
3562
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3563
			}
3564
		}
3565
	}
3566
3567
	function intercept_plugin_error_scrape_init() {
3568
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3569
	}
3570
3571
	function intercept_plugin_error_scrape( $action, $result ) {
3572
		if ( ! $result ) {
3573
			return;
3574
		}
3575
3576
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3577
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3578
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3579
			}
3580
		}
3581
	}
3582
3583
	/**
3584
	 * Register the remote file upload request handlers, if needed.
3585
	 *
3586
	 * @access public
3587
	 */
3588
	public function add_remote_request_handlers() {
3589
		// Remote file uploads are allowed only via AJAX requests.
3590
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3591
			return;
3592
		}
3593
3594
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3595
		$remote_request_actions = array(
3596
			'jetpack_upload_file',
3597
			'jetpack_update_file',
3598
		);
3599
3600
		// phpcs:ignore WordPress.Security.NonceVerification
3601
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3602
			return;
3603
		}
3604
3605
		// Require Jetpack authentication for the remote file upload AJAX requests.
3606
		self::connection()->require_jetpack_authentication();
3607
3608
		// Register the remote file upload AJAX handlers.
3609
		foreach ( $remote_request_actions as $action ) {
3610
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3611
		}
3612
	}
3613
3614
	/**
3615
	 * Handler for Jetpack remote file uploads.
3616
	 *
3617
	 * @access public
3618
	 */
3619
	public function remote_request_handlers() {
3620
		$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...
3621
3622
		switch ( current_filter() ) {
3623
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3624
			$response = $this->upload_handler();
3625
			break;
3626
3627
		case 'wp_ajax_nopriv_jetpack_update_file' :
3628
			$response = $this->upload_handler( true );
3629
			break;
3630
		default :
3631
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_handler'.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
3643
3644
			if ( ! is_int( $status_code ) ) {
3645
				$status_code = 400;
3646
			}
3647
3648
			status_header( $status_code );
3649
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3650
		}
3651
3652
		status_header( 200 );
3653
		if ( true === $response ) {
3654
			exit;
3655
		}
3656
3657
		die( json_encode( (object) $response ) );
3658
	}
3659
3660
	/**
3661
	 * Uploads a file gotten from the global $_FILES.
3662
	 * If `$update_media_item` is true and `post_id` is defined
3663
	 * the attachment file of the media item (gotten through of the post_id)
3664
	 * will be updated instead of add a new one.
3665
	 *
3666
	 * @param  boolean $update_media_item - update media attachment
3667
	 * @return array - An array describing the uploadind files process
3668
	 */
3669
	function upload_handler( $update_media_item = false ) {
3670
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3671
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 405.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
3692
			}
3693
		}
3694
3695
		$media_keys = array_keys( $_FILES['media'] );
3696
3697
		$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...
3698
		if ( ! $token || is_wp_error( $token ) ) {
3699
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
3700
		}
3701
3702
		$uploaded_files = array();
3703
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3704
		unset( $GLOBALS['post'] );
3705
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3706
			$file = array();
3707
			foreach ( $media_keys as $media_key ) {
3708
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3709
			}
3710
3711
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3712
3713
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3714
			if ( $hmac_provided !== $hmac_file ) {
3715
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3716
				continue;
3717
			}
3718
3719
			$_FILES['.jetpack.upload.'] = $file;
3720
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3721
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3722
				$post_id = 0;
3723
			}
3724
3725
			if ( $update_media_item ) {
3726
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3727
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'invalid_input'.

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

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

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

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

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

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

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

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

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

Loading history...
4003
4004
					/**
4005
					 * Jetpack registration Error.
4006
					 *
4007
					 * @since 7.5.0
4008
					 *
4009
					 * @param string|int $error The error code.
4010
					 * @param \WP_Error $registered The error object.
4011
					 */
4012
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4013
					break;
4014
				}
4015
4016
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4017
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4018
4019
				/**
4020
				 * Jetpack registration Success.
4021
				 *
4022
				 * @since 7.5.0
4023
				 *
4024
				 * @param string $from 'from' GET parameter;
4025
				 */
4026
				do_action( 'jetpack_connection_register_success', $from );
4027
4028
				$url = $this->build_connect_url( true, $redirect, $from );
4029
4030
				if ( ! empty( $_GET['onboarding'] ) ) {
4031
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4032
				}
4033
4034
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4035
					$url = add_query_arg( 'auth_approved', 'true', $url );
4036
				}
4037
4038
				wp_redirect( $url );
4039
				exit;
4040
			case 'activate' :
4041
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4042
					$error = 'cheatin';
4043
					break;
4044
				}
4045
4046
				$module = stripslashes( $_GET['module'] );
4047
				check_admin_referer( "jetpack_activate-$module" );
4048
				Jetpack::log( 'activate', $module );
4049
				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...
4050
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4051
				}
4052
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4053
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4054
				exit;
4055
			case 'activate_default_modules' :
4056
				check_admin_referer( 'activate_default_modules' );
4057
				Jetpack::log( 'activate_default_modules' );
4058
				Jetpack::restate();
4059
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4060
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4061
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4062
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4063
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4064
				exit;
4065
			case 'disconnect' :
4066
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4067
					$error = 'cheatin';
4068
					break;
4069
				}
4070
4071
				check_admin_referer( 'jetpack-disconnect' );
4072
				Jetpack::log( 'disconnect' );
4073
				Jetpack::disconnect();
4074
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4075
				exit;
4076
			case 'reconnect' :
4077
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4078
					$error = 'cheatin';
4079
					break;
4080
				}
4081
4082
				check_admin_referer( 'jetpack-reconnect' );
4083
				Jetpack::log( 'reconnect' );
4084
				$this->disconnect();
4085
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4086
				exit;
4087 View Code Duplication
			case 'deactivate' :
4088
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4089
					$error = 'cheatin';
4090
					break;
4091
				}
4092
4093
				$modules = stripslashes( $_GET['module'] );
4094
				check_admin_referer( "jetpack_deactivate-$modules" );
4095
				foreach ( explode( ',', $modules ) as $module ) {
4096
					Jetpack::log( 'deactivate', $module );
4097
					Jetpack::deactivate_module( $module );
4098
					Jetpack::state( 'message', 'module_deactivated' );
4099
				}
4100
				Jetpack::state( 'module', $modules );
4101
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4102
				exit;
4103
			case 'unlink' :
4104
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4105
				check_admin_referer( 'jetpack-unlink' );
4106
				Jetpack::log( 'unlink' );
4107
				Connection_Manager::disconnect_user();
4108
				Jetpack::state( 'message', 'unlinked' );
4109
				if ( 'sub-unlink' == $redirect ) {
4110
					wp_safe_redirect( admin_url() );
4111
				} else {
4112
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4113
				}
4114
				exit;
4115
			case 'onboard' :
4116
				if ( ! current_user_can( 'manage_options' ) ) {
4117
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4118
				} else {
4119
					Jetpack::create_onboarding_token();
4120
					$url = $this->build_connect_url( true );
4121
4122
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4123
						$url = add_query_arg( 'onboarding', $token, $url );
4124
					}
4125
4126
					$calypso_env = $this->get_calypso_env();
4127
					if ( ! empty( $calypso_env ) ) {
4128
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4129
					}
4130
4131
					wp_redirect( $url );
4132
					exit;
4133
				}
4134
				exit;
4135
			default:
4136
				/**
4137
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4138
				 *
4139
				 * @since 2.6.0
4140
				 *
4141
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4142
				 */
4143
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4144
			}
4145
		}
4146
4147
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4148
			self::activate_new_modules( true );
4149
		}
4150
4151
		$message_code = Jetpack::state( 'message' );
4152
		if ( Jetpack::state( 'optin-manage' ) ) {
4153
			$activated_manage = $message_code;
4154
			$message_code = 'jetpack-manage';
4155
		}
4156
4157
		switch ( $message_code ) {
4158
		case 'jetpack-manage':
4159
			$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>';
4160
			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...
4161
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4162
			}
4163
			break;
4164
4165
		}
4166
4167
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4168
4169
		if ( ! empty( $deactivated_plugins ) ) {
4170
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4171
			$deactivated_titles  = array();
4172
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4173
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4174
					continue;
4175
				}
4176
4177
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4178
			}
4179
4180
			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...
4181
				if ( $this->message ) {
4182
					$this->message .= "<br /><br />\n";
4183
				}
4184
4185
				$this->message .= wp_sprintf(
4186
					_n(
4187
						'Jetpack contains the most recent version of the old %l plugin.',
4188
						'Jetpack contains the most recent versions of the old %l plugins.',
4189
						count( $deactivated_titles ),
4190
						'jetpack'
4191
					),
4192
					$deactivated_titles
4193
				);
4194
4195
				$this->message .= "<br />\n";
4196
4197
				$this->message .= _n(
4198
					'The old version has been deactivated and can be removed from your site.',
4199
					'The old versions have been deactivated and can be removed from your site.',
4200
					count( $deactivated_titles ),
4201
					'jetpack'
4202
				);
4203
			}
4204
		}
4205
4206
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4207
4208
		if ( $this->message || $this->error || $this->privacy_checks ) {
4209
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4210
		}
4211
4212
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4213
	}
4214
4215
	function admin_notices() {
4216
4217
		if ( $this->error ) {
4218
?>
4219
<div id="message" class="jetpack-message jetpack-err">
4220
	<div class="squeezer">
4221
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4222
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4223
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4224
<?php	endif; ?>
4225
	</div>
4226
</div>
4227
<?php
4228
		}
4229
4230
		if ( $this->message ) {
4231
?>
4232
<div id="message" class="jetpack-message">
4233
	<div class="squeezer">
4234
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4235
	</div>
4236
</div>
4237
<?php
4238
		}
4239
4240
		if ( $this->privacy_checks ) :
4241
			$module_names = $module_slugs = array();
4242
4243
			$privacy_checks = explode( ',', $this->privacy_checks );
4244
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4245
			foreach ( $privacy_checks as $module_slug ) {
4246
				$module = Jetpack::get_module( $module_slug );
4247
				if ( ! $module ) {
4248
					continue;
4249
				}
4250
4251
				$module_slugs[] = $module_slug;
4252
				$module_names[] = "<strong>{$module['name']}</strong>";
4253
			}
4254
4255
			$module_slugs = join( ',', $module_slugs );
4256
?>
4257
<div id="message" class="jetpack-message jetpack-err">
4258
	<div class="squeezer">
4259
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4260
		<p><?php
4261
			echo wp_kses(
4262
				wptexturize(
4263
					wp_sprintf(
4264
						_nx(
4265
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4266
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4267
							count( $privacy_checks ),
4268
							'%l = list of Jetpack module/feature names',
4269
							'jetpack'
4270
						),
4271
						$module_names
4272
					)
4273
				),
4274
				array( 'strong' => true )
4275
			);
4276
4277
			echo "\n<br />\n";
4278
4279
			echo wp_kses(
4280
				sprintf(
4281
					_nx(
4282
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4283
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4284
						count( $privacy_checks ),
4285
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4286
						'jetpack'
4287
					),
4288
					wp_nonce_url(
4289
						Jetpack::admin_url(
4290
							array(
4291
								'page'   => 'jetpack',
4292
								'action' => 'deactivate',
4293
								'module' => urlencode( $module_slugs ),
4294
							)
4295
						),
4296
						"jetpack_deactivate-$module_slugs"
4297
					),
4298
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4299
				),
4300
				array( 'a' => array( 'href' => true, 'title' => true ) )
4301
			);
4302
		?></p>
4303
	</div>
4304
</div>
4305
<?php endif;
4306
	}
4307
4308
	/**
4309
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4310
	 */
4311
	function stat( $group, $detail ) {
4312
		if ( ! isset( $this->stats[ $group ] ) )
4313
			$this->stats[ $group ] = array();
4314
		$this->stats[ $group ][] = $detail;
4315
	}
4316
4317
	/**
4318
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4319
	 */
4320
	function do_stats( $method = '' ) {
4321
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4322
			foreach ( $this->stats as $group => $stats ) {
4323
				if ( is_array( $stats ) && count( $stats ) ) {
4324
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4325
					if ( 'server_side' === $method ) {
4326
						self::do_server_side_stat( $args );
4327
					} else {
4328
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4329
					}
4330
				}
4331
				unset( $this->stats[ $group ] );
4332
			}
4333
		}
4334
	}
4335
4336
	/**
4337
	 * Runs stats code for a one-off, server-side.
4338
	 *
4339
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4340
	 *
4341
	 * @return bool If it worked.
4342
	 */
4343
	static function do_server_side_stat( $args ) {
4344
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4345
		if ( is_wp_error( $response ) )
4346
			return false;
4347
4348
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4349
			return false;
4350
4351
		return true;
4352
	}
4353
4354
	/**
4355
	 * Builds the stats url.
4356
	 *
4357
	 * @param $args array|string The arguments to append to the URL.
4358
	 *
4359
	 * @return string The URL to be pinged.
4360
	 */
4361
	static function build_stats_url( $args ) {
4362
		$defaults = array(
4363
			'v'    => 'wpcom2',
4364
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4365
		);
4366
		$args     = wp_parse_args( $args, $defaults );
4367
		/**
4368
		 * Filter the URL used as the Stats tracking pixel.
4369
		 *
4370
		 * @since 2.3.2
4371
		 *
4372
		 * @param string $url Base URL used as the Stats tracking pixel.
4373
		 */
4374
		$base_url = apply_filters(
4375
			'jetpack_stats_base_url',
4376
			'https://pixel.wp.com/g.gif'
4377
		);
4378
		$url      = add_query_arg( $args, $base_url );
4379
		return $url;
4380
	}
4381
4382
	/**
4383
	 * Get the role of the current user.
4384
	 *
4385
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4386
	 *
4387
	 * @access public
4388
	 * @static
4389
	 *
4390
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4391
	 */
4392
	public static function translate_current_user_to_role() {
4393
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4394
4395
		$roles = new Roles();
4396
		return $roles->translate_current_user_to_role();
4397
	}
4398
4399
	/**
4400
	 * Get the role of a particular user.
4401
	 *
4402
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4403
	 *
4404
	 * @access public
4405
	 * @static
4406
	 *
4407
	 * @param \WP_User $user User object.
4408
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4409
	 */
4410
	public static function translate_user_to_role( $user ) {
4411
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4412
4413
		$roles = new Roles();
4414
		return $roles->translate_user_to_role( $user );
4415
	}
4416
4417
	/**
4418
	 * Get the minimum capability for a role.
4419
	 *
4420
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4421
	 *
4422
	 * @access public
4423
	 * @static
4424
	 *
4425
	 * @param string $role Role name.
4426
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4427
	 */
4428
	public static function translate_role_to_cap( $role ) {
4429
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4430
4431
		$roles = new Roles();
4432
		return $roles->translate_role_to_cap( $role );
4433
	}
4434
4435
	static function sign_role( $role, $user_id = null ) {
4436
		if ( empty( $user_id ) ) {
4437
			$user_id = (int) get_current_user_id();
4438
		}
4439
4440
		if ( ! $user_id  ) {
4441
			return false;
4442
		}
4443
4444
		$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
		if ( ! $token || is_wp_error( $token ) ) {
4446
			return false;
4447
		}
4448
4449
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4450
	}
4451
4452
4453
	/**
4454
	 * Builds a URL to the Jetpack connection auth page
4455
	 *
4456
	 * @since 3.9.5
4457
	 *
4458
	 * @param bool $raw If true, URL will not be escaped.
4459
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4460
	 *                              If string, will be a custom redirect.
4461
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4462
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4463
	 *
4464
	 * @return string Connect URL
4465
	 */
4466
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4467
		$site_id = Jetpack_Options::get_option( 'id' );
4468
		$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...
4469
4470
		if ( $register || ! $blog_token || ! $site_id ) {
4471
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4472
4473
			if ( ! empty( $redirect ) ) {
4474
				$url = add_query_arg(
4475
					'redirect',
4476
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4477
					$url
4478
				);
4479
			}
4480
4481
			if( is_network_admin() ) {
4482
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4483
			}
4484
		} else {
4485
4486
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4487
			// because otherwise this logic can get us in to a loop.
4488
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4489
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4490
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4491
4492
				$response = Client::wpcom_json_api_request_as_blog(
4493
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4494
					'1.1'
4495
				);
4496
4497
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4498
4499
					// Generating a register URL instead to refresh the existing token
4500
					return $this->build_connect_url( $raw, $redirect, $from, true );
4501
				}
4502
			}
4503
4504
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4466 can also be of type string; however, Jetpack::build_authorize_url() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
4505
		}
4506
4507
		if ( $from ) {
4508
			$url = add_query_arg( 'from', $from, $url );
4509
		}
4510
4511
		// Ensure that class to get the affiliate code is loaded
4512
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4513
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4514
		}
4515
		// Get affiliate code and add it to the URL
4516
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4517
4518
		$calypso_env = $this->get_calypso_env();
4519
4520
		if ( ! empty( $calypso_env ) ) {
4521
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4522
		}
4523
4524
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4525
	}
4526
4527
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4528
		if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4529
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4530
		}
4531
4532
		$roles       = new Roles();
4533
		$role        = $roles->translate_current_user_to_role();
4534
		$signed_role = self::sign_role( $role );
4535
4536
		$user = wp_get_current_user();
4537
4538
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4539
		$redirect = $redirect
4540
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4541
			: $jetpack_admin_page;
4542
4543
		if( isset( $_REQUEST['is_multisite'] ) ) {
4544
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4545
		}
4546
4547
		$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4548
4549
		/**
4550
		 * Filter the type of authorization.
4551
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4552
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4553
		 *
4554
		 * @since 4.3.3
4555
		 *
4556
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4557
		 */
4558
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4559
4560
4561
		$tracks = new Tracking();
4562
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4563
4564
		$args = urlencode_deep(
4565
			array(
4566
				'response_type' => 'code',
4567
				'client_id'     => Jetpack_Options::get_option( 'id' ),
4568
				'redirect_uri'  => add_query_arg(
4569
					array(
4570
						'action'   => 'authorize',
4571
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4572
						'redirect' => urlencode( $redirect ),
4573
					),
4574
					esc_url( admin_url( 'admin.php?page=jetpack' ) )
4575
				),
4576
				'state'         => $user->ID,
4577
				'scope'         => $signed_role,
4578
				'user_email'    => $user->user_email,
4579
				'user_login'    => $user->user_login,
4580
				'is_active'     => Jetpack::is_active(),
4581
				'jp_version'    => JETPACK__VERSION,
4582
				'auth_type'     => $auth_type,
4583
				'secret'        => $secrets['secret_1'],
4584
				'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4585
				'blogname'      => get_option( 'blogname' ),
4586
				'site_url'      => site_url(),
4587
				'home_url'      => home_url(),
4588
				'site_icon'     => get_site_icon_url(),
4589
				'site_lang'     => get_locale(),
4590
				'_ui'           => $tracks_identity['_ui'],
4591
				'_ut'           => $tracks_identity['_ut'],
4592
				'site_created'  => Jetpack::get_assumed_site_creation_date(),
4593
			)
4594
		);
4595
4596
		self::apply_activation_source_to_args( $args );
4597
4598
		$connection = self::connection();
4599
4600
		$api_url = $iframe ? $connection->api_url( 'authorize_iframe' ) : $connection->api_url( 'authorize' );
4601
4602
		return add_query_arg( $args, $api_url );
4603
	}
4604
4605
	/**
4606
	 * Get our assumed site creation date.
4607
	 * Calculated based on the earlier date of either:
4608
	 * - Earliest admin user registration date.
4609
	 * - Earliest date of post of any post type.
4610
	 *
4611
	 * @since 7.2.0
4612
	 *
4613
	 * @return string Assumed site creation date and time.
4614
	 */
4615 View Code Duplication
	public static function get_assumed_site_creation_date() {
4616
		$earliest_registered_users = get_users( array(
4617
			'role'    => 'administrator',
4618
			'orderby' => 'user_registered',
4619
			'order'   => 'ASC',
4620
			'fields'  => array( 'user_registered' ),
4621
			'number'  => 1,
4622
		) );
4623
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4624
4625
		$earliest_posts = get_posts( array(
4626
			'posts_per_page' => 1,
4627
			'post_type'      => 'any',
4628
			'post_status'    => 'any',
4629
			'orderby'        => 'date',
4630
			'order'          => 'ASC',
4631
		) );
4632
4633
		// If there are no posts at all, we'll count only on user registration date.
4634
		if ( $earliest_posts ) {
4635
			$earliest_post_date = $earliest_posts[0]->post_date;
4636
		} else {
4637
			$earliest_post_date = PHP_INT_MAX;
4638
		}
4639
4640
		return min( $earliest_registration_date, $earliest_post_date );
4641
	}
4642
4643 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4644
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4645
4646
		if ( $activation_source_name ) {
4647
			$args['_as'] = urlencode( $activation_source_name );
4648
		}
4649
4650
		if ( $activation_source_keyword ) {
4651
			$args['_ak'] = urlencode( $activation_source_keyword );
4652
		}
4653
	}
4654
4655
	function build_reconnect_url( $raw = false ) {
4656
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4657
		return $raw ? $url : esc_url( $url );
4658
	}
4659
4660
	public static function admin_url( $args = null ) {
4661
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4662
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4663
		return $url;
4664
	}
4665
4666
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4667
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4668
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4669
	}
4670
4671
	function dismiss_jetpack_notice() {
4672
4673
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4674
			return;
4675
		}
4676
4677
		switch( $_GET['jetpack-notice'] ) {
4678
			case 'dismiss':
4679
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4680
4681
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4682
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4683
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4684
				}
4685
				break;
4686
			case 'jetpack-protect-multisite-opt-out':
4687
4688
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4689
					// Don't show the banner again
4690
4691
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4692
					// redirect back to the page that had the notice
4693
					if ( wp_get_referer() ) {
4694
						wp_safe_redirect( wp_get_referer() );
4695
					} else {
4696
						// Take me to Jetpack
4697
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4698
					}
4699
				}
4700
				break;
4701
		}
4702
	}
4703
4704
	public static function sort_modules( $a, $b ) {
4705
		if ( $a['sort'] == $b['sort'] )
4706
			return 0;
4707
4708
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4709
	}
4710
4711
	function ajax_recheck_ssl() {
4712
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4713
		$result = Jetpack::permit_ssl( true );
4714
		wp_send_json( array(
4715
			'enabled' => $result,
4716
			'message' => get_transient( 'jetpack_https_test_message' )
4717
		) );
4718
	}
4719
4720
/* Client API */
4721
4722
	/**
4723
	 * Returns the requested Jetpack API URL
4724
	 *
4725
	 * @deprecated since 7.7
4726
	 * @return string
4727
	 */
4728
	public static function api_url( $relative_url ) {
4729
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4730
		$connection = self::connection();
4731
		return $connection->api_url( $relative_url );
4732
	}
4733
4734
	/**
4735
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4736
	 */
4737
	public static function fix_url_for_bad_hosts( $url ) {
4738
		if ( 0 !== strpos( $url, 'https://' ) ) {
4739
			return $url;
4740
		}
4741
4742
		switch ( JETPACK_CLIENT__HTTPS ) {
4743
			case 'ALWAYS' :
4744
				return $url;
4745
			case 'NEVER' :
4746
				return set_url_scheme( $url, 'http' );
4747
			// default : case 'AUTO' :
4748
		}
4749
4750
		// we now return the unmodified SSL URL by default, as a security precaution
4751
		return $url;
4752
	}
4753
4754
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4755
		// Default to a blog token.
4756
		$token_type = 'blog';
4757
4758
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4759
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4760
			if ( ! empty( $_GET['onboarding'] ) ) {
4761
				$jpo = $_GET;
4762
			} else {
4763
				$jpo = json_decode( $request_data, true );
4764
			}
4765
4766
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4767
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4768
4769
			if (
4770
				isset( $jpo_user )
4771
				&& isset( $jpo_token )
4772
				&& is_email( $jpo_user )
4773
				&& ctype_alnum( $jpo_token )
4774
				&& isset( $_GET['rest_route'] )
4775
				&& self::validate_onboarding_token_action(
4776
					$jpo_token,
4777
					$_GET['rest_route']
4778
				)
4779
			) {
4780
				$jp_user = get_user_by( 'email', $jpo_user );
4781
				if ( is_a( $jp_user, 'WP_User' ) ) {
4782
					wp_set_current_user( $jp_user->ID );
4783
					$user_can = is_multisite()
4784
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4785
						: current_user_can( 'manage_options' );
4786
					if ( $user_can ) {
4787
						$token_type = 'user';
4788
						$token->external_user_id = $jp_user->ID;
4789
					}
4790
				}
4791
			}
4792
4793
			$token_data['type']    = $token_type;
4794
			$token_data['user_id'] = $token->external_user_id;
4795
		}
4796
4797
		return $token_data;
4798
	}
4799
4800
	/**
4801
	 * Create a random secret for validating onboarding payload
4802
	 *
4803
	 * @return string Secret token
4804
	 */
4805
	public static function create_onboarding_token() {
4806
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4807
			$token = wp_generate_password( 32, false );
4808
			Jetpack_Options::update_option( 'onboarding', $token );
4809
		}
4810
4811
		return $token;
4812
	}
4813
4814
	/**
4815
	 * Remove the onboarding token
4816
	 *
4817
	 * @return bool True on success, false on failure
4818
	 */
4819
	public static function invalidate_onboarding_token() {
4820
		return Jetpack_Options::delete_option( 'onboarding' );
4821
	}
4822
4823
	/**
4824
	 * Validate an onboarding token for a specific action
4825
	 *
4826
	 * @return boolean True if token/action pair is accepted, false if not
4827
	 */
4828
	public static function validate_onboarding_token_action( $token, $action ) {
4829
		// Compare tokens, bail if tokens do not match
4830
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4831
			return false;
4832
		}
4833
4834
		// List of valid actions we can take
4835
		$valid_actions = array(
4836
			'/jetpack/v4/settings',
4837
		);
4838
4839
		// Whitelist the action
4840
		if ( ! in_array( $action, $valid_actions ) ) {
4841
			return false;
4842
		}
4843
4844
		return true;
4845
	}
4846
4847
	/**
4848
	 * Checks to see if the URL is using SSL to connect with Jetpack
4849
	 *
4850
	 * @since 2.3.3
4851
	 * @return boolean
4852
	 */
4853
	public static function permit_ssl( $force_recheck = false ) {
4854
		// Do some fancy tests to see if ssl is being supported
4855
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4856
			$message = '';
4857
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4858
				$ssl = 0;
4859
			} else {
4860
				switch ( JETPACK_CLIENT__HTTPS ) {
4861
					case 'NEVER':
4862
						$ssl = 0;
4863
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4864
						break;
4865
					case 'ALWAYS':
4866
					case 'AUTO':
4867
					default:
4868
						$ssl = 1;
4869
						break;
4870
				}
4871
4872
				// If it's not 'NEVER', test to see
4873
				if ( $ssl ) {
4874
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4875
						$ssl = 0;
4876
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4877
					} else {
4878
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4879
						if ( is_wp_error( $response ) ) {
4880
							$ssl = 0;
4881
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4882
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4883
							$ssl = 0;
4884
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4885
						}
4886
					}
4887
				}
4888
			}
4889
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4890
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4891
		}
4892
4893
		return (bool) $ssl;
4894
	}
4895
4896
	/*
4897
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4898
	 */
4899
	public function alert_auto_ssl_fail() {
4900
		if ( ! current_user_can( 'manage_options' ) )
4901
			return;
4902
4903
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4904
		?>
4905
4906
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4907
			<div class="jp-banner__content">
4908
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4909
				<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>
4910
				<p>
4911
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4912
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4913
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4914
				</p>
4915
				<p>
4916
					<?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' ),
4917
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4918
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4919
				</p>
4920
			</div>
4921
		</div>
4922
		<style>
4923
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4924
		</style>
4925
		<script type="text/javascript">
4926
			jQuery( document ).ready( function( $ ) {
4927
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4928
					var $this = $( this );
4929
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4930
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4931
					e.preventDefault();
4932
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4933
					$.post( ajaxurl, data )
4934
					  .done( function( response ) {
4935
					  	if ( response.enabled ) {
4936
					  		$( '#jetpack-ssl-warning' ).hide();
4937
					  	} else {
4938
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4939
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4940
					  	}
4941
					  }.bind( $this ) );
4942
				} );
4943
			} );
4944
		</script>
4945
4946
		<?php
4947
	}
4948
4949
	/**
4950
	 * Returns the Jetpack XML-RPC API
4951
	 *
4952
	 * @return string
4953
	 */
4954
	public static function xmlrpc_api_url() {
4955
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4956
		return untrailingslashit( $base ) . '/xmlrpc.php';
4957
	}
4958
4959
	public static function connection() {
4960
		return self::init()->connection_manager;
4961
	}
4962
4963
	/**
4964
	 * Creates two secret tokens and the end of life timestamp for them.
4965
	 *
4966
	 * Note these tokens are unique per call, NOT static per site for connecting.
4967
	 *
4968
	 * @since 2.6
4969
	 * @return array
4970
	 */
4971
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4972
		if ( false === $user_id ) {
4973
			$user_id = get_current_user_id();
4974
		}
4975
4976
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4977
	}
4978
4979
	public static function get_secrets( $action, $user_id ) {
4980
		$secrets = self::connection()->get_secrets( $action, $user_id );
4981
4982
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4983
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

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

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

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

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

Loading history...
4988
		}
4989
4990
		return $secrets;
4991
	}
4992
4993
	/**
4994
	 * @deprecated 7.5 Use Connection_Manager instead.
4995
	 *
4996
	 * @param $action
4997
	 * @param $user_id
4998
	 */
4999
	public static function delete_secrets( $action, $user_id ) {
5000
		return self::connection()->delete_secrets( $action, $user_id );
5001
	}
5002
5003
	/**
5004
	 * Builds the timeout limit for queries talking with the wpcom servers.
5005
	 *
5006
	 * Based on local php max_execution_time in php.ini
5007
	 *
5008
	 * @since 2.6
5009
	 * @return int
5010
	 * @deprecated
5011
	 **/
5012
	public function get_remote_query_timeout_limit() {
5013
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5014
		return Jetpack::get_max_execution_time();
5015
	}
5016
5017
	/**
5018
	 * Builds the timeout limit for queries talking with the wpcom servers.
5019
	 *
5020
	 * Based on local php max_execution_time in php.ini
5021
	 *
5022
	 * @since 5.4
5023
	 * @return int
5024
	 **/
5025
	public static function get_max_execution_time() {
5026
		$timeout = (int) ini_get( 'max_execution_time' );
5027
5028
		// Ensure exec time set in php.ini
5029
		if ( ! $timeout ) {
5030
			$timeout = 30;
5031
		}
5032
		return $timeout;
5033
	}
5034
5035
	/**
5036
	 * Sets a minimum request timeout, and returns the current timeout
5037
	 *
5038
	 * @since 5.4
5039
	 **/
5040 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5041
		$timeout = self::get_max_execution_time();
5042
		if ( $timeout < $min_timeout ) {
5043
			$timeout = $min_timeout;
5044
			set_time_limit( $timeout );
5045
		}
5046
		return $timeout;
5047
	}
5048
5049
	/**
5050
	 * Takes the response from the Jetpack register new site endpoint and
5051
	 * verifies it worked properly.
5052
	 *
5053
	 * @since 2.6
5054
	 * @deprecated since 7.7.0
5055
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5056
	 **/
5057
	public function validate_remote_register_response() {
5058
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5059
	}
5060
5061
	/**
5062
	 * @return bool|WP_Error
5063
	 */
5064
	public static function register() {
5065
		$tracking = new Tracking();
5066
		$tracking->record_user_event( 'jpc_register_begin' );
5067
5068
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5069
5070
		$connection = self::connection();
5071
		$registration = $connection->register();
5072
5073
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5074
5075
		if ( ! $registration || is_wp_error( $registration ) ) {
5076
			return $registration;
5077
		}
5078
5079
		return true;
5080
	}
5081
5082
	/**
5083
	 * Filters the registration request body to include tracking properties.
5084
	 *
5085
	 * @param Array $properties
5086
	 * @return Array amended properties.
5087
	 */
5088
	public static function filter_register_request_body( $properties ) {
5089
		$tracking = new Tracking();
5090
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5091
5092
		return array_merge(
5093
			$properties,
5094
			array(
5095
				'_ui' => $tracks_identity['_ui'],
5096
				'_ut' => $tracks_identity['_ut'],
5097
			)
5098
		);
5099
	}
5100
5101
	/**
5102
	 * If the db version is showing something other that what we've got now, bump it to current.
5103
	 *
5104
	 * @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...
5105
	 */
5106
	public static function maybe_set_version_option() {
5107
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5108
		if ( JETPACK__VERSION != $version ) {
5109
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5110
5111
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5112
				/** This action is documented in class.jetpack.php */
5113
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5114
			}
5115
5116
			return true;
5117
		}
5118
		return false;
5119
	}
5120
5121
/* Client Server API */
5122
5123
	/**
5124
	 * Loads the Jetpack XML-RPC client
5125
	 */
5126
	public static function load_xml_rpc_client() {
5127
		require_once ABSPATH . WPINC . '/class-IXR.php';
5128
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5129
	}
5130
5131
	/**
5132
	 * Resets the saved authentication state in between testing requests.
5133
	 */
5134
	public function reset_saved_auth_state() {
5135
		$this->rest_authentication_status = null;
5136
		$this->connection_manager->reset_saved_auth_state();
5137
	}
5138
5139
	/**
5140
	 * Verifies the signature of the current request.
5141
	 *
5142
	 * @deprecated since 7.7.0
5143
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5144
	 *
5145
	 * @return false|array
5146
	 */
5147
	public function verify_xml_rpc_signature() {
5148
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5149
		return self::connection()->verify_xml_rpc_signature();
5150
	}
5151
5152
	/**
5153
	 * Verifies the signature of the current request.
5154
	 *
5155
	 * This function has side effects and should not be used. Instead,
5156
	 * use the memoized version `->verify_xml_rpc_signature()`.
5157
	 *
5158
	 * @deprecated since 7.7.0
5159
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5160
	 * @internal
5161
	 */
5162
	private function internal_verify_xml_rpc_signature() {
5163
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5164
	}
5165
5166
	/**
5167
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5168
	 *
5169
	 * @deprecated since 7.7.0
5170
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5171
	 *
5172
	 * @param \WP_User|mixed $user     User object if authenticated.
5173
	 * @param string         $username Username.
5174
	 * @param string         $password Password string.
5175
	 * @return \WP_User|mixed Authenticated user or error.
5176
	 */
5177
	public function authenticate_jetpack( $user, $username, $password ) {
5178
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5179
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5180
	}
5181
5182
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5183
	// Uses the existing XMLRPC request signing implementation.
5184
	function wp_rest_authenticate( $user ) {
5185
		if ( ! empty( $user ) ) {
5186
			// Another authentication method is in effect.
5187
			return $user;
5188
		}
5189
5190
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5191
			// Nothing to do for this authentication method.
5192
			return null;
5193
		}
5194
5195
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5196
			// Nothing to do for this authentication method.
5197
			return null;
5198
		}
5199
5200
		// Ensure that we always have the request body available.  At this
5201
		// point, the WP REST API code to determine the request body has not
5202
		// run yet.  That code may try to read from 'php://input' later, but
5203
		// this can only be done once per request in PHP versions prior to 5.6.
5204
		// So we will go ahead and perform this read now if needed, and save
5205
		// the request body where both the Jetpack signature verification code
5206
		// and the WP REST API code can see it.
5207
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5208
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5209
		}
5210
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5211
5212
		// Only support specific request parameters that have been tested and
5213
		// are known to work with signature verification.  A different method
5214
		// can be passed to the WP REST API via the '?_method=' parameter if
5215
		// needed.
5216
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5217
			$this->rest_authentication_status = new WP_Error(
5218
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5219
				__( 'This request method is not supported.', 'jetpack' ),
5220
				array( 'status' => 400 )
5221
			);
5222
			return null;
5223
		}
5224
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5225
			$this->rest_authentication_status = new WP_Error(
5226
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5227
				__( 'This request method does not support body parameters.', 'jetpack' ),
5228
				array( 'status' => 400 )
5229
			);
5230
			return null;
5231
		}
5232
5233
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5234
5235
		if (
5236
			$verified &&
5237
			isset( $verified['type'] ) &&
5238
			'user' === $verified['type'] &&
5239
			! empty( $verified['user_id'] )
5240
		) {
5241
			// Authentication successful.
5242
			$this->rest_authentication_status = true;
5243
			return $verified['user_id'];
5244
		}
5245
5246
		// Something else went wrong.  Probably a signature error.
5247
		$this->rest_authentication_status = new WP_Error(
5248
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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

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

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

Loading history...
5249
			__( 'The request is not signed correctly.', 'jetpack' ),
5250
			array( 'status' => 400 )
5251
		);
5252
		return null;
5253
	}
5254
5255
	/**
5256
	 * Report authentication status to the WP REST API.
5257
	 *
5258
	 * @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...
5259
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5260
	 */
5261
	public function wp_rest_authentication_errors( $value ) {
5262
		if ( $value !== null ) {
5263
			return $value;
5264
		}
5265
		return $this->rest_authentication_status;
5266
	}
5267
5268
	/**
5269
	 * Add our nonce to this request.
5270
	 *
5271
	 * @deprecated since 7.7.0
5272
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5273
	 *
5274
	 * @param int    $timestamp Timestamp of the request.
5275
	 * @param string $nonce     Nonce string.
5276
	 */
5277
	public function add_nonce( $timestamp, $nonce ) {
5278
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5279
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5280
	}
5281
5282
	/**
5283
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5284
	 * Capture it here so we can verify the signature later.
5285
	 *
5286
	 * @deprecated since 7.7.0
5287
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5288
	 *
5289
	 * @param array $methods XMLRPC methods.
5290
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5291
	 */
5292
	public function xmlrpc_methods( $methods ) {
5293
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5294
		return $this->connection_manager->xmlrpc_methods( $methods );
5295
	}
5296
5297
	/**
5298
	 * Register additional public XMLRPC methods.
5299
	 *
5300
	 * @deprecated since 7.7.0
5301
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5302
	 *
5303
	 * @param array $methods Public XMLRPC methods.
5304
	 * @return array Public XMLRPC methods, with the getOptions one.
5305
	 */
5306
	public function public_xmlrpc_methods( $methods ) {
5307
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5308
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5309
	}
5310
5311
	/**
5312
	 * Handles a getOptions XMLRPC method call.
5313
	 *
5314
	 * @deprecated since 7.7.0
5315
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5316
	 *
5317
	 * @param array $args method call arguments.
5318
	 * @return array an amended XMLRPC server options array.
5319
	 */
5320
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5321
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5322
		return $this->connection_manager->jetpack_getOptions( $args );
5323
	}
5324
5325
	/**
5326
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5327
	 *
5328
	 * @deprecated since 7.7.0
5329
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5330
	 *
5331
	 * @param array $options Standard Core options.
5332
	 * @return array Amended options.
5333
	 */
5334
	public function xmlrpc_options( $options ) {
5335
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5336
		return $this->connection_manager->xmlrpc_options( $options );
5337
	}
5338
5339
	/**
5340
	 * Cleans nonces that were saved when calling ::add_nonce.
5341
	 *
5342
	 * @deprecated since 7.7.0
5343
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5344
	 *
5345
	 * @param bool $all whether to clean even non-expired nonces.
5346
	 */
5347
	public static function clean_nonces( $all = false ) {
5348
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5349
		return self::connection()->clean_nonces( $all );
5350
	}
5351
5352
	/**
5353
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5354
	 * SET: state( $key, $value );
5355
	 * GET: $value = state( $key );
5356
	 *
5357
	 * @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...
5358
	 * @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...
5359
	 * @param bool $restate private
5360
	 */
5361
	public static function state( $key = null, $value = null, $restate = false ) {
5362
		static $state = array();
5363
		static $path, $domain;
5364
		if ( ! isset( $path ) ) {
5365
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5366
			$admin_url = Jetpack::admin_url();
5367
			$bits      = wp_parse_url( $admin_url );
5368
5369
			if ( is_array( $bits ) ) {
5370
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5371
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5372
			} else {
5373
				$path = $domain = null;
5374
			}
5375
		}
5376
5377
		// Extract state from cookies and delete cookies
5378
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5379
			$yum = $_COOKIE[ 'jetpackState' ];
5380
			unset( $_COOKIE[ 'jetpackState' ] );
5381
			foreach ( $yum as $k => $v ) {
5382
				if ( strlen( $v ) )
5383
					$state[ $k ] = $v;
5384
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5385
			}
5386
		}
5387
5388
		if ( $restate ) {
5389
			foreach ( $state as $k => $v ) {
5390
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5391
			}
5392
			return;
5393
		}
5394
5395
		// Get a state variable
5396
		if ( isset( $key ) && ! isset( $value ) ) {
5397
			if ( array_key_exists( $key, $state ) )
5398
				return $state[ $key ];
5399
			return null;
5400
		}
5401
5402
		// Set a state variable
5403
		if ( isset ( $key ) && isset( $value ) ) {
5404
			if( is_array( $value ) && isset( $value[0] ) ) {
5405
				$value = $value[0];
5406
			}
5407
			$state[ $key ] = $value;
5408
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5409
		}
5410
	}
5411
5412
	public static function restate() {
5413
		Jetpack::state( null, null, true );
5414
	}
5415
5416
	public static function check_privacy( $file ) {
5417
		static $is_site_publicly_accessible = null;
5418
5419
		if ( is_null( $is_site_publicly_accessible ) ) {
5420
			$is_site_publicly_accessible = false;
5421
5422
			Jetpack::load_xml_rpc_client();
5423
			$rpc = new Jetpack_IXR_Client();
5424
5425
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5426
			if ( $success ) {
5427
				$response = $rpc->getResponse();
5428
				if ( $response ) {
5429
					$is_site_publicly_accessible = true;
5430
				}
5431
			}
5432
5433
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5434
		}
5435
5436
		if ( $is_site_publicly_accessible ) {
5437
			return;
5438
		}
5439
5440
		$module_slug = self::get_module_slug( $file );
5441
5442
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5443
		if ( ! $privacy_checks ) {
5444
			$privacy_checks = $module_slug;
5445
		} else {
5446
			$privacy_checks .= ",$module_slug";
5447
		}
5448
5449
		Jetpack::state( 'privacy_checks', $privacy_checks );
5450
	}
5451
5452
	/**
5453
	 * Helper method for multicall XMLRPC.
5454
	 */
5455
	public static function xmlrpc_async_call() {
5456
		global $blog_id;
5457
		static $clients = array();
5458
5459
		$client_blog_id = is_multisite() ? $blog_id : 0;
5460
5461
		if ( ! isset( $clients[$client_blog_id] ) ) {
5462
			Jetpack::load_xml_rpc_client();
5463
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5464
			if ( function_exists( 'ignore_user_abort' ) ) {
5465
				ignore_user_abort( true );
5466
			}
5467
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5468
		}
5469
5470
		$args = func_get_args();
5471
5472
		if ( ! empty( $args[0] ) ) {
5473
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5474
		} elseif ( is_multisite() ) {
5475
			foreach ( $clients as $client_blog_id => $client ) {
5476
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5477
					continue;
5478
				}
5479
5480
				$switch_success = switch_to_blog( $client_blog_id, true );
5481
				if ( ! $switch_success ) {
5482
					continue;
5483
				}
5484
5485
				flush();
5486
				$client->query();
5487
5488
				restore_current_blog();
5489
			}
5490
		} else {
5491
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5492
				flush();
5493
				$clients[0]->query();
5494
			}
5495
		}
5496
	}
5497
5498
	public static function staticize_subdomain( $url ) {
5499
5500
		// Extract hostname from URL
5501
		$host = parse_url( $url, PHP_URL_HOST );
5502
5503
		// Explode hostname on '.'
5504
		$exploded_host = explode( '.', $host );
5505
5506
		// Retrieve the name and TLD
5507
		if ( count( $exploded_host ) > 1 ) {
5508
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5509
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5510
			// Rebuild domain excluding subdomains
5511
			$domain = $name . '.' . $tld;
5512
		} else {
5513
			$domain = $host;
5514
		}
5515
		// Array of Automattic domains
5516
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5517
5518
		// Return $url if not an Automattic domain
5519
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5520
			return $url;
5521
		}
5522
5523
		if ( is_ssl() ) {
5524
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5525
		}
5526
5527
		srand( crc32( basename( $url ) ) );
5528
		$static_counter = rand( 0, 2 );
5529
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5530
5531
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5532
	}
5533
5534
/* JSON API Authorization */
5535
5536
	/**
5537
	 * Handles the login action for Authorizing the JSON API
5538
	 */
5539
	function login_form_json_api_authorization() {
5540
		$this->verify_json_api_authorization_request();
5541
5542
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5543
5544
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5545
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5546
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5547
	}
5548
5549
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5550
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5551
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5552
			return $url;
5553
		}
5554
5555
		$parsed_url = parse_url( $url );
5556
		$url = strtok( $url, '?' );
5557
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5558
		if ( ! empty( $parsed_url['query'] ) )
5559
			$url .= "&{$parsed_url['query']}";
5560
5561
		return $url;
5562
	}
5563
5564
	// Make sure the POSTed request is handled by the same action
5565
	function preserve_action_in_login_form_for_json_api_authorization() {
5566
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5567
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5568
	}
5569
5570
	// If someone logs in to approve API access, store the Access Code in usermeta
5571
	function store_json_api_authorization_token( $user_login, $user ) {
5572
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5573
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5574
		$token = wp_generate_password( 32, false );
5575
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5576
	}
5577
5578
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5579
	function allow_wpcom_public_api_domain( $domains ) {
5580
		$domains[] = 'public-api.wordpress.com';
5581
		return $domains;
5582
	}
5583
5584
	static function is_redirect_encoded( $redirect_url ) {
5585
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5586
	}
5587
5588
	// Add all wordpress.com environments to the safe redirect whitelist
5589
	function allow_wpcom_environments( $domains ) {
5590
		$domains[] = 'wordpress.com';
5591
		$domains[] = 'wpcalypso.wordpress.com';
5592
		$domains[] = 'horizon.wordpress.com';
5593
		$domains[] = 'calypso.localhost';
5594
		return $domains;
5595
	}
5596
5597
	// Add the Access Code details to the public-api.wordpress.com redirect
5598
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5599
		return add_query_arg(
5600
			urlencode_deep(
5601
				array(
5602
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5603
					'jetpack-user-id' => (int) $user->ID,
5604
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5605
				)
5606
			),
5607
			$redirect_to
5608
		);
5609
	}
5610
5611
5612
	/**
5613
	 * Verifies the request by checking the signature
5614
	 *
5615
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5616
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5617
	 *
5618
	 * @param null|array $environment
5619
	 */
5620
	function verify_json_api_authorization_request( $environment = null ) {
5621
		$environment = is_null( $environment )
5622
			? $_REQUEST
5623
			: $environment;
5624
5625
		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...
5626
		$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...
5627
		if ( ! $token || empty( $token->secret ) ) {
5628
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5629
		}
5630
5631
		$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' );
5632
5633
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5634
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5635
			/**
5636
			 * Jetpack authorisation request Error.
5637
			 *
5638
			 * @since 7.5.0
5639
			 *
5640
			 */
5641
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5642
			$die_error = sprintf(
5643
				/* translators: %s is a URL */
5644
				__( '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' ),
5645
				'https://jetpack.com/support/double-encoding/'
5646
			);
5647
		}
5648
5649
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5650
5651
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5652
			$signature = $jetpack_signature->sign_request(
5653
				$environment['token'],
5654
				$environment['timestamp'],
5655
				$environment['nonce'],
5656
				'',
5657
				'GET',
5658
				$environment['jetpack_json_api_original_query'],
5659
				null,
5660
				true
5661
			);
5662
		} else {
5663
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5664
		}
5665
5666
		if ( ! $signature ) {
5667
			wp_die( $die_error );
5668
		} else if ( is_wp_error( $signature ) ) {
5669
			wp_die( $die_error );
5670
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5671
			if ( is_ssl() ) {
5672
				// 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
5673
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5674
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5675
					wp_die( $die_error );
5676
				}
5677
			} else {
5678
				wp_die( $die_error );
5679
			}
5680
		}
5681
5682
		$timestamp = (int) $environment['timestamp'];
5683
		$nonce     = stripslashes( (string) $environment['nonce'] );
5684
5685
		if ( ! $this->connection->add_nonce( $timestamp, $nonce ) ) {
0 ignored issues
show
Bug introduced by
The property connection does not seem to exist. Did you mean connection_manager?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
5686
			// De-nonce the nonce, at least for 5 minutes.
5687
			// 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)
5688
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5689
			if ( $old_nonce_time < time() - 300 ) {
5690
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5691
			}
5692
		}
5693
5694
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5695
		$data_filters = array(
5696
			'state'        => 'opaque',
5697
			'client_id'    => 'int',
5698
			'client_title' => 'string',
5699
			'client_image' => 'url',
5700
		);
5701
5702
		foreach ( $data_filters as $key => $sanitation ) {
5703
			if ( ! isset( $data->$key ) ) {
5704
				wp_die( $die_error );
5705
			}
5706
5707
			switch ( $sanitation ) {
5708
			case 'int' :
5709
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5710
				break;
5711
			case 'opaque' :
5712
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5713
				break;
5714
			case 'string' :
5715
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5716
				break;
5717
			case 'url' :
5718
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5719
				break;
5720
			}
5721
		}
5722
5723
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5724
			wp_die( $die_error );
5725
		}
5726
	}
5727
5728
	function login_message_json_api_authorization( $message ) {
5729
		return '<p class="message">' . sprintf(
5730
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5731
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5732
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5733
	}
5734
5735
	/**
5736
	 * Get $content_width, but with a <s>twist</s> filter.
5737
	 */
5738
	public static function get_content_width() {
5739
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5740
			? $GLOBALS['content_width']
5741
			: false;
5742
		/**
5743
		 * Filter the Content Width value.
5744
		 *
5745
		 * @since 2.2.3
5746
		 *
5747
		 * @param string $content_width Content Width value.
5748
		 */
5749
		return apply_filters( 'jetpack_content_width', $content_width );
5750
	}
5751
5752
	/**
5753
	 * Pings the WordPress.com Mirror Site for the specified options.
5754
	 *
5755
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5756
	 *
5757
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5758
	 */
5759
	public function get_cloud_site_options( $option_names ) {
5760
		$option_names = array_filter( (array) $option_names, 'is_string' );
5761
5762
		Jetpack::load_xml_rpc_client();
5763
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5764
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5765
		if ( $xml->isError() ) {
5766
			return array(
5767
				'error_code' => $xml->getErrorCode(),
5768
				'error_msg'  => $xml->getErrorMessage(),
5769
			);
5770
		}
5771
		$cloud_site_options = $xml->getResponse();
5772
5773
		return $cloud_site_options;
5774
	}
5775
5776
	/**
5777
	 * Checks if the site is currently in an identity crisis.
5778
	 *
5779
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5780
	 */
5781
	public static function check_identity_crisis() {
5782
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5783
			return false;
5784
		}
5785
5786
		return Jetpack_Options::get_option( 'sync_error_idc' );
5787
	}
5788
5789
	/**
5790
	 * Checks whether the home and siteurl specifically are whitelisted
5791
	 * Written so that we don't have re-check $key and $value params every time
5792
	 * we want to check if this site is whitelisted, for example in footer.php
5793
	 *
5794
	 * @since  3.8.0
5795
	 * @return bool True = already whitelisted False = not whitelisted
5796
	 */
5797
	public static function is_staging_site() {
5798
		$is_staging = false;
5799
5800
		$known_staging = array(
5801
			'urls' => array(
5802
				'#\.staging\.wpengine\.com$#i', // WP Engine
5803
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5804
				'#\.stage\.site$#i'             // DreamPress
5805
			),
5806
			'constants' => array(
5807
				'IS_WPE_SNAPSHOT',      // WP Engine
5808
				'KINSTA_DEV_ENV',       // Kinsta.com
5809
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5810
				'JETPACK_STAGING_MODE', // Generic
5811
			)
5812
		);
5813
		/**
5814
		 * Filters the flags of known staging sites.
5815
		 *
5816
		 * @since 3.9.0
5817
		 *
5818
		 * @param array $known_staging {
5819
		 *     An array of arrays that each are used to check if the current site is staging.
5820
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5821
		 *     @type array $constants PHP constants of known staging/developement environments.
5822
		 *  }
5823
		 */
5824
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5825
5826
		if ( isset( $known_staging['urls'] ) ) {
5827
			foreach ( $known_staging['urls'] as $url ){
5828
				if ( preg_match( $url, site_url() ) ) {
5829
					$is_staging = true;
5830
					break;
5831
				}
5832
			}
5833
		}
5834
5835
		if ( isset( $known_staging['constants'] ) ) {
5836
			foreach ( $known_staging['constants'] as $constant ) {
5837
				if ( defined( $constant ) && constant( $constant ) ) {
5838
					$is_staging = true;
5839
				}
5840
			}
5841
		}
5842
5843
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5844
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5845
			$is_staging = true;
5846
		}
5847
5848
		/**
5849
		 * Filters is_staging_site check.
5850
		 *
5851
		 * @since 3.9.0
5852
		 *
5853
		 * @param bool $is_staging If the current site is a staging site.
5854
		 */
5855
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5856
	}
5857
5858
	/**
5859
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5860
	 *
5861
	 * @since 4.4.0
5862
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5863
	 *
5864
	 * @return bool
5865
	 */
5866
	public static function validate_sync_error_idc_option() {
5867
		$is_valid = false;
5868
5869
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5870
		if ( false === $idc_allowed ) {
5871
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5872
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5873
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5874
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5875
				$transient_duration = HOUR_IN_SECONDS;
5876
			} else {
5877
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5878
				$idc_allowed = '1';
5879
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5880
			}
5881
5882
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5883
		}
5884
5885
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5886
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5887
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5888
			$local_options = self::get_sync_error_idc_option();
5889
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5890
				$is_valid = true;
5891
			}
5892
		}
5893
5894
		/**
5895
		 * Filters whether the sync_error_idc option is valid.
5896
		 *
5897
		 * @since 4.4.0
5898
		 *
5899
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5900
		 */
5901
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5902
5903
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5904
			// Since the option exists, and did not validate, delete it
5905
			Jetpack_Options::delete_option( 'sync_error_idc' );
5906
		}
5907
5908
		return $is_valid;
5909
	}
5910
5911
	/**
5912
	 * Normalizes a url by doing three things:
5913
	 *  - Strips protocol
5914
	 *  - Strips www
5915
	 *  - Adds a trailing slash
5916
	 *
5917
	 * @since 4.4.0
5918
	 * @param string $url
5919
	 * @return WP_Error|string
5920
	 */
5921
	public static function normalize_url_protocol_agnostic( $url ) {
5922
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5923
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5924
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

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

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

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

Loading history...
5925
		}
5926
5927
		// Strip www and protocols
5928
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5929
		return $url;
5930
	}
5931
5932
	/**
5933
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5934
	 *
5935
	 * @since 4.4.0
5936
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5937
	 *
5938
	 * @param array $response
5939
	 * @return array Array of the local urls, wpcom urls, and error code
5940
	 */
5941
	public static function get_sync_error_idc_option( $response = array() ) {
5942
		// Since the local options will hit the database directly, store the values
5943
		// in a transient to allow for autoloading and caching on subsequent views.
5944
		$local_options = get_transient( 'jetpack_idc_local' );
5945
		if ( false === $local_options ) {
5946
			$local_options = array(
5947
				'home'    => Functions::home_url(),
5948
				'siteurl' => Functions::site_url(),
5949
			);
5950
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5951
		}
5952
5953
		$options = array_merge( $local_options, $response );
5954
5955
		$returned_values = array();
5956
		foreach( $options as $key => $option ) {
5957
			if ( 'error_code' === $key ) {
5958
				$returned_values[ $key ] = $option;
5959
				continue;
5960
			}
5961
5962
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5963
				continue;
5964
			}
5965
5966
			$returned_values[ $key ] = $normalized_url;
5967
		}
5968
5969
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
5970
5971
		return $returned_values;
5972
	}
5973
5974
	/**
5975
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5976
	 * If set to true, the site will be put into staging mode.
5977
	 *
5978
	 * @since 4.3.2
5979
	 * @return bool
5980
	 */
5981
	public static function sync_idc_optin() {
5982
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5983
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5984
		} else {
5985
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5986
		}
5987
5988
		/**
5989
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5990
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5991
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5992
		 *
5993
		 * @since 4.3.2
5994
		 *
5995
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5996
		 */
5997
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5998
	}
5999
6000
	/**
6001
	 * Maybe Use a .min.css stylesheet, maybe not.
6002
	 *
6003
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6004
	 */
6005
	public static function maybe_min_asset( $url, $path, $plugin ) {
6006
		// Short out on things trying to find actual paths.
6007
		if ( ! $path || empty( $plugin ) ) {
6008
			return $url;
6009
		}
6010
6011
		$path = ltrim( $path, '/' );
6012
6013
		// Strip out the abspath.
6014
		$base = dirname( plugin_basename( $plugin ) );
6015
6016
		// Short out on non-Jetpack assets.
6017
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6018
			return $url;
6019
		}
6020
6021
		// File name parsing.
6022
		$file              = "{$base}/{$path}";
6023
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6024
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6025
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6026
		$extension         = array_shift( $file_name_parts_r );
6027
6028
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6029
			// Already pointing at the minified version.
6030
			if ( 'min' === $file_name_parts_r[0] ) {
6031
				return $url;
6032
			}
6033
6034
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6035
			if ( file_exists( $min_full_path ) ) {
6036
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6037
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6038
				if ( 'css' === $extension ) {
6039
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6040
					self::$min_assets[ $key ] = $path;
6041
				}
6042
			}
6043
		}
6044
6045
		return $url;
6046
	}
6047
6048
	/**
6049
	 * If the asset is minified, let's flag .min as the suffix.
6050
	 *
6051
	 * Attached to `style_loader_src` filter.
6052
	 *
6053
	 * @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...
6054
	 * @param string $handle The registered handle of the script in question.
6055
	 * @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...
6056
	 */
6057
	public static function set_suffix_on_min( $src, $handle ) {
6058
		if ( false === strpos( $src, '.min.css' ) ) {
6059
			return $src;
6060
		}
6061
6062
		if ( ! empty( self::$min_assets ) ) {
6063
			foreach ( self::$min_assets as $file => $path ) {
6064
				if ( false !== strpos( $src, $file ) ) {
6065
					wp_style_add_data( $handle, 'suffix', '.min' );
6066
					return $src;
6067
				}
6068
			}
6069
		}
6070
6071
		return $src;
6072
	}
6073
6074
	/**
6075
	 * Maybe inlines a stylesheet.
6076
	 *
6077
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6078
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6079
	 *
6080
	 * Attached to `style_loader_tag` filter.
6081
	 *
6082
	 * @param string $tag The tag that would link to the external asset.
6083
	 * @param string $handle The registered handle of the script in question.
6084
	 *
6085
	 * @return string
6086
	 */
6087
	public static function maybe_inline_style( $tag, $handle ) {
6088
		global $wp_styles;
6089
		$item = $wp_styles->registered[ $handle ];
6090
6091
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6092
			return $tag;
6093
		}
6094
6095
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6096
			$href = $matches[1];
6097
			// Strip off query string
6098
			if ( $pos = strpos( $href, '?' ) ) {
6099
				$href = substr( $href, 0, $pos );
6100
			}
6101
			// Strip off fragment
6102
			if ( $pos = strpos( $href, '#' ) ) {
6103
				$href = substr( $href, 0, $pos );
6104
			}
6105
		} else {
6106
			return $tag;
6107
		}
6108
6109
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6110
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6111
			return $tag;
6112
		}
6113
6114
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6115
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6116
			// And this isn't the pass that actually deals with the RTL version...
6117
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6118
				// Short out, as the RTL version will deal with it in a moment.
6119
				return $tag;
6120
			}
6121
		}
6122
6123
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6124
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6125
		if ( $css ) {
6126
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6127
			if ( empty( $item->extra['after'] ) ) {
6128
				wp_add_inline_style( $handle, $css );
6129
			} else {
6130
				array_unshift( $item->extra['after'], $css );
6131
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6132
			}
6133
		}
6134
6135
		return $tag;
6136
	}
6137
6138
	/**
6139
	 * Loads a view file from the views
6140
	 *
6141
	 * Data passed in with the $data parameter will be available in the
6142
	 * template file as $data['value']
6143
	 *
6144
	 * @param string $template - Template file to load
6145
	 * @param array $data - Any data to pass along to the template
6146
	 * @return boolean - If template file was found
6147
	 **/
6148
	public function load_view( $template, $data = array() ) {
6149
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6150
6151
		if( file_exists( $views_dir . $template ) ) {
6152
			require_once( $views_dir . $template );
6153
			return true;
6154
		}
6155
6156
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6157
		return false;
6158
	}
6159
6160
	/**
6161
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6162
	 */
6163
	public function deprecated_hooks() {
6164
		global $wp_filter;
6165
6166
		/*
6167
		 * Format:
6168
		 * deprecated_filter_name => replacement_name
6169
		 *
6170
		 * If there is no replacement, use null for replacement_name
6171
		 */
6172
		$deprecated_list = array(
6173
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6174
			'wpl_sharing_2014_1'                                     => null,
6175
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6176
			'jetpack_identity_crisis_options_to_check'               => null,
6177
			'update_option_jetpack_single_user_site'                 => null,
6178
			'audio_player_default_colors'                            => null,
6179
			'add_option_jetpack_featured_images_enabled'             => null,
6180
			'add_option_jetpack_update_details'                      => null,
6181
			'add_option_jetpack_updates'                             => null,
6182
			'add_option_jetpack_network_name'                        => null,
6183
			'add_option_jetpack_network_allow_new_registrations'     => null,
6184
			'add_option_jetpack_network_add_new_users'               => null,
6185
			'add_option_jetpack_network_site_upload_space'           => null,
6186
			'add_option_jetpack_network_upload_file_types'           => null,
6187
			'add_option_jetpack_network_enable_administration_menus' => null,
6188
			'add_option_jetpack_is_multi_site'                       => null,
6189
			'add_option_jetpack_is_main_network'                     => null,
6190
			'add_option_jetpack_main_network_site'                   => null,
6191
			'jetpack_sync_all_registered_options'                    => null,
6192
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6193
			'jetpack_is_post_mailable'                               => null,
6194
			'jetpack_seo_site_host'                                  => null,
6195
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6196
			'jetpack_holiday_snow_option_name'                       => null,
6197
			'jetpack_holiday_chance_of_snow'                         => null,
6198
			'jetpack_holiday_snow_js_url'                            => null,
6199
			'jetpack_is_holiday_snow_season'                         => null,
6200
			'jetpack_holiday_snow_option_updated'                    => null,
6201
			'jetpack_holiday_snowing'                                => null,
6202
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6203
			'jetpack_cache_plans'                                    => null,
6204
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6205
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6206
			'jetpack_enable_site_verification'                       => null,
6207
			'can_display_jetpack_manage_notice'                      => null,
6208
			// Removed in Jetpack 7.3.0
6209
			'atd_load_scripts'                                       => null,
6210
			'atd_http_post_timeout'                                  => null,
6211
			'atd_http_post_error'                                    => null,
6212
			'atd_service_domain'                                     => null,
6213
			'jetpack_widget_authors_exclude'                         => 'jetpack_widget_authors_params',
6214
		);
6215
6216
		// This is a silly loop depth. Better way?
6217
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6218
			if ( has_action( $hook ) ) {
6219
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6220
					foreach( $values AS $hooked ) {
6221
						if ( is_callable( $hooked['function'] ) ) {
6222
							$function_name = 'an anonymous function';
6223
						} else {
6224
							$function_name = $hooked['function'];
6225
						}
6226
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6227
					}
6228
				}
6229
			}
6230
		}
6231
	}
6232
6233
	/**
6234
	 * Converts any url in a stylesheet, to the correct absolute url.
6235
	 *
6236
	 * Considerations:
6237
	 *  - Normal, relative URLs     `feh.png`
6238
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6239
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6240
	 *  - Absolute URLs             `http://domain.com/feh.png`
6241
	 *  - Domain root relative URLs `/feh.png`
6242
	 *
6243
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6244
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6245
	 *
6246
	 * @return mixed|string
6247
	 */
6248
	public static function absolutize_css_urls( $css, $css_file_url ) {
6249
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6250
		$css_dir = dirname( $css_file_url );
6251
		$p       = parse_url( $css_dir );
6252
		$domain  = sprintf(
6253
					'%1$s//%2$s%3$s%4$s',
6254
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6255
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6256
					$p['host'],
6257
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6258
				);
6259
6260
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6261
			$find = $replace = array();
6262
			foreach ( $matches as $match ) {
6263
				$url = trim( $match['path'], "'\" \t" );
6264
6265
				// If this is a data url, we don't want to mess with it.
6266
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6267
					continue;
6268
				}
6269
6270
				// If this is an absolute or protocol-agnostic url,
6271
				// we don't want to mess with it.
6272
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6273
					continue;
6274
				}
6275
6276
				switch ( substr( $url, 0, 1 ) ) {
6277
					case '/':
6278
						$absolute = $domain . $url;
6279
						break;
6280
					default:
6281
						$absolute = $css_dir . '/' . $url;
6282
				}
6283
6284
				$find[]    = $match[0];
6285
				$replace[] = sprintf( 'url("%s")', $absolute );
6286
			}
6287
			$css = str_replace( $find, $replace, $css );
6288
		}
6289
6290
		return $css;
6291
	}
6292
6293
	/**
6294
	 * This methods removes all of the registered css files on the front end
6295
	 * from Jetpack in favor of using a single file. In effect "imploding"
6296
	 * all the files into one file.
6297
	 *
6298
	 * Pros:
6299
	 * - Uses only ONE css asset connection instead of 15
6300
	 * - Saves a minimum of 56k
6301
	 * - Reduces server load
6302
	 * - Reduces time to first painted byte
6303
	 *
6304
	 * Cons:
6305
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6306
	 *		should not cause any issues with themes.
6307
	 * - Plugins/themes dequeuing styles no longer do anything. See
6308
	 *		jetpack_implode_frontend_css filter for a workaround
6309
	 *
6310
	 * For some situations developers may wish to disable css imploding and
6311
	 * instead operate in legacy mode where each file loads seperately and
6312
	 * can be edited individually or dequeued. This can be accomplished with
6313
	 * the following line:
6314
	 *
6315
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6316
	 *
6317
	 * @since 3.2
6318
	 **/
6319
	public function implode_frontend_css( $travis_test = false ) {
6320
		$do_implode = true;
6321
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6322
			$do_implode = false;
6323
		}
6324
6325
		// Do not implode CSS when the page loads via the AMP plugin.
6326
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6327
			$do_implode = false;
6328
		}
6329
6330
		/**
6331
		 * Allow CSS to be concatenated into a single jetpack.css file.
6332
		 *
6333
		 * @since 3.2.0
6334
		 *
6335
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6336
		 */
6337
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6338
6339
		// Do not use the imploded file when default behavior was altered through the filter
6340
		if ( ! $do_implode ) {
6341
			return;
6342
		}
6343
6344
		// We do not want to use the imploded file in dev mode, or if not connected
6345
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6346
			if ( ! $travis_test ) {
6347
				return;
6348
			}
6349
		}
6350
6351
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6352
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6353
			return;
6354
		}
6355
6356
		/*
6357
		 * Now we assume Jetpack is connected and able to serve the single
6358
		 * file.
6359
		 *
6360
		 * In the future there will be a check here to serve the file locally
6361
		 * or potentially from the Jetpack CDN
6362
		 *
6363
		 * For now:
6364
		 * - Enqueue a single imploded css file
6365
		 * - Zero out the style_loader_tag for the bundled ones
6366
		 * - Be happy, drink scotch
6367
		 */
6368
6369
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6370
6371
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6372
6373
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6374
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6375
	}
6376
6377
	function concat_remove_style_loader_tag( $tag, $handle ) {
6378
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6379
			$tag = '';
6380
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6381
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6382
			}
6383
		}
6384
6385
		return $tag;
6386
	}
6387
6388
	/**
6389
	 * Add an async attribute to scripts that can be loaded asynchronously.
6390
	 * https://www.w3schools.com/tags/att_script_async.asp
6391
	 *
6392
	 * @since 7.7.0
6393
	 *
6394
	 * @param string $tag    The <script> tag for the enqueued script.
6395
	 * @param string $handle The script's registered handle.
6396
	 * @param string $src    The script's source URL.
6397
	 */
6398
	public function script_add_async( $tag, $handle, $src ) {
6399
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6400
			return preg_replace( '/^<script /i', '<script async ', $tag );
6401
		}
6402
6403
		return $tag;
6404
	}
6405
6406
	/*
6407
	 * Check the heartbeat data
6408
	 *
6409
	 * Organizes the heartbeat data by severity.  For example, if the site
6410
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6411
	 *
6412
	 * Data will be added to "caution" array, if it either:
6413
	 *  - Out of date Jetpack version
6414
	 *  - Out of date WP version
6415
	 *  - Out of date PHP version
6416
	 *
6417
	 * $return array $filtered_data
6418
	 */
6419
	public static function jetpack_check_heartbeat_data() {
6420
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6421
6422
		$good    = array();
6423
		$caution = array();
6424
		$bad     = array();
6425
6426
		foreach ( $raw_data as $stat => $value ) {
6427
6428
			// Check jetpack version
6429
			if ( 'version' == $stat ) {
6430
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6431
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6432
					continue;
6433
				}
6434
			}
6435
6436
			// Check WP version
6437
			if ( 'wp-version' == $stat ) {
6438
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6439
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6440
					continue;
6441
				}
6442
			}
6443
6444
			// Check PHP version
6445
			if ( 'php-version' == $stat ) {
6446
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6447
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6448
					continue;
6449
				}
6450
			}
6451
6452
			// Check ID crisis
6453
			if ( 'identitycrisis' == $stat ) {
6454
				if ( 'yes' == $value ) {
6455
					$bad[ $stat ] = $value;
6456
					continue;
6457
				}
6458
			}
6459
6460
			// The rest are good :)
6461
			$good[ $stat ] = $value;
6462
		}
6463
6464
		$filtered_data = array(
6465
			'good'    => $good,
6466
			'caution' => $caution,
6467
			'bad'     => $bad
6468
		);
6469
6470
		return $filtered_data;
6471
	}
6472
6473
6474
	/*
6475
	 * This method is used to organize all options that can be reset
6476
	 * without disconnecting Jetpack.
6477
	 *
6478
	 * It is used in class.jetpack-cli.php to reset options
6479
	 *
6480
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6481
	 *
6482
	 * @return array of options to delete.
6483
	 */
6484
	public static function get_jetpack_options_for_reset() {
6485
		return Jetpack_Options::get_options_for_reset();
6486
	}
6487
6488
	/*
6489
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6490
	 * so we can bring them directly to their site in calypso.
6491
	 *
6492
	 * @param string | url
6493
	 * @return string | url without the guff
6494
	 */
6495
	public static function build_raw_urls( $url ) {
6496
		$strip_http = '/.*?:\/\//i';
6497
		$url = preg_replace( $strip_http, '', $url  );
6498
		$url = str_replace( '/', '::', $url );
6499
		return $url;
6500
	}
6501
6502
	/**
6503
	 * Stores and prints out domains to prefetch for page speed optimization.
6504
	 *
6505
	 * @param mixed $new_urls
6506
	 */
6507
	public static function dns_prefetch( $new_urls = null ) {
6508
		static $prefetch_urls = array();
6509
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6510
			echo "\r\n";
6511
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6512
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6513
			}
6514
		} elseif ( ! empty( $new_urls ) ) {
6515
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6516
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6517
			}
6518
			foreach ( (array) $new_urls as $this_new_url ) {
6519
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6520
			}
6521
			$prefetch_urls = array_unique( $prefetch_urls );
6522
		}
6523
	}
6524
6525
	public function wp_dashboard_setup() {
6526
		if ( self::is_active() ) {
6527
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6528
		}
6529
6530
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6531
			$jetpack_logo = new Jetpack_Logo();
6532
			$widget_title = sprintf(
6533
				wp_kses(
6534
					/* translators: Placeholder is a Jetpack logo. */
6535
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6536
					array( 'span' => array() )
6537
				),
6538
				$jetpack_logo->get_jp_emblem( true )
6539
			);
6540
6541
			wp_add_dashboard_widget(
6542
				'jetpack_summary_widget',
6543
				$widget_title,
6544
				array( __CLASS__, 'dashboard_widget' )
6545
			);
6546
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6547
6548
			// If we're inactive and not in development mode, sort our box to the top.
6549
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6550
				global $wp_meta_boxes;
6551
6552
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6553
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6554
6555
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6556
			}
6557
		}
6558
	}
6559
6560
	/**
6561
	 * @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...
6562
	 * @return mixed
6563
	 */
6564
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6565
		if ( ! is_array( $sorted ) ) {
6566
			return $sorted;
6567
		}
6568
6569
		foreach ( $sorted as $box_context => $ids ) {
6570
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6571
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6572
				continue;
6573
			}
6574
6575
			$ids_array = explode( ',', $ids );
6576
			$key = array_search( 'dashboard_stats', $ids_array );
6577
6578
			if ( false !== $key ) {
6579
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6580
				$ids_array[ $key ] = 'jetpack_summary_widget';
6581
				$sorted[ $box_context ] = implode( ',', $ids_array );
6582
				// We've found it, stop searching, and just return.
6583
				break;
6584
			}
6585
		}
6586
6587
		return $sorted;
6588
	}
6589
6590
	public static function dashboard_widget() {
6591
		/**
6592
		 * Fires when the dashboard is loaded.
6593
		 *
6594
		 * @since 3.4.0
6595
		 */
6596
		do_action( 'jetpack_dashboard_widget' );
6597
	}
6598
6599
	public static function dashboard_widget_footer() {
6600
		?>
6601
		<footer>
6602
6603
		<div class="protect">
6604
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6605
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6606
				<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>
6607
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6608
				<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' ); ?>">
6609
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6610
				</a>
6611
			<?php else : ?>
6612
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6613
			<?php endif; ?>
6614
		</div>
6615
6616
		<div class="akismet">
6617
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6618
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6619
				<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>
6620
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6621
				<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">
6622
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6623
				</a>
6624
			<?php else : ?>
6625
				<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>
6626
			<?php endif; ?>
6627
		</div>
6628
6629
		</footer>
6630
		<?php
6631
	}
6632
6633
	/*
6634
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6635
	 */
6636
	function jetpack_icon_user_connected( $columns ) {
6637
		$columns['user_jetpack'] = '';
6638
		return $columns;
6639
	}
6640
6641
	/*
6642
	 * Show Jetpack icon if the user is linked.
6643
	 */
6644
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6645
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6646
			$jetpack_logo = new Jetpack_Logo();
6647
			$emblem_html = sprintf(
6648
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6649
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6650
				$jetpack_logo->get_jp_emblem()
6651
			);
6652
			return $emblem_html;
6653
		}
6654
6655
		return $val;
6656
	}
6657
6658
	/*
6659
	 * Style the Jetpack user column
6660
	 */
6661
	function jetpack_user_col_style() {
6662
		global $current_screen;
6663
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6664
			<style>
6665
				.fixed .column-user_jetpack {
6666
					width: 21px;
6667
				}
6668
				.jp-emblem-user-admin svg {
6669
					width: 20px;
6670
					height: 20px;
6671
				}
6672
				.jp-emblem-user-admin path {
6673
					fill: #00BE28;
6674
				}
6675
			</style>
6676
		<?php }
6677
	}
6678
6679
	/**
6680
	 * Checks if Akismet is active and working.
6681
	 *
6682
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6683
	 * that implied usage of methods present since more recent version.
6684
	 * See https://github.com/Automattic/jetpack/pull/9585
6685
	 *
6686
	 * @since  5.1.0
6687
	 *
6688
	 * @return bool True = Akismet available. False = Aksimet not available.
6689
	 */
6690
	public static function is_akismet_active() {
6691
		static $status = null;
6692
6693
		if ( ! is_null( $status ) ) {
6694
			return $status;
6695
		}
6696
6697
		// Check if a modern version of Akismet is active.
6698
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6699
			$status = false;
6700
			return $status;
6701
		}
6702
6703
		// Make sure there is a key known to Akismet at all before verifying key.
6704
		$akismet_key = Akismet::get_api_key();
6705
		if ( ! $akismet_key ) {
6706
			$status = false;
6707
			return $status;
6708
		}
6709
6710
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6711
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6712
6713
		// 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.
6714
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6715
		// We cache the result of the Akismet key verification for ten minutes.
6716
		if ( ! $akismet_key_state || $recheck ) {
6717
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6718
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6719
		}
6720
6721
		$status = 'valid' === $akismet_key_state;
6722
6723
		return $status;
6724
	}
6725
6726
	/**
6727
	 * @deprecated
6728
	 *
6729
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6730
	 */
6731
	public static function is_function_in_backtrace() {
6732
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6733
	}
6734
6735
	/**
6736
	 * Given a minified path, and a non-minified path, will return
6737
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6738
	 *
6739
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6740
	 * root Jetpack directory.
6741
	 *
6742
	 * @since 5.6.0
6743
	 *
6744
	 * @param string $min_path
6745
	 * @param string $non_min_path
6746
	 * @return string The URL to the file
6747
	 */
6748
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6749
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6750
	}
6751
6752
	/**
6753
	 * Checks for whether Jetpack Backup & Scan is enabled.
6754
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6755
	 * @return bool|int|mixed
6756
	 */
6757
	public static function is_rewind_enabled() {
6758
		if ( ! Jetpack::is_active() ) {
6759
			return false;
6760
		}
6761
6762
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6763
		if ( false === $rewind_enabled ) {
6764
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6765
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6766
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6767
				&& ! empty( $rewind_data['state'] )
6768
				&& 'active' === $rewind_data['state'] )
6769
				? 1
6770
				: 0;
6771
6772
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6773
		}
6774
		return $rewind_enabled;
6775
	}
6776
6777
	/**
6778
	 * Return Calypso environment value; used for developing Jetpack and pairing
6779
	 * it with different Calypso enrionments, such as localhost.
6780
	 *
6781
	 * @since 7.4.0
6782
	 *
6783
	 * @return string Calypso environment
6784
	 */
6785
	public static function get_calypso_env() {
6786
		if ( isset( $_GET['calypso_env'] ) ) {
6787
			return sanitize_key( $_GET['calypso_env'] );
6788
		}
6789
6790
		if ( getenv( 'CALYPSO_ENV' ) ) {
6791
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6792
		}
6793
6794
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6795
			return sanitize_key( CALYPSO_ENV );
6796
		}
6797
6798
		return '';
6799
	}
6800
6801
	/**
6802
	 * Checks whether or not TOS has been agreed upon.
6803
	 * Will return true if a user has clicked to register, or is already connected.
6804
	 */
6805
	public static function jetpack_tos_agreed() {
6806
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
6807
	}
6808
6809
	/**
6810
	 * Handles activating default modules as well general cleanup for the new connection.
6811
	 *
6812
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6813
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6814
	 * @param boolean $send_state_messages          Whether to send state messages.
6815
	 * @return void
6816
	 */
6817
	public static function handle_post_authorization_actions(
6818
		$activate_sso = false,
6819
		$redirect_on_activation_error = false,
6820
		$send_state_messages = true
6821
	) {
6822
		$other_modules = $activate_sso
6823
			? array( 'sso' )
6824
			: array();
6825
6826
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6827
			Jetpack::delete_active_modules();
6828
6829
			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...
6830
		} else {
6831
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6832
		}
6833
6834
		// Since this is a fresh connection, be sure to clear out IDC options
6835
		Jetpack_IDC::clear_all_idc_options();
6836
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6837
6838
		// Start nonce cleaner
6839
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6840
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6841
6842
		if ( $send_state_messages ) {
6843
			Jetpack::state( 'message', 'authorized' );
6844
		}
6845
	}
6846
6847
	/**
6848
	 * Returns a boolean for whether backups UI should be displayed or not.
6849
	 *
6850
	 * @return bool Should backups UI be displayed?
6851
	 */
6852
	public static function show_backups_ui() {
6853
		/**
6854
		 * Whether UI for backups should be displayed.
6855
		 *
6856
		 * @since 6.5.0
6857
		 *
6858
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6859
		 */
6860
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6861
	}
6862
6863
	/*
6864
	 * Deprecated manage functions
6865
	 */
6866
	function prepare_manage_jetpack_notice() {
6867
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6868
	}
6869
	function manage_activate_screen() {
6870
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6871
	}
6872
	function admin_jetpack_manage_notice() {
6873
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6874
	}
6875
	function opt_out_jetpack_manage_url() {
6876
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6877
	}
6878
	function opt_in_jetpack_manage_url() {
6879
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6880
	}
6881
	function opt_in_jetpack_manage_notice() {
6882
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6883
	}
6884
	function can_display_jetpack_manage_notice() {
6885
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6886
	}
6887
6888
	/**
6889
	 * Clean leftoveruser meta.
6890
	 *
6891
	 * Delete Jetpack-related user meta when it is no longer needed.
6892
	 *
6893
	 * @since 7.3.0
6894
	 *
6895
	 * @param int $user_id User ID being updated.
6896
	 */
6897
	public static function user_meta_cleanup( $user_id ) {
6898
		$meta_keys = array(
6899
			// AtD removed from Jetpack 7.3
6900
			'AtD_options',
6901
			'AtD_check_when',
6902
			'AtD_guess_lang',
6903
			'AtD_ignored_phrases',
6904
		);
6905
6906
		foreach ( $meta_keys as $meta_key ) {
6907
			if ( get_user_meta( $user_id, $meta_key ) ) {
6908
				delete_user_meta( $user_id, $meta_key );
6909
			}
6910
		}
6911
	}
6912
6913
	function is_active_and_not_development_mode( $maybe ) {
6914
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
6915
			return false;
6916
		}
6917
		return true;
6918
	}
6919
}
6920