Completed
Push — memberships/widget ( e36f77...e31ee1 )
by
unknown
48:35 queued 32:12
created

class.jetpack.php (42 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
use Automattic\Jetpack\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\Sync\Sender;
10
use Automattic\Jetpack\Tracking;
11
12
/*
13
Options:
14
jetpack_options (array)
15
	An array of options.
16
	@see Jetpack_Options::get_option_names()
17
18
jetpack_register (string)
19
	Temporary verification secrets.
20
21
jetpack_activated (int)
22
	1: the plugin was activated normally
23
	2: the plugin was activated on this site because of a network-wide activation
24
	3: the plugin was auto-installed
25
	4: the plugin was manually disconnected (but is still installed)
26
27
jetpack_active_modules (array)
28
	Array of active module slugs.
29
30
jetpack_do_activate (bool)
31
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
32
*/
33
34
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
35
36
class Jetpack {
37
	public $xmlrpc_server = null;
38
39
	private $xmlrpc_verification = null;
40
	private $rest_authentication_status = null;
41
42
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
43
44
	private $tracking;
45
46
	/**
47
	 * @var array The handles of styles that are concatenated into jetpack.css.
48
	 *
49
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
50
	 */
51
	public $concatenated_style_handles = array(
52
		'jetpack-carousel',
53
		'grunion.css',
54
		'the-neverending-homepage',
55
		'jetpack_likes',
56
		'jetpack_related-posts',
57
		'sharedaddy',
58
		'jetpack-slideshow',
59
		'presentations',
60
		'quiz',
61
		'jetpack-subscriptions',
62
		'jetpack-responsive-videos-style',
63
		'jetpack-social-menu',
64
		'tiled-gallery',
65
		'jetpack_display_posts_widget',
66
		'gravatar-profile-widget',
67
		'goodreads-widget',
68
		'jetpack_social_media_icons_widget',
69
		'jetpack-top-posts-widget',
70
		'jetpack_image_widget',
71
		'jetpack-my-community-widget',
72
		'jetpack-authors-widget',
73
		'wordads',
74
		'eu-cookie-law-style',
75
		'flickr-widget-style',
76
		'jetpack-search-widget',
77
		'jetpack-simple-payments-widget-style',
78
		'jetpack-widget-social-icons-styles',
79
	);
80
81
	/**
82
	 * Contains all assets that have had their URL rewritten to minified versions.
83
	 *
84
	 * @var array
85
	 */
86
	static $min_assets = array();
87
88
	public $plugins_to_deactivate = array(
89
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
90
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
91
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
92
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
93
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
94
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
95
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
96
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
97
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
98
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
99
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
100
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
101
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
102
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
103
	);
104
105
	static $capability_translations = array(
106
		'administrator' => 'manage_options',
107
		'editor'        => 'edit_others_posts',
108
		'author'        => 'publish_posts',
109
		'contributor'   => 'edit_posts',
110
		'subscriber'    => 'read',
111
	);
112
113
	/**
114
	 * Map of modules that have conflicts with plugins and should not be auto-activated
115
	 * if the plugins are active.  Used by filter_default_modules
116
	 *
117
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
118
	 * change `module-slug` and add this to your plugin:
119
	 *
120
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
121
	 * function my_jetpack_get_default_modules( $modules ) {
122
	 *     return array_diff( $modules, array( 'module-slug' ) );
123
	 * }
124
	 *
125
	 * @var array
126
	 */
127
	private $conflicting_plugins = array(
128
		'comments'          => array(
129
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
130
			'Disqus'                               => 'disqus-comment-system/disqus.php',
131
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
132
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
133
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
134
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
135
		),
136
		'comment-likes' => array(
137
			'Epoch'                                => 'epoch/plugincore.php',
138
		),
139
		'contact-form'      => array(
140
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
141
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
142
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
143
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
144
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
145
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
146
		),
147
		'minileven'         => array(
148
			'WPtouch'                              => 'wptouch/wptouch.php',
149
		),
150
		'latex'             => array(
151
			'LaTeX for WordPress'                  => 'latex/latex.php',
152
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
153
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
154
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
155
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
156
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
157
		),
158
		'protect'           => array(
159
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
160
			'Captcha'                              => 'captcha/captcha.php',
161
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
162
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
163
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
164
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
165
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
166
			'Security-protection'                  => 'security-protection/security-protection.php',
167
			'Login Security'                       => 'login-security/login-security.php',
168
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
169
			'Wordfence Security'                   => 'wordfence/wordfence.php',
170
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
171
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
172
		),
173
		'random-redirect'   => array(
174
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
175
		),
176
		'related-posts'     => array(
177
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
178
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
179
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
180
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
181
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
182
			'outbrain'                             => 'outbrain/outbrain.php',
183
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
184
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
185
		),
186
		'sharedaddy'        => array(
187
			'AddThis'                              => 'addthis/addthis_social_widget.php',
188
			'Add To Any'                           => 'add-to-any/add-to-any.php',
189
			'ShareThis'                            => 'share-this/sharethis.php',
190
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
191
		),
192
		'seo-tools' => array(
193
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
194
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
195
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
196
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
197
			'The SEO Framework'                    => 'autodescription/autodescription.php',
198
		),
199
		'verification-tools' => array(
200
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
201
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
202
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
203
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
204
			'The SEO Framework'                    => 'autodescription/autodescription.php',
205
		),
206
		'widget-visibility' => array(
207
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
208
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
209
		),
210
		'sitemaps' => array(
211
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
212
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
213
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
214
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
215
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
216
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
217
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
218
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
219
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
220
			'The SEO Framework'                    => 'autodescription/autodescription.php',
221
			'Sitemap'                              => 'sitemap/sitemap.php',
222
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
223
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
224
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
225
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
226
		),
227
		'lazy-images' => array(
228
			'Lazy Load'              => 'lazy-load/lazy-load.php',
229
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
230
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
231
		),
232
	);
233
234
	/**
235
	 * Plugins for which we turn off our Facebook OG Tags implementation.
236
	 *
237
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
238
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
239
	 *
240
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
241
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
242
	 */
243
	private $open_graph_conflicting_plugins = array(
244
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
245
		                                                         // 2 Click Social Media Buttons
246
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
247
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
248
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
249
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
250
		                                                         // Open Graph Meta Tags by Heateor
251
		'facebook/facebook.php',                                 // Facebook (official plugin)
252
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
253
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
254
		                                                         // Facebook Featured Image & OG Meta Tags
255
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
256
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
257
		                                                         // Facebook Open Graph Meta Tags for WordPress
258
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
259
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
260
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
261
		                                                         // Fedmich's Facebook Open Graph Meta
262
		'network-publisher/networkpub.php',                      // Network Publisher
263
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
264
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
265
		                                                         // NextScripts SNAP
266
		'og-tags/og-tags.php',                                   // OG Tags
267
		'opengraph/opengraph.php',                               // Open Graph
268
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
269
		                                                         // Open Graph Protocol Framework
270
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
271
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
272
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
273
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
274
		'sharepress/sharepress.php',                             // SharePress
275
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
276
		'social-discussions/social-discussions.php',             // Social Discussions
277
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
278
		'socialize/socialize.php',                               // Socialize
279
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
280
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
281
		                                                         // Tweet, Like, Google +1 and Share
282
		'wordbooker/wordbooker.php',                             // Wordbooker
283
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
284
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
285
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
286
		                                                         // WP Facebook Like Send & Open Graph Meta
287
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
288
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
289
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
290
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
291
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
292
	);
293
294
	/**
295
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
296
	 */
297
	private $twitter_cards_conflicting_plugins = array(
298
	//	'twitter/twitter.php',                       // The official one handles this on its own.
299
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
300
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
301
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
302
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
303
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
304
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
305
		'twitter-cards/twitter-cards.php',           // Twitter Cards
306
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
307
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
308
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
309
	);
310
311
	/**
312
	 * Message to display in admin_notice
313
	 * @var string
314
	 */
315
	public $message = '';
316
317
	/**
318
	 * Error to display in admin_notice
319
	 * @var string
320
	 */
321
	public $error = '';
322
323
	/**
324
	 * Modules that need more privacy description.
325
	 * @var string
326
	 */
327
	public $privacy_checks = '';
328
329
	/**
330
	 * Stats to record once the page loads
331
	 *
332
	 * @var array
333
	 */
334
	public $stats = array();
335
336
	/**
337
	 * Jetpack_Sync object
338
	 */
339
	public $sync;
340
341
	/**
342
	 * Verified data for JSON authorization request
343
	 */
344
	public $json_api_authorization_request = array();
345
346
	/**
347
	 * @var \Automattic\Jetpack\Connection\Manager
348
	 */
349
	protected $connection_manager;
350
351
	/**
352
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
353
	 */
354
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
355
356
	/**
357
	 * Holds the singleton instance of this class
358
	 * @since 2.3.3
359
	 * @var Jetpack
360
	 */
361
	static $instance = false;
362
363
	/**
364
	 * Singleton
365
	 * @static
366
	 */
367
	public static function init() {
368
		if ( ! self::$instance ) {
369
			self::$instance = new Jetpack;
370
371
			self::$instance->plugin_upgrade();
372
		}
373
374
		return self::$instance;
375
	}
376
377
	/**
378
	 * Must never be called statically
379
	 */
380
	function plugin_upgrade() {
381
		if ( Jetpack::is_active() ) {
382
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
383
			if ( JETPACK__VERSION != $version ) {
384
				// Prevent multiple upgrades at once - only a single process should trigger
385
				// an upgrade to avoid stampedes
386
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
387
					return;
388
				}
389
390
				// Set a short lock to prevent multiple instances of the upgrade
391
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
392
393
				// check which active modules actually exist and remove others from active_modules list
394
				$unfiltered_modules = Jetpack::get_active_modules();
395
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
396
				if ( array_diff( $unfiltered_modules, $modules ) ) {
397
					Jetpack::update_active_modules( $modules );
398
				}
399
400
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
401
402
				// Upgrade to 4.3.0
403
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
404
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
405
				}
406
407
				// Make sure Markdown for posts gets turned back on
408
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
409
					update_option( 'wpcom_publish_posts_with_markdown', true );
410
				}
411
412
				if ( did_action( 'wp_loaded' ) ) {
413
					self::upgrade_on_load();
414
				} else {
415
					add_action(
416
						'wp_loaded',
417
						array( __CLASS__, 'upgrade_on_load' )
418
					);
419
				}
420
			}
421
		}
422
	}
423
424
	/**
425
	 * Runs upgrade routines that need to have modules loaded.
426
	 */
427
	static function upgrade_on_load() {
428
429
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
430
		// This can happen in case Jetpack has been just upgraded and is
431
		// being initialized late during the page load. In this case we wait
432
		// until the next proper admin page load with Jetpack active.
433
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
434
			delete_transient( self::$plugin_upgrade_lock_key );
435
436
			return;
437
		}
438
439
		Jetpack::maybe_set_version_option();
440
441
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
442
			Jetpack_Widget_Conditions::migrate_post_type_rules();
443
		}
444
445
		if (
446
			class_exists( 'Jetpack_Sitemap_Manager' )
447
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
448
		) {
449
			do_action( 'jetpack_sitemaps_purge_data' );
450
		}
451
452
		delete_transient( self::$plugin_upgrade_lock_key );
453
	}
454
455
	/**
456
	 * Saves all the currently active modules to options.
457
	 * Also fires Action hooks for each newly activated and deactivated module.
458
	 *
459
	 * @param $modules Array Array of active modules to be saved in options.
460
	 *
461
	 * @return $success bool true for success, false for failure.
462
	 */
463
	static function update_active_modules( $modules ) {
464
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
465
		$active_modules       = Jetpack::get_active_modules();
466
		$new_active_modules   = array_diff( $modules, $current_modules );
467
		$new_inactive_modules = array_diff( $active_modules, $modules );
468
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
469
		$reindexed_modules    = array_values( $new_current_modules );
470
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
471
472
		foreach ( $new_active_modules as $module ) {
473
			/**
474
			 * Fires when a specific module is activated.
475
			 *
476
			 * @since 1.9.0
477
			 *
478
			 * @param string $module Module slug.
479
			 * @param boolean $success whether the module was activated. @since 4.2
480
			 */
481
			do_action( 'jetpack_activate_module', $module, $success );
482
			/**
483
			 * Fires when a module is activated.
484
			 * The dynamic part of the filter, $module, is the module slug.
485
			 *
486
			 * @since 1.9.0
487
			 *
488
			 * @param string $module Module slug.
489
			 */
490
			do_action( "jetpack_activate_module_$module", $module );
491
		}
492
493
		foreach ( $new_inactive_modules as $module ) {
494
			/**
495
			 * Fired after a module has been deactivated.
496
			 *
497
			 * @since 4.2.0
498
			 *
499
			 * @param string $module Module slug.
500
			 * @param boolean $success whether the module was deactivated.
501
			 */
502
			do_action( 'jetpack_deactivate_module', $module, $success );
503
			/**
504
			 * Fires when a module is deactivated.
505
			 * The dynamic part of the filter, $module, is the module slug.
506
			 *
507
			 * @since 1.9.0
508
			 *
509
			 * @param string $module Module slug.
510
			 */
511
			do_action( "jetpack_deactivate_module_$module", $module );
512
		}
513
514
		return $success;
515
	}
516
517
	static function delete_active_modules() {
518
		self::update_active_modules( array() );
519
	}
520
521
	/**
522
	 * Constructor.  Initializes WordPress hooks
523
	 */
524
	private function __construct() {
525
		/*
526
		 * Check for and alert any deprecated hooks
527
		 */
528
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
529
530
		/*
531
		 * Enable enhanced handling of previewing sites in Calypso
532
		 */
533
		if ( Jetpack::is_active() ) {
534
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
535
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
536
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
537
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
538
		}
539
540
		if ( self::jetpack_tos_agreed() ) {
541
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
542
			add_action( 'init', array( $tracking, 'init' ) );
543
		}
544
545
		/*
546
		 * Load things that should only be in Network Admin.
547
		 *
548
		 * For now blow away everything else until a more full
549
		 * understanding of what is needed at the network level is
550
		 * available
551
		 */
552
		if ( is_multisite() ) {
553
			Jetpack_Network::init();
554
		}
555
556
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
557
			return function() {
558
				return wp_generate_password( 32, false );
559
			};
560
		} );
561
562
		$this->connection_manager = new Connection_Manager( );
563
564
		/**
565
		 * Prepare Gutenberg Editor functionality
566
		 */
567
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
568
		Jetpack_Gutenberg::init();
569
		Jetpack_Gutenberg::load_independent_blocks();
570
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
571
572
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
573
574
		// Unlink user before deleting the user from .com
575
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
576
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
577
578
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
579
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
580
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
581
				define( 'XMLRPC_REQUEST', true );
582
			}
583
584
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
585
586
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
587
		}
588
589
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
590
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
591
592
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
593
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
594
595
			$this->require_jetpack_authentication();
596
597
			if ( Jetpack::is_active() ) {
598
				// Hack to preserve $HTTP_RAW_POST_DATA
599
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
600
601 View Code Duplication
				if ( $this->verify_xml_rpc_signature() ) {
602
					// The actual API methods.
603
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
604
				} else {
605
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
606
					// active Jetpack connection, so that additional users can link their account.
607
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
608
				}
609 View Code Duplication
			} else {
610
				new XMLRPC_Connector( $this->connection_manager );
611
612
				// The bootstrap API methods.
613
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
614
615
				if ( $this->verify_xml_rpc_signature() ) {
616
					// the jetpack Provision method is available for blog-token-signed requests
617
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
618
				}
619
			}
620
621
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
622
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
623
		} elseif (
624
			is_admin() &&
625
			isset( $_POST['action'] ) && (
626
				'jetpack_upload_file' == $_POST['action'] ||
627
				'jetpack_update_file' == $_POST['action']
628
			)
629
		) {
630
			$this->require_jetpack_authentication();
631
			$this->add_remote_request_handlers();
632
		} else {
633
			if ( Jetpack::is_active() ) {
634
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
635
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
636
			} else {
637
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
638
			}
639
		}
640
641
		if ( Jetpack::is_active() ) {
642
			Jetpack_Heartbeat::init();
643
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
644
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
645
				Jetpack_Search_Performance_Logger::init();
646
			}
647
		}
648
649
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
650
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
651
652
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
653
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
654
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
655
		}
656
657
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
658
659
		add_action( 'admin_init', array( $this, 'admin_init' ) );
660
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
661
662
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
663
664
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
665
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
666
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
667
668
		// returns HTTPS support status
669
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
670
671
		// JITM AJAX callback function
672
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
673
674
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
675
676
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
677
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
678
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
679
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
680
681
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
682
683
		/**
684
		 * These actions run checks to load additional files.
685
		 * They check for external files or plugins, so they need to run as late as possible.
686
		 */
687
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
688
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
689
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
690
691
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
692
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
693
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
694
695
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
696
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
697
698
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
699
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
700
701
		// A filter to control all just in time messages
702
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
703
704
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
705
706
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
707
		// We should make sure to only do this for front end links.
708
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
709
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
710
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
711
712
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
713
			//so they point moderation links on emails to Calypso
714
			jetpack_require_lib( 'functions.wp-notify' );
715
		}
716
717
		// Update the Jetpack plan from API on heartbeats
718
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
719
720
		/**
721
		 * This is the hack to concatenate all css files into one.
722
		 * For description and reasoning see the implode_frontend_css method
723
		 *
724
		 * Super late priority so we catch all the registered styles
725
		 */
726
		if( !is_admin() ) {
727
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
728
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
729
		}
730
731
732
		/**
733
		 * These are sync actions that we need to keep track of for jitms
734
		 */
735
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
736
737
		// Actually push the stats on shutdown.
738
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
739
			add_action( 'shutdown', array( $this, 'push_stats' ) );
740
		}
741
742
	}
743
744
	function initialize_rest_api_registration_connector() {
745
		new REST_Connector( $this->connection_manager );
746
	}
747
748
	/**
749
	 * This is ported over from the manage module, which has been deprecated and baked in here.
750
	 *
751
	 * @param $domains
752
	 */
753
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
754
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
755
	}
756
757
	/**
758
	 * Return $domains, with 'wordpress.com' appended.
759
	 * This is ported over from the manage module, which has been deprecated and baked in here.
760
	 *
761
	 * @param $domains
762
	 * @return array
763
	 */
764
	function allow_wpcom_domain( $domains ) {
765
		if ( empty( $domains ) ) {
766
			$domains = array();
767
		}
768
		$domains[] = 'wordpress.com';
769
		return array_unique( $domains );
770
	}
771
772
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
773
		$post = get_post( $post_id );
774
775
		if ( empty( $post ) ) {
776
			return $default_url;
777
		}
778
779
		$post_type = $post->post_type;
780
781
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
782
		// https://en.support.wordpress.com/custom-post-types/
783
		$allowed_post_types = array(
784
			'post' => 'post',
785
			'page' => 'page',
786
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
787
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
788
		);
789
790
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
791
			return $default_url;
792
		}
793
794
		$path_prefix = $allowed_post_types[ $post_type ];
795
796
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
797
798
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
799
	}
800
801
	function point_edit_comment_links_to_calypso( $url ) {
802
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
803
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
804
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
805
			Jetpack::build_raw_urls( get_home_url() ),
806
			$query_args['amp;c']
807
		) );
808
	}
809
810
	function jetpack_track_last_sync_callback( $params ) {
811
		/**
812
		 * Filter to turn off jitm caching
813
		 *
814
		 * @since 5.4.0
815
		 *
816
		 * @param bool false Whether to cache just in time messages
817
		 */
818
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
819
			return $params;
820
		}
821
822
		if ( is_array( $params ) && isset( $params[0] ) ) {
823
			$option = $params[0];
824
			if ( 'active_plugins' === $option ) {
825
				// use the cache if we can, but not terribly important if it gets evicted
826
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
827
			}
828
		}
829
830
		return $params;
831
	}
832
833
	function jetpack_connection_banner_callback() {
834
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
835
836
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
837
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
838
			wp_send_json_success();
839
		}
840
841
		wp_die();
842
	}
843
844
	/**
845
	 * Removes all XML-RPC methods that are not `jetpack.*`.
846
	 * Only used in our alternate XML-RPC endpoint, where we want to
847
	 * ensure that Core and other plugins' methods are not exposed.
848
	 *
849
	 * @param array $methods
850
	 * @return array filtered $methods
851
	 */
852
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
853
		$jetpack_methods = array();
854
855
		foreach ( $methods as $method => $callback ) {
856
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
857
				$jetpack_methods[ $method ] = $callback;
858
			}
859
		}
860
861
		return $jetpack_methods;
862
	}
863
864
	/**
865
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
866
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
867
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
868
	 * which is accessible via a different URI. Most of the below is copied directly
869
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
870
	 */
871
	function alternate_xmlrpc() {
872
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
873
		global $HTTP_RAW_POST_DATA;
874
875
		// Some browser-embedded clients send cookies. We don't want them.
876
		$_COOKIE = array();
877
878
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
879
		// but we can do it ourself.
880
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
881
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
882
		}
883
884
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
885
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
886
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
887
		}
888
889
		// phpcs:enable
890
891
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
892
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
893
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
894
895
		/**
896
		 * Filters the class used for handling XML-RPC requests.
897
		 *
898
		 * @since 3.1.0
899
		 *
900
		 * @param string $class The name of the XML-RPC server class.
901
		 */
902
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
903
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
904
905
		// Fire off the request
906
		nocache_headers();
907
		$wp_xmlrpc_server->serve_request();
908
909
		exit;
910
	}
911
912
	/**
913
	 * The callback for the JITM ajax requests.
914
	 */
915
	function jetpack_jitm_ajax_callback() {
916
		// Check for nonce
917
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
918
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
919
		}
920
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
921
			$module_slug = $_REQUEST['jitmModule'];
922
			Jetpack::log( 'activate', $module_slug );
923
			Jetpack::activate_module( $module_slug, false, false );
924
			Jetpack::state( 'message', 'no_message' );
925
926
			//A Jetpack module is being activated through a JITM, track it
927
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
928
			$this->do_stats( 'server_side' );
929
930
			wp_send_json_success();
931
		}
932
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
933
			// get the hide_jitm options array
934
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
935
			$module_slug = $_REQUEST['jitmModule'];
936
937
			if( ! $jetpack_hide_jitm ) {
938
				$jetpack_hide_jitm = array(
939
					$module_slug => 'hide'
940
				);
941
			} else {
942
				$jetpack_hide_jitm[$module_slug] = 'hide';
943
			}
944
945
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
946
947
			//jitm is being dismissed forever, track it
948
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
949
			$this->do_stats( 'server_side' );
950
951
			wp_send_json_success();
952
		}
953 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
954
			$module_slug = $_REQUEST['jitmModule'];
955
956
			// User went to WordPress.com, track this
957
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
958
			$this->do_stats( 'server_side' );
959
960
			wp_send_json_success();
961
		}
962 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
963
			$track = $_REQUEST['jitmModule'];
964
965
			// User is viewing JITM, track it.
966
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
967
			$this->do_stats( 'server_side' );
968
969
			wp_send_json_success();
970
		}
971
	}
972
973
	/**
974
	 * If there are any stats that need to be pushed, but haven't been, push them now.
975
	 */
976
	function push_stats() {
977
		if ( ! empty( $this->stats ) ) {
978
			$this->do_stats( 'server_side' );
979
		}
980
	}
981
982
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
983
		switch( $cap ) {
984
			case 'jetpack_connect' :
985
			case 'jetpack_reconnect' :
986
				if ( Jetpack::is_development_mode() ) {
987
					$caps = array( 'do_not_allow' );
988
					break;
989
				}
990
				/**
991
				 * Pass through. If it's not development mode, these should match disconnect.
992
				 * Let users disconnect if it's development mode, just in case things glitch.
993
				 */
994
			case 'jetpack_disconnect' :
995
				/**
996
				 * In multisite, can individual site admins manage their own connection?
997
				 *
998
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
999
				 */
1000
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1001
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1002
						/**
1003
						 * We need to update the option name -- it's terribly unclear which
1004
						 * direction the override goes.
1005
						 *
1006
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1007
						 */
1008
						$caps = array( 'do_not_allow' );
1009
						break;
1010
					}
1011
				}
1012
1013
				$caps = array( 'manage_options' );
1014
				break;
1015
			case 'jetpack_manage_modules' :
1016
			case 'jetpack_activate_modules' :
1017
			case 'jetpack_deactivate_modules' :
1018
				$caps = array( 'manage_options' );
1019
				break;
1020
			case 'jetpack_configure_modules' :
1021
				$caps = array( 'manage_options' );
1022
				break;
1023
			case 'jetpack_manage_autoupdates' :
1024
				$caps = array(
1025
					'manage_options',
1026
					'update_plugins',
1027
				);
1028
				break;
1029
			case 'jetpack_network_admin_page':
1030
			case 'jetpack_network_settings_page':
1031
				$caps = array( 'manage_network_plugins' );
1032
				break;
1033
			case 'jetpack_network_sites_page':
1034
				$caps = array( 'manage_sites' );
1035
				break;
1036
			case 'jetpack_admin_page' :
1037
				if ( Jetpack::is_development_mode() ) {
1038
					$caps = array( 'manage_options' );
1039
					break;
1040
				} else {
1041
					$caps = array( 'read' );
1042
				}
1043
				break;
1044
			case 'jetpack_connect_user' :
1045
				if ( Jetpack::is_development_mode() ) {
1046
					$caps = array( 'do_not_allow' );
1047
					break;
1048
				}
1049
				$caps = array( 'read' );
1050
				break;
1051
		}
1052
		return $caps;
1053
	}
1054
1055
	function require_jetpack_authentication() {
1056
		// Don't let anyone authenticate
1057
		$_COOKIE = array();
1058
		remove_all_filters( 'authenticate' );
1059
		remove_all_actions( 'wp_login_failed' );
1060
1061
		if ( Jetpack::is_active() ) {
1062
			// Allow Jetpack authentication
1063
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1064
		}
1065
	}
1066
1067
	/**
1068
	 * Load language files
1069
	 * @action plugins_loaded
1070
	 */
1071
	public static function plugin_textdomain() {
1072
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1073
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1074
	}
1075
1076
	/**
1077
	 * Register assets for use in various modules and the Jetpack admin page.
1078
	 *
1079
	 * @uses wp_script_is, wp_register_script, plugins_url
1080
	 * @action wp_loaded
1081
	 * @return null
1082
	 */
1083
	public function register_assets() {
1084
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1085
			wp_register_script(
1086
				'spin',
1087
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1088
				false,
1089
				'1.3'
1090
			);
1091
		}
1092
1093
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1094
			wp_register_script(
1095
				'jquery.spin',
1096
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1097
				array( 'jquery', 'spin' ),
1098
				'1.3'
1099
			);
1100
		}
1101
1102 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1103
			wp_register_script(
1104
				'jetpack-gallery-settings',
1105
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1106
				array( 'media-views' ),
1107
				'20121225'
1108
			);
1109
		}
1110
1111
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1112
			wp_register_script(
1113
				'jetpack-twitter-timeline',
1114
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1115
				array( 'jquery' ),
1116
				'4.0.0',
1117
				true
1118
			);
1119
		}
1120
1121
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1122
			wp_register_script(
1123
				'jetpack-facebook-embed',
1124
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1125
				array( 'jquery' ),
1126
				null,
1127
				true
1128
			);
1129
1130
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1131
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1132
			if ( ! is_numeric( $fb_app_id ) ) {
1133
				$fb_app_id = '';
1134
			}
1135
			wp_localize_script(
1136
				'jetpack-facebook-embed',
1137
				'jpfbembed',
1138
				array(
1139
					'appid' => $fb_app_id,
1140
					'locale' => $this->get_locale(),
1141
				)
1142
			);
1143
		}
1144
1145
		/**
1146
		 * As jetpack_register_genericons is by default fired off a hook,
1147
		 * the hook may have already fired by this point.
1148
		 * So, let's just trigger it manually.
1149
		 */
1150
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1151
		jetpack_register_genericons();
1152
1153
		/**
1154
		 * Register the social logos
1155
		 */
1156
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1157
		jetpack_register_social_logos();
1158
1159 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1160
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1161
	}
1162
1163
	/**
1164
	 * Guess locale from language code.
1165
	 *
1166
	 * @param string $lang Language code.
1167
	 * @return string|bool
1168
	 */
1169 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1170
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1171
			return 'en_US';
1172
		}
1173
1174
		if ( ! class_exists( 'GP_Locales' ) ) {
1175
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1176
				return false;
1177
			}
1178
1179
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1180
		}
1181
1182
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1183
			// WP.com: get_locale() returns 'it'
1184
			$locale = GP_Locales::by_slug( $lang );
1185
		} else {
1186
			// Jetpack: get_locale() returns 'it_IT';
1187
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1188
		}
1189
1190
		if ( ! $locale ) {
1191
			return false;
1192
		}
1193
1194
		if ( empty( $locale->facebook_locale ) ) {
1195
			if ( empty( $locale->wp_locale ) ) {
1196
				return false;
1197
			} else {
1198
				// Facebook SDK is smart enough to fall back to en_US if a
1199
				// locale isn't supported. Since supported Facebook locales
1200
				// can fall out of sync, we'll attempt to use the known
1201
				// wp_locale value and rely on said fallback.
1202
				return $locale->wp_locale;
1203
			}
1204
		}
1205
1206
		return $locale->facebook_locale;
1207
	}
1208
1209
	/**
1210
	 * Get the locale.
1211
	 *
1212
	 * @return string|bool
1213
	 */
1214
	function get_locale() {
1215
		$locale = $this->guess_locale_from_lang( get_locale() );
1216
1217
		if ( ! $locale ) {
1218
			$locale = 'en_US';
1219
		}
1220
1221
		return $locale;
1222
	}
1223
1224
	/**
1225
	 * Device Pixels support
1226
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1227
	 */
1228
	function devicepx() {
1229
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1230
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1231
		}
1232
	}
1233
1234
	/**
1235
	 * Return the network_site_url so that .com knows what network this site is a part of.
1236
	 * @param  bool $option
1237
	 * @return string
1238
	 */
1239
	public function jetpack_main_network_site_option( $option ) {
1240
		return network_site_url();
1241
	}
1242
	/**
1243
	 * Network Name.
1244
	 */
1245
	static function network_name( $option = null ) {
1246
		global $current_site;
1247
		return $current_site->site_name;
1248
	}
1249
	/**
1250
	 * Does the network allow new user and site registrations.
1251
	 * @return string
1252
	 */
1253
	static function network_allow_new_registrations( $option = null ) {
1254
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1255
	}
1256
	/**
1257
	 * Does the network allow admins to add new users.
1258
	 * @return boolian
1259
	 */
1260
	static function network_add_new_users( $option = null ) {
1261
		return (bool) get_site_option( 'add_new_users' );
1262
	}
1263
	/**
1264
	 * File upload psace left per site in MB.
1265
	 *  -1 means NO LIMIT.
1266
	 * @return number
1267
	 */
1268
	static function network_site_upload_space( $option = null ) {
1269
		// value in MB
1270
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1271
	}
1272
1273
	/**
1274
	 * Network allowed file types.
1275
	 * @return string
1276
	 */
1277
	static function network_upload_file_types( $option = null ) {
1278
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1279
	}
1280
1281
	/**
1282
	 * Maximum file upload size set by the network.
1283
	 * @return number
1284
	 */
1285
	static function network_max_upload_file_size( $option = null ) {
1286
		// value in KB
1287
		return get_site_option( 'fileupload_maxk', 300 );
1288
	}
1289
1290
	/**
1291
	 * Lets us know if a site allows admins to manage the network.
1292
	 * @return array
1293
	 */
1294
	static function network_enable_administration_menus( $option = null ) {
1295
		return get_site_option( 'menu_items' );
1296
	}
1297
1298
	/**
1299
	 * If a user has been promoted to or demoted from admin, we need to clear the
1300
	 * jetpack_other_linked_admins transient.
1301
	 *
1302
	 * @since 4.3.2
1303
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1304
	 *
1305
	 * @param int    $user_id   The user ID whose role changed.
1306
	 * @param string $role      The new role.
1307
	 * @param array  $old_roles An array of the user's previous roles.
1308
	 */
1309
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1310
		if ( 'administrator' == $role
1311
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1312
			|| is_null( $old_roles )
1313
		) {
1314
			delete_transient( 'jetpack_other_linked_admins' );
1315
		}
1316
	}
1317
1318
	/**
1319
	 * Checks to see if there are any other users available to become primary
1320
	 * Users must both:
1321
	 * - Be linked to wpcom
1322
	 * - Be an admin
1323
	 *
1324
	 * @return mixed False if no other users are linked, Int if there are.
1325
	 */
1326
	static function get_other_linked_admins() {
1327
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1328
1329
		if ( false === $other_linked_users ) {
1330
			$admins = get_users( array( 'role' => 'administrator' ) );
1331
			if ( count( $admins ) > 1 ) {
1332
				$available = array();
1333
				foreach ( $admins as $admin ) {
1334
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1335
						$available[] = $admin->ID;
1336
					}
1337
				}
1338
1339
				$count_connected_admins = count( $available );
1340
				if ( count( $available ) > 1 ) {
1341
					$other_linked_users = $count_connected_admins;
1342
				} else {
1343
					$other_linked_users = 0;
1344
				}
1345
			} else {
1346
				$other_linked_users = 0;
1347
			}
1348
1349
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1350
		}
1351
1352
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1353
	}
1354
1355
	/**
1356
	 * Return whether we are dealing with a multi network setup or not.
1357
	 * The reason we are type casting this is because we want to avoid the situation where
1358
	 * the result is false since when is_main_network_option return false it cases
1359
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1360
	 * database which could be set to anything as opposed to what this function returns.
1361
	 * @param  bool  $option
1362
	 *
1363
	 * @return boolean
1364
	 */
1365
	public function is_main_network_option( $option ) {
1366
		// return '1' or ''
1367
		return (string) (bool) Jetpack::is_multi_network();
1368
	}
1369
1370
	/**
1371
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1372
	 *
1373
	 * @param  string  $option
1374
	 * @return boolean
1375
	 */
1376
	public function is_multisite( $option ) {
1377
		return (string) (bool) is_multisite();
1378
	}
1379
1380
	/**
1381
	 * Implemented since there is no core is multi network function
1382
	 * Right now there is no way to tell if we which network is the dominant network on the system
1383
	 *
1384
	 * @since  3.3
1385
	 * @return boolean
1386
	 */
1387
	public static function is_multi_network() {
1388
		global  $wpdb;
1389
1390
		// if we don't have a multi site setup no need to do any more
1391
		if ( ! is_multisite() ) {
1392
			return false;
1393
		}
1394
1395
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1396
		if ( $num_sites > 1 ) {
1397
			return true;
1398
		} else {
1399
			return false;
1400
		}
1401
	}
1402
1403
	/**
1404
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1405
	 * @return null
1406
	 */
1407
	function update_jetpack_main_network_site_option() {
1408
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1409
	}
1410
	/**
1411
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1412
	 *
1413
	 */
1414
	function update_jetpack_network_settings() {
1415
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1416
		// Only sync this info for the main network site.
1417
	}
1418
1419
	/**
1420
	 * Get back if the current site is single user site.
1421
	 *
1422
	 * @return bool
1423
	 */
1424
	public static function is_single_user_site() {
1425
		global $wpdb;
1426
1427 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1428
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1429
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1430
		}
1431
		return 1 === (int) $some_users;
1432
	}
1433
1434
	/**
1435
	 * Returns true if the site has file write access false otherwise.
1436
	 * @return string ( '1' | '0' )
1437
	 **/
1438
	public static function file_system_write_access() {
1439
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1440
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1441
		}
1442
1443
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1444
1445
		$filesystem_method = get_filesystem_method();
1446
		if ( $filesystem_method === 'direct' ) {
1447
			return 1;
1448
		}
1449
1450
		ob_start();
1451
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1452
		ob_end_clean();
1453
		if ( $filesystem_credentials_are_stored ) {
1454
			return 1;
1455
		}
1456
		return 0;
1457
	}
1458
1459
	/**
1460
	 * Finds out if a site is using a version control system.
1461
	 * @return string ( '1' | '0' )
1462
	 **/
1463
	public static function is_version_controlled() {
1464
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1465
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1466
	}
1467
1468
	/**
1469
	 * Determines whether the current theme supports featured images or not.
1470
	 * @return string ( '1' | '0' )
1471
	 */
1472
	public static function featured_images_enabled() {
1473
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1474
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1475
	}
1476
1477
	/**
1478
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1479
	 *
1480
	 * @deprecated 4.7 use get_avatar_url instead.
1481
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1482
	 * @param int $size Size of the avatar image
1483
	 * @param string $default URL to a default image to use if no avatar is available
1484
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1485
	 *
1486
	 * @return array
1487
	 */
1488
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1489
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1490
		return get_avatar_url( $id_or_email, array(
1491
			'size' => $size,
1492
			'default' => $default,
1493
			'force_default' => $force_display,
1494
		) );
1495
	}
1496
1497
	/**
1498
	 * jetpack_updates is saved in the following schema:
1499
	 *
1500
	 * array (
1501
	 *      'plugins'                       => (int) Number of plugin updates available.
1502
	 *      'themes'                        => (int) Number of theme updates available.
1503
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1504
	 *      'translations'                  => (int) Number of translation updates available.
1505
	 *      'total'                         => (int) Total of all available updates.
1506
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1507
	 * )
1508
	 * @return array
1509
	 */
1510
	public static function get_updates() {
1511
		$update_data = wp_get_update_data();
1512
1513
		// Stores the individual update counts as well as the total count.
1514
		if ( isset( $update_data['counts'] ) ) {
1515
			$updates = $update_data['counts'];
1516
		}
1517
1518
		// If we need to update WordPress core, let's find the latest version number.
1519 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1520
			$cur = get_preferred_from_update_core();
1521
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1522
				$updates['wp_update_version'] = $cur->current;
1523
			}
1524
		}
1525
		return isset( $updates ) ? $updates : array();
1526
	}
1527
1528
	public static function get_update_details() {
1529
		$update_details = array(
1530
			'update_core' => get_site_transient( 'update_core' ),
1531
			'update_plugins' => get_site_transient( 'update_plugins' ),
1532
			'update_themes' => get_site_transient( 'update_themes' ),
1533
		);
1534
		return $update_details;
1535
	}
1536
1537
	public static function refresh_update_data() {
1538
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1539
1540
	}
1541
1542
	public static function refresh_theme_data() {
1543
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1544
	}
1545
1546
	/**
1547
	 * Is Jetpack active?
1548
	 */
1549
	public static function is_active() {
1550
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1551
	}
1552
1553
	/**
1554
	 * Make an API call to WordPress.com for plan status
1555
	 *
1556
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1557
	 *
1558
	 * @return bool True if plan is updated, false if no update
1559
	 */
1560
	public static function refresh_active_plan_from_wpcom() {
1561
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1562
		return Jetpack_Plan::refresh_from_wpcom();
1563
	}
1564
1565
	/**
1566
	 * Get the plan that this Jetpack site is currently using
1567
	 *
1568
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1569
	 * @return array Active Jetpack plan details.
1570
	 */
1571
	public static function get_active_plan() {
1572
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1573
		return Jetpack_Plan::get();
1574
	}
1575
1576
	/**
1577
	 * Determine whether the active plan supports a particular feature
1578
	 *
1579
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1580
	 * @return bool True if plan supports feature, false if not.
1581
	 */
1582
	public static function active_plan_supports( $feature ) {
1583
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1584
		return Jetpack_Plan::supports( $feature );
1585
	}
1586
1587
	/**
1588
	 * Is Jetpack in development (offline) mode?
1589
	 */
1590 View Code Duplication
	public static function is_development_mode() {
1591
		$development_mode = false;
1592
1593
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1594
			$development_mode = JETPACK_DEV_DEBUG;
1595
		} elseif ( $site_url = site_url() ) {
1596
			$development_mode = false === strpos( $site_url, '.' );
1597
		}
1598
1599
		/**
1600
		 * Filters Jetpack's development mode.
1601
		 *
1602
		 * @see https://jetpack.com/support/development-mode/
1603
		 *
1604
		 * @since 2.2.1
1605
		 *
1606
		 * @param bool $development_mode Is Jetpack's development mode active.
1607
		 */
1608
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1609
		return $development_mode;
1610
	}
1611
1612
	/**
1613
	 * Whether the site is currently onboarding or not.
1614
	 * A site is considered as being onboarded if it currently has an onboarding token.
1615
	 *
1616
	 * @since 5.8
1617
	 *
1618
	 * @access public
1619
	 * @static
1620
	 *
1621
	 * @return bool True if the site is currently onboarding, false otherwise
1622
	 */
1623
	public static function is_onboarding() {
1624
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1625
	}
1626
1627
	/**
1628
	 * Determines reason for Jetpack development mode.
1629
	 */
1630
	public static function development_mode_trigger_text() {
1631
		if ( ! Jetpack::is_development_mode() ) {
1632
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1633
		}
1634
1635
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1636
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1637
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1638
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1639
		} else {
1640
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1641
		}
1642
1643
		return $notice;
1644
1645
	}
1646
	/**
1647
	* Get Jetpack development mode notice text and notice class.
1648
	*
1649
	* Mirrors the checks made in Jetpack::is_development_mode
1650
	*
1651
	*/
1652
	public static function show_development_mode_notice() {
1653 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1654
			$notice = sprintf(
1655
			/* translators: %s is a URL */
1656
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1657
				'https://jetpack.com/support/development-mode/'
1658
			);
1659
1660
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1661
1662
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1663
		}
1664
1665
		// Throw up a notice if using a development version and as for feedback.
1666
		if ( Jetpack::is_development_version() ) {
1667
			/* translators: %s is a URL */
1668
			$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/' );
1669
1670
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1671
		}
1672
		// Throw up a notice if using staging mode
1673
		if ( Jetpack::is_staging_site() ) {
1674
			/* translators: %s is a URL */
1675
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1676
1677
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1678
		}
1679
	}
1680
1681
	/**
1682
	 * Whether Jetpack's version maps to a public release, or a development version.
1683
	 */
1684
	public static function is_development_version() {
1685
		/**
1686
		 * Allows filtering whether this is a development version of Jetpack.
1687
		 *
1688
		 * This filter is especially useful for tests.
1689
		 *
1690
		 * @since 4.3.0
1691
		 *
1692
		 * @param bool $development_version Is this a develoment version of Jetpack?
1693
		 */
1694
		return (bool) apply_filters(
1695
			'jetpack_development_version',
1696
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1697
		);
1698
	}
1699
1700
	/**
1701
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1702
	 */
1703
	public static function is_user_connected( $user_id = false ) {
1704
		return self::connection()->is_user_connected( $user_id );
1705
	}
1706
1707
	/**
1708
	 * Get the wpcom user data of the current|specified connected user.
1709
	 */
1710 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1711
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1712
		if ( ! $user_id ) {
1713
			$user_id = get_current_user_id();
1714
		}
1715
1716
		$transient_key = "jetpack_connected_user_data_$user_id";
1717
1718
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1719
			return $cached_user_data;
1720
		}
1721
1722
		Jetpack::load_xml_rpc_client();
1723
		$xml = new Jetpack_IXR_Client( array(
1724
			'user_id' => $user_id,
1725
		) );
1726
		$xml->query( 'wpcom.getUser' );
1727
		if ( ! $xml->isError() ) {
1728
			$user_data = $xml->getResponse();
1729
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1730
			return $user_data;
1731
		}
1732
1733
		return false;
1734
	}
1735
1736
	/**
1737
	 * Get the wpcom email of the current|specified connected user.
1738
	 */
1739 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1740
		if ( ! $user_id ) {
1741
			$user_id = get_current_user_id();
1742
		}
1743
		Jetpack::load_xml_rpc_client();
1744
		$xml = new Jetpack_IXR_Client( array(
1745
			'user_id' => $user_id,
1746
		) );
1747
		$xml->query( 'wpcom.getUserEmail' );
1748
		if ( ! $xml->isError() ) {
1749
			return $xml->getResponse();
1750
		}
1751
		return false;
1752
	}
1753
1754
	/**
1755
	 * Get the wpcom email of the master user.
1756
	 */
1757
	public static function get_master_user_email() {
1758
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1759
		if ( $master_user_id ) {
1760
			return self::get_connected_user_email( $master_user_id );
1761
		}
1762
		return '';
1763
	}
1764
1765
	function current_user_is_connection_owner() {
1766
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1767
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1768
	}
1769
1770
	/**
1771
	 * Gets current user IP address.
1772
	 *
1773
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1774
	 *
1775
	 * @return string                  Current user IP address.
1776
	 */
1777
	public static function current_user_ip( $check_all_headers = false ) {
1778
		if ( $check_all_headers ) {
1779
			foreach ( array(
1780
				'HTTP_CF_CONNECTING_IP',
1781
				'HTTP_CLIENT_IP',
1782
				'HTTP_X_FORWARDED_FOR',
1783
				'HTTP_X_FORWARDED',
1784
				'HTTP_X_CLUSTER_CLIENT_IP',
1785
				'HTTP_FORWARDED_FOR',
1786
				'HTTP_FORWARDED',
1787
				'HTTP_VIA',
1788
			) as $key ) {
1789
				if ( ! empty( $_SERVER[ $key ] ) ) {
1790
					return $_SERVER[ $key ];
1791
				}
1792
			}
1793
		}
1794
1795
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1796
	}
1797
1798
	/**
1799
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1800
	 */
1801
	function extra_oembed_providers() {
1802
		// Cloudup: https://dev.cloudup.com/#oembed
1803
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1804
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1805
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1806
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1807
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1808
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1809
	}
1810
1811
	/**
1812
	 * Synchronize connected user role changes
1813
	 */
1814
	function user_role_change( $user_id ) {
1815
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1816
		Jetpack_Sync_Users::user_role_change( $user_id );
1817
	}
1818
1819
	/**
1820
	 * Loads the currently active modules.
1821
	 */
1822
	public static function load_modules() {
1823
		if (
1824
			! self::is_active()
1825
			&& ! self::is_development_mode()
1826
			&& ! self::is_onboarding()
1827
			&& (
1828
				! is_multisite()
1829
				|| ! get_site_option( 'jetpack_protect_active' )
1830
			)
1831
		) {
1832
			return;
1833
		}
1834
1835
		$version = Jetpack_Options::get_option( 'version' );
1836 View Code Duplication
		if ( ! $version ) {
1837
			$version = $old_version = JETPACK__VERSION . ':' . time();
1838
			/** This action is documented in class.jetpack.php */
1839
			do_action( 'updating_jetpack_version', $version, false );
1840
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1841
		}
1842
		list( $version ) = explode( ':', $version );
1843
1844
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1845
1846
		$modules_data = array();
1847
1848
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1849
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1850
			$updated_modules = array();
1851
			foreach ( $modules as $module ) {
1852
				$modules_data[ $module ] = Jetpack::get_module( $module );
1853
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1854
					continue;
1855
				}
1856
1857
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1858
					continue;
1859
				}
1860
1861
				$updated_modules[] = $module;
1862
			}
1863
1864
			$modules = array_diff( $modules, $updated_modules );
1865
		}
1866
1867
		$is_development_mode = Jetpack::is_development_mode();
1868
1869
		foreach ( $modules as $index => $module ) {
1870
			// If we're in dev mode, disable modules requiring a connection
1871
			if ( $is_development_mode ) {
1872
				// Prime the pump if we need to
1873
				if ( empty( $modules_data[ $module ] ) ) {
1874
					$modules_data[ $module ] = Jetpack::get_module( $module );
1875
				}
1876
				// If the module requires a connection, but we're in local mode, don't include it.
1877
				if ( $modules_data[ $module ]['requires_connection'] ) {
1878
					continue;
1879
				}
1880
			}
1881
1882
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1883
				continue;
1884
			}
1885
1886
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1887
				unset( $modules[ $index ] );
1888
				self::update_active_modules( array_values( $modules ) );
1889
				continue;
1890
			}
1891
1892
			/**
1893
			 * Fires when a specific module is loaded.
1894
			 * The dynamic part of the hook, $module, is the module slug.
1895
			 *
1896
			 * @since 1.1.0
1897
			 */
1898
			do_action( 'jetpack_module_loaded_' . $module );
1899
		}
1900
1901
		/**
1902
		 * Fires when all the modules are loaded.
1903
		 *
1904
		 * @since 1.1.0
1905
		 */
1906
		do_action( 'jetpack_modules_loaded' );
1907
1908
		// 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.
1909
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1910
	}
1911
1912
	/**
1913
	 * Check if Jetpack's REST API compat file should be included
1914
	 * @action plugins_loaded
1915
	 * @return null
1916
	 */
1917
	public function check_rest_api_compat() {
1918
		/**
1919
		 * Filters the list of REST API compat files to be included.
1920
		 *
1921
		 * @since 2.2.5
1922
		 *
1923
		 * @param array $args Array of REST API compat files to include.
1924
		 */
1925
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1926
1927
		if ( function_exists( 'bbpress' ) )
1928
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1929
1930
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1931
			require_once $_jetpack_rest_api_compat_include;
1932
	}
1933
1934
	/**
1935
	 * Gets all plugins currently active in values, regardless of whether they're
1936
	 * traditionally activated or network activated.
1937
	 *
1938
	 * @todo Store the result in core's object cache maybe?
1939
	 */
1940
	public static function get_active_plugins() {
1941
		$active_plugins = (array) get_option( 'active_plugins', array() );
1942
1943
		if ( is_multisite() ) {
1944
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1945
			// whereas active_plugins stores them in the values.
1946
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1947
			if ( $network_plugins ) {
1948
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1949
			}
1950
		}
1951
1952
		sort( $active_plugins );
1953
1954
		return array_unique( $active_plugins );
1955
	}
1956
1957
	/**
1958
	 * Gets and parses additional plugin data to send with the heartbeat data
1959
	 *
1960
	 * @since 3.8.1
1961
	 *
1962
	 * @return array Array of plugin data
1963
	 */
1964
	public static function get_parsed_plugin_data() {
1965
		if ( ! function_exists( 'get_plugins' ) ) {
1966
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1967
		}
1968
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1969
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1970
		$active_plugins = Jetpack::get_active_plugins();
1971
1972
		$plugins = array();
1973
		foreach ( $all_plugins as $path => $plugin_data ) {
1974
			$plugins[ $path ] = array(
1975
					'is_active' => in_array( $path, $active_plugins ),
1976
					'file'      => $path,
1977
					'name'      => $plugin_data['Name'],
1978
					'version'   => $plugin_data['Version'],
1979
					'author'    => $plugin_data['Author'],
1980
			);
1981
		}
1982
1983
		return $plugins;
1984
	}
1985
1986
	/**
1987
	 * Gets and parses theme data to send with the heartbeat data
1988
	 *
1989
	 * @since 3.8.1
1990
	 *
1991
	 * @return array Array of theme data
1992
	 */
1993
	public static function get_parsed_theme_data() {
1994
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1995
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1996
1997
		$themes = array();
1998
		foreach ( $all_themes as $slug => $theme_data ) {
1999
			$theme_headers = array();
2000
			foreach ( $header_keys as $header_key ) {
2001
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2002
			}
2003
2004
			$themes[ $slug ] = array(
2005
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2006
					'slug' => $slug,
2007
					'theme_root' => $theme_data->get_theme_root_uri(),
2008
					'parent' => $theme_data->parent(),
2009
					'headers' => $theme_headers
2010
			);
2011
		}
2012
2013
		return $themes;
2014
	}
2015
2016
	/**
2017
	 * Checks whether a specific plugin is active.
2018
	 *
2019
	 * We don't want to store these in a static variable, in case
2020
	 * there are switch_to_blog() calls involved.
2021
	 */
2022
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2023
		return in_array( $plugin, self::get_active_plugins() );
2024
	}
2025
2026
	/**
2027
	 * Check if Jetpack's Open Graph tags should be used.
2028
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2029
	 *
2030
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2031
	 * @action plugins_loaded
2032
	 * @return null
2033
	 */
2034
	public function check_open_graph() {
2035
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2036
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2037
		}
2038
2039
		$active_plugins = self::get_active_plugins();
2040
2041
		if ( ! empty( $active_plugins ) ) {
2042
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2043
				if ( in_array( $plugin, $active_plugins ) ) {
2044
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2045
					break;
2046
				}
2047
			}
2048
		}
2049
2050
		/**
2051
		 * Allow the addition of Open Graph Meta Tags to all pages.
2052
		 *
2053
		 * @since 2.0.3
2054
		 *
2055
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2056
		 */
2057
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2058
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2059
		}
2060
	}
2061
2062
	/**
2063
	 * Check if Jetpack's Twitter tags should be used.
2064
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2065
	 *
2066
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2067
	 * @action plugins_loaded
2068
	 * @return null
2069
	 */
2070
	public function check_twitter_tags() {
2071
2072
		$active_plugins = self::get_active_plugins();
2073
2074
		if ( ! empty( $active_plugins ) ) {
2075
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2076
				if ( in_array( $plugin, $active_plugins ) ) {
2077
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2078
					break;
2079
				}
2080
			}
2081
		}
2082
2083
		/**
2084
		 * Allow Twitter Card Meta tags to be disabled.
2085
		 *
2086
		 * @since 2.6.0
2087
		 *
2088
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2089
		 */
2090
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2091
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2092
		}
2093
	}
2094
2095
	/**
2096
	 * Allows plugins to submit security reports.
2097
 	 *
2098
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2099
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2100
	 * @param array   $args         See definitions above
2101
	 */
2102
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2103
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2104
	}
2105
2106
/* Jetpack Options API */
2107
2108
	public static function get_option_names( $type = 'compact' ) {
2109
		return Jetpack_Options::get_option_names( $type );
2110
	}
2111
2112
	/**
2113
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2114
 	 *
2115
	 * @param string $name    Option name
2116
	 * @param mixed  $default (optional)
2117
	 */
2118
	public static function get_option( $name, $default = false ) {
2119
		return Jetpack_Options::get_option( $name, $default );
2120
	}
2121
2122
	/**
2123
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2124
 	 *
2125
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2126
	 * @param string $name  Option name
2127
	 * @param mixed  $value Option value
2128
	 */
2129
	public static function update_option( $name, $value ) {
2130
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2131
		return Jetpack_Options::update_option( $name, $value );
2132
	}
2133
2134
	/**
2135
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2136
 	 *
2137
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2138
	 * @param array $array array( option name => option value, ... )
2139
	 */
2140
	public static function update_options( $array ) {
2141
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2142
		return Jetpack_Options::update_options( $array );
2143
	}
2144
2145
	/**
2146
	 * Deletes the given option.  May be passed multiple option names as an array.
2147
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2148
	 *
2149
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2150
	 * @param string|array $names
2151
	 */
2152
	public static function delete_option( $names ) {
2153
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2154
		return Jetpack_Options::delete_option( $names );
2155
	}
2156
2157
	/**
2158
	 * Enters a user token into the user_tokens option
2159
	 *
2160
	 * @param int $user_id
2161
	 * @param string $token
2162
	 * return bool
2163
	 */
2164
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2165
		// not designed for concurrent updates
2166
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2167
		if ( ! is_array( $user_tokens ) )
2168
			$user_tokens = array();
2169
		$user_tokens[$user_id] = $token;
2170
		if ( $is_master_user ) {
2171
			$master_user = $user_id;
2172
			$options     = compact( 'user_tokens', 'master_user' );
2173
		} else {
2174
			$options = compact( 'user_tokens' );
2175
		}
2176
		return Jetpack_Options::update_options( $options );
2177
	}
2178
2179
	/**
2180
	 * Returns an array of all PHP files in the specified absolute path.
2181
	 * Equivalent to glob( "$absolute_path/*.php" ).
2182
	 *
2183
	 * @param string $absolute_path The absolute path of the directory to search.
2184
	 * @return array Array of absolute paths to the PHP files.
2185
	 */
2186
	public static function glob_php( $absolute_path ) {
2187
		if ( function_exists( 'glob' ) ) {
2188
			return glob( "$absolute_path/*.php" );
2189
		}
2190
2191
		$absolute_path = untrailingslashit( $absolute_path );
2192
		$files = array();
2193
		if ( ! $dir = @opendir( $absolute_path ) ) {
2194
			return $files;
2195
		}
2196
2197
		while ( false !== $file = readdir( $dir ) ) {
2198
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2199
				continue;
2200
			}
2201
2202
			$file = "$absolute_path/$file";
2203
2204
			if ( ! is_file( $file ) ) {
2205
				continue;
2206
			}
2207
2208
			$files[] = $file;
2209
		}
2210
2211
		closedir( $dir );
2212
2213
		return $files;
2214
	}
2215
2216
	public static function activate_new_modules( $redirect = false ) {
2217
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2218
			return;
2219
		}
2220
2221
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2222 View Code Duplication
		if ( ! $jetpack_old_version ) {
2223
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2224
			/** This action is documented in class.jetpack.php */
2225
			do_action( 'updating_jetpack_version', $version, false );
2226
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2227
		}
2228
2229
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2230
2231
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2232
			return;
2233
		}
2234
2235
		$active_modules     = Jetpack::get_active_modules();
2236
		$reactivate_modules = array();
2237
		foreach ( $active_modules as $active_module ) {
2238
			$module = Jetpack::get_module( $active_module );
2239
			if ( ! isset( $module['changed'] ) ) {
2240
				continue;
2241
			}
2242
2243
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2244
				continue;
2245
			}
2246
2247
			$reactivate_modules[] = $active_module;
2248
			Jetpack::deactivate_module( $active_module );
2249
		}
2250
2251
		$new_version = JETPACK__VERSION . ':' . time();
2252
		/** This action is documented in class.jetpack.php */
2253
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2254
		Jetpack_Options::update_options(
2255
			array(
2256
				'version'     => $new_version,
2257
				'old_version' => $jetpack_old_version,
2258
			)
2259
		);
2260
2261
		Jetpack::state( 'message', 'modules_activated' );
2262
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2263
2264
		if ( $redirect ) {
2265
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2266
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2267
				$page = $_GET['page'];
2268
			}
2269
2270
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2271
			exit;
2272
		}
2273
	}
2274
2275
	/**
2276
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2277
	 * Make sure to tuck away module "library" files in a sub-directory.
2278
	 */
2279
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2280
		static $modules = null;
2281
2282
		if ( ! isset( $modules ) ) {
2283
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2284
			// Use the cache if we're on the front-end and it's available...
2285
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2286
				$modules = $available_modules_option[ JETPACK__VERSION ];
2287
			} else {
2288
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2289
2290
				$modules = array();
2291
2292
				foreach ( $files as $file ) {
2293
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2294
						continue;
2295
					}
2296
2297
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2298
				}
2299
2300
				Jetpack_Options::update_option( 'available_modules', array(
2301
					JETPACK__VERSION => $modules,
2302
				) );
2303
			}
2304
		}
2305
2306
		/**
2307
		 * Filters the array of modules available to be activated.
2308
		 *
2309
		 * @since 2.4.0
2310
		 *
2311
		 * @param array $modules Array of available modules.
2312
		 * @param string $min_version Minimum version number required to use modules.
2313
		 * @param string $max_version Maximum version number required to use modules.
2314
		 */
2315
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2316
2317
		if ( ! $min_version && ! $max_version ) {
2318
			return array_keys( $mods );
2319
		}
2320
2321
		$r = array();
2322
		foreach ( $mods as $slug => $introduced ) {
2323
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2324
				continue;
2325
			}
2326
2327
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2328
				continue;
2329
			}
2330
2331
			$r[] = $slug;
2332
		}
2333
2334
		return $r;
2335
	}
2336
2337
	/**
2338
	 * Default modules loaded on activation.
2339
	 */
2340
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2341
		$return = array();
2342
2343
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2344
			$module_data = Jetpack::get_module( $module );
2345
2346
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2347
				case 'yes' :
2348
					$return[] = $module;
2349
					break;
2350
				case 'public' :
2351
					if ( Jetpack_Options::get_option( 'public' ) ) {
2352
						$return[] = $module;
2353
					}
2354
					break;
2355
				case 'no' :
2356
				default :
2357
					break;
2358
			}
2359
		}
2360
		/**
2361
		 * Filters the array of default modules.
2362
		 *
2363
		 * @since 2.5.0
2364
		 *
2365
		 * @param array $return Array of default modules.
2366
		 * @param string $min_version Minimum version number required to use modules.
2367
		 * @param string $max_version Maximum version number required to use modules.
2368
		 */
2369
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2370
	}
2371
2372
	/**
2373
	 * Checks activated modules during auto-activation to determine
2374
	 * if any of those modules are being deprecated.  If so, close
2375
	 * them out, and add any replacement modules.
2376
	 *
2377
	 * Runs at priority 99 by default.
2378
	 *
2379
	 * This is run late, so that it can still activate a module if
2380
	 * the new module is a replacement for another that the user
2381
	 * currently has active, even if something at the normal priority
2382
	 * would kibosh everything.
2383
	 *
2384
	 * @since 2.6
2385
	 * @uses jetpack_get_default_modules filter
2386
	 * @param array $modules
2387
	 * @return array
2388
	 */
2389
	function handle_deprecated_modules( $modules ) {
2390
		$deprecated_modules = array(
2391
			'debug'            => null,  // Closed out and moved to the debugger library.
2392
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2393
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2394
		);
2395
2396
		// Don't activate SSO if they never completed activating WPCC.
2397
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2398
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2399
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2400
				$deprecated_modules['wpcc'] = null;
2401
			}
2402
		}
2403
2404
		foreach ( $deprecated_modules as $module => $replacement ) {
2405
			if ( Jetpack::is_module_active( $module ) ) {
2406
				self::deactivate_module( $module );
2407
				if ( $replacement ) {
2408
					$modules[] = $replacement;
2409
				}
2410
			}
2411
		}
2412
2413
		return array_unique( $modules );
2414
	}
2415
2416
	/**
2417
	 * Checks activated plugins during auto-activation to determine
2418
	 * if any of those plugins are in the list with a corresponding module
2419
	 * that is not compatible with the plugin. The module will not be allowed
2420
	 * to auto-activate.
2421
	 *
2422
	 * @since 2.6
2423
	 * @uses jetpack_get_default_modules filter
2424
	 * @param array $modules
2425
	 * @return array
2426
	 */
2427
	function filter_default_modules( $modules ) {
2428
2429
		$active_plugins = self::get_active_plugins();
2430
2431
		if ( ! empty( $active_plugins ) ) {
2432
2433
			// For each module we'd like to auto-activate...
2434
			foreach ( $modules as $key => $module ) {
2435
				// If there are potential conflicts for it...
2436
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2437
					// For each potential conflict...
2438
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2439
						// If that conflicting plugin is active...
2440
						if ( in_array( $plugin, $active_plugins ) ) {
2441
							// Remove that item from being auto-activated.
2442
							unset( $modules[ $key ] );
2443
						}
2444
					}
2445
				}
2446
			}
2447
		}
2448
2449
		return $modules;
2450
	}
2451
2452
	/**
2453
	 * Extract a module's slug from its full path.
2454
	 */
2455
	public static function get_module_slug( $file ) {
2456
		return str_replace( '.php', '', basename( $file ) );
2457
	}
2458
2459
	/**
2460
	 * Generate a module's path from its slug.
2461
	 */
2462
	public static function get_module_path( $slug ) {
2463
		/**
2464
		 * Filters the path of a modules.
2465
		 *
2466
		 * @since 7.4.0
2467
		 *
2468
		 * @param array $return The absolute path to a module's root php file
2469
		 * @param string $slug The module slug
2470
		 */
2471
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2472
	}
2473
2474
	/**
2475
	 * Load module data from module file. Headers differ from WordPress
2476
	 * plugin headers to avoid them being identified as standalone
2477
	 * plugins on the WordPress plugins page.
2478
	 */
2479
	public static function get_module( $module ) {
2480
		$headers = array(
2481
			'name'                      => 'Module Name',
2482
			'description'               => 'Module Description',
2483
			'sort'                      => 'Sort Order',
2484
			'recommendation_order'      => 'Recommendation Order',
2485
			'introduced'                => 'First Introduced',
2486
			'changed'                   => 'Major Changes In',
2487
			'deactivate'                => 'Deactivate',
2488
			'free'                      => 'Free',
2489
			'requires_connection'       => 'Requires Connection',
2490
			'auto_activate'             => 'Auto Activate',
2491
			'module_tags'               => 'Module Tags',
2492
			'feature'                   => 'Feature',
2493
			'additional_search_queries' => 'Additional Search Queries',
2494
			'plan_classes'              => 'Plans',
2495
		);
2496
2497
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2498
2499
		$mod = Jetpack::get_file_data( $file, $headers );
2500
		if ( empty( $mod['name'] ) ) {
2501
			return false;
2502
		}
2503
2504
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2505
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2506
		$mod['deactivate']              = empty( $mod['deactivate'] );
2507
		$mod['free']                    = empty( $mod['free'] );
2508
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2509
2510
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2511
			$mod['auto_activate'] = 'No';
2512
		} else {
2513
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2514
		}
2515
2516
		if ( $mod['module_tags'] ) {
2517
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2518
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2519
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2520
		} else {
2521
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2522
		}
2523
2524 View Code Duplication
		if ( $mod['plan_classes'] ) {
2525
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2526
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2527
		} else {
2528
			$mod['plan_classes'] = array( 'free' );
2529
		}
2530
2531 View Code Duplication
		if ( $mod['feature'] ) {
2532
			$mod['feature'] = explode( ',', $mod['feature'] );
2533
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2534
		} else {
2535
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2536
		}
2537
2538
		/**
2539
		 * Filters the feature array on a module.
2540
		 *
2541
		 * This filter allows you to control where each module is filtered: Recommended,
2542
		 * and the default "Other" listing.
2543
		 *
2544
		 * @since 3.5.0
2545
		 *
2546
		 * @param array   $mod['feature'] The areas to feature this module:
2547
		 *     'Recommended' shows on the main Jetpack admin screen.
2548
		 *     'Other' should be the default if no other value is in the array.
2549
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2550
		 * @param array   $mod All the currently assembled module data.
2551
		 */
2552
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2553
2554
		/**
2555
		 * Filter the returned data about a module.
2556
		 *
2557
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2558
		 * so please be careful.
2559
		 *
2560
		 * @since 3.6.0
2561
		 *
2562
		 * @param array   $mod    The details of the requested module.
2563
		 * @param string  $module The slug of the module, e.g. sharedaddy
2564
		 * @param string  $file   The path to the module source file.
2565
		 */
2566
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2567
	}
2568
2569
	/**
2570
	 * Like core's get_file_data implementation, but caches the result.
2571
	 */
2572
	public static function get_file_data( $file, $headers ) {
2573
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2574
		$file_name = basename( $file );
2575
2576
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2577
2578
		$file_data_option = get_transient( $cache_key );
2579
2580
		if ( false === $file_data_option ) {
2581
			$file_data_option = array();
2582
		}
2583
2584
		$key           = md5( $file_name . serialize( $headers ) );
2585
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2586
2587
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2588
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2589
			return $file_data_option[ $key ];
2590
		}
2591
2592
		$data = get_file_data( $file, $headers );
2593
2594
		$file_data_option[ $key ] = $data;
2595
2596
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2597
2598
		return $data;
2599
	}
2600
2601
2602
	/**
2603
	 * Return translated module tag.
2604
	 *
2605
	 * @param string $tag Tag as it appears in each module heading.
2606
	 *
2607
	 * @return mixed
2608
	 */
2609
	public static function translate_module_tag( $tag ) {
2610
		return jetpack_get_module_i18n_tag( $tag );
2611
	}
2612
2613
	/**
2614
	 * Get i18n strings as a JSON-encoded string
2615
	 *
2616
	 * @return string The locale as JSON
2617
	 */
2618
	public static function get_i18n_data_json() {
2619
2620
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2621
		// JSON files with the file they should be included for. This is an md5
2622
		// of '_inc/build/admin.js'.
2623
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2624
2625
		$i18n_json =
2626
				   JETPACK__PLUGIN_DIR
2627
				   . 'languages/json/jetpack-'
2628
				   . get_user_locale()
2629
				   . '-'
2630
				   . $path_md5
2631
				   . '.json';
2632
2633
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2634
			$locale_data = @file_get_contents( $i18n_json );
2635
			if ( $locale_data ) {
2636
				return $locale_data;
2637
			}
2638
		}
2639
2640
		// Return valid empty Jed locale
2641
		return '{ "locale_data": { "messages": { "": {} } } }';
2642
	}
2643
2644
	/**
2645
	 * Add locale data setup to wp-i18n
2646
	 *
2647
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2648
	 *
2649
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2650
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2651
	 *
2652
	 * This method provides a safe way to request the setup multiple times but add the script at
2653
	 * most once.
2654
	 *
2655
	 * @since 6.7.0
2656
	 *
2657
	 * @return void
2658
	 */
2659
	public static function setup_wp_i18n_locale_data() {
2660
		static $script_added = false;
2661
		if ( ! $script_added ) {
2662
			$script_added = true;
2663
			wp_add_inline_script(
2664
				'wp-i18n',
2665
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2666
			);
2667
		}
2668
	}
2669
2670
	/**
2671
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2672
	 *
2673
	 * @since 3.9.2
2674
	 *
2675
	 * @param array $modules
2676
	 *
2677
	 * @return string|void
2678
	 */
2679
	public static function get_translated_modules( $modules ) {
2680
		foreach ( $modules as $index => $module ) {
2681
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2682
			if ( isset( $module['name'] ) ) {
2683
				$modules[ $index ]['name'] = $i18n_module['name'];
2684
			}
2685
			if ( isset( $module['description'] ) ) {
2686
				$modules[ $index ]['description'] = $i18n_module['description'];
2687
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2688
			}
2689
		}
2690
		return $modules;
2691
	}
2692
2693
	/**
2694
	 * Get a list of activated modules as an array of module slugs.
2695
	 */
2696
	public static function get_active_modules() {
2697
		$active = Jetpack_Options::get_option( 'active_modules' );
2698
2699
		if ( ! is_array( $active ) ) {
2700
			$active = array();
2701
		}
2702
2703
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2704
			$active[] = 'vaultpress';
2705
		} else {
2706
			$active = array_diff( $active, array( 'vaultpress' ) );
2707
		}
2708
2709
		//If protect is active on the main site of a multisite, it should be active on all sites.
2710
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2711
			$active[] = 'protect';
2712
		}
2713
2714
		/**
2715
		 * Allow filtering of the active modules.
2716
		 *
2717
		 * Gives theme and plugin developers the power to alter the modules that
2718
		 * are activated on the fly.
2719
		 *
2720
		 * @since 5.8.0
2721
		 *
2722
		 * @param array $active Array of active module slugs.
2723
		 */
2724
		$active = apply_filters( 'jetpack_active_modules', $active );
2725
2726
		return array_unique( $active );
2727
	}
2728
2729
	/**
2730
	 * Check whether or not a Jetpack module is active.
2731
	 *
2732
	 * @param string $module The slug of a Jetpack module.
2733
	 * @return bool
2734
	 *
2735
	 * @static
2736
	 */
2737
	public static function is_module_active( $module ) {
2738
		return in_array( $module, self::get_active_modules() );
2739
	}
2740
2741
	public static function is_module( $module ) {
2742
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2743
	}
2744
2745
	/**
2746
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2747
	 *
2748
	 * @param bool $catch True to start catching, False to stop.
2749
	 *
2750
	 * @static
2751
	 */
2752
	public static function catch_errors( $catch ) {
2753
		static $display_errors, $error_reporting;
2754
2755
		if ( $catch ) {
2756
			$display_errors  = @ini_set( 'display_errors', 1 );
2757
			$error_reporting = @error_reporting( E_ALL );
2758
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2759
		} else {
2760
			@ini_set( 'display_errors', $display_errors );
2761
			@error_reporting( $error_reporting );
2762
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2763
		}
2764
	}
2765
2766
	/**
2767
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2768
	 */
2769
	public static function catch_errors_on_shutdown() {
2770
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2771
	}
2772
2773
	/**
2774
	 * Rewrite any string to make paths easier to read.
2775
	 *
2776
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2777
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2778
	 *
2779
	 * @param $string
2780
	 * @return mixed
2781
	 */
2782
	public static function alias_directories( $string ) {
2783
		// ABSPATH has a trailing slash.
2784
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2785
		// WP_CONTENT_DIR does not have a trailing slash.
2786
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2787
2788
		return $string;
2789
	}
2790
2791
	public static function activate_default_modules(
2792
		$min_version = false,
2793
		$max_version = false,
2794
		$other_modules = array(),
2795
		$redirect = true,
2796
		$send_state_messages = true
2797
	) {
2798
		$jetpack = Jetpack::init();
2799
2800
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2801
		$modules = array_merge( $other_modules, $modules );
2802
2803
		// Look for standalone plugins and disable if active.
2804
2805
		$to_deactivate = array();
2806
		foreach ( $modules as $module ) {
2807
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2808
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2809
			}
2810
		}
2811
2812
		$deactivated = array();
2813
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2814
			list( $probable_file, $probable_title ) = $deactivate_me;
2815
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2816
				$deactivated[] = $module;
2817
			}
2818
		}
2819
2820
		if ( $deactivated && $redirect ) {
2821
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2822
2823
			$url = add_query_arg(
2824
				array(
2825
					'action'   => 'activate_default_modules',
2826
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2827
				),
2828
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2829
			);
2830
			wp_safe_redirect( $url );
2831
			exit;
2832
		}
2833
2834
		/**
2835
		 * Fires before default modules are activated.
2836
		 *
2837
		 * @since 1.9.0
2838
		 *
2839
		 * @param string $min_version Minimum version number required to use modules.
2840
		 * @param string $max_version Maximum version number required to use modules.
2841
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2842
		 */
2843
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2844
2845
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2846
		if ( $send_state_messages ) {
2847
			Jetpack::restate();
2848
			Jetpack::catch_errors( true );
2849
		}
2850
2851
		$active = Jetpack::get_active_modules();
2852
2853
		foreach ( $modules as $module ) {
2854
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2855
				$active[] = $module;
2856
				self::update_active_modules( $active );
2857
				continue;
2858
			}
2859
2860
			if ( $send_state_messages && in_array( $module, $active ) ) {
2861
				$module_info = Jetpack::get_module( $module );
2862 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2863
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2864
					if ( $active_state = Jetpack::state( $state ) ) {
2865
						$active_state = explode( ',', $active_state );
2866
					} else {
2867
						$active_state = array();
2868
					}
2869
					$active_state[] = $module;
2870
					Jetpack::state( $state, implode( ',', $active_state ) );
2871
				}
2872
				continue;
2873
			}
2874
2875
			$file = Jetpack::get_module_path( $module );
2876
			if ( ! file_exists( $file ) ) {
2877
				continue;
2878
			}
2879
2880
			// we'll override this later if the plugin can be included without fatal error
2881
			if ( $redirect ) {
2882
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2883
			}
2884
2885
			if ( $send_state_messages ) {
2886
				Jetpack::state( 'error', 'module_activation_failed' );
2887
				Jetpack::state( 'module', $module );
2888
			}
2889
2890
			ob_start();
2891
			require_once $file;
2892
2893
			$active[] = $module;
2894
2895 View Code Duplication
			if ( $send_state_messages ) {
2896
2897
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2898
				if ( $active_state = Jetpack::state( $state ) ) {
2899
					$active_state = explode( ',', $active_state );
2900
				} else {
2901
					$active_state = array();
2902
				}
2903
				$active_state[] = $module;
2904
				Jetpack::state( $state, implode( ',', $active_state ) );
2905
			}
2906
2907
			Jetpack::update_active_modules( $active );
2908
2909
			ob_end_clean();
2910
		}
2911
2912
		if ( $send_state_messages ) {
2913
			Jetpack::state( 'error', false );
2914
			Jetpack::state( 'module', false );
2915
		}
2916
2917
		Jetpack::catch_errors( false );
2918
		/**
2919
		 * Fires when default modules are activated.
2920
		 *
2921
		 * @since 1.9.0
2922
		 *
2923
		 * @param string $min_version Minimum version number required to use modules.
2924
		 * @param string $max_version Maximum version number required to use modules.
2925
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2926
		 */
2927
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2928
	}
2929
2930
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2931
		/**
2932
		 * Fires before a module is activated.
2933
		 *
2934
		 * @since 2.6.0
2935
		 *
2936
		 * @param string $module Module slug.
2937
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2938
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2939
		 */
2940
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2941
2942
		$jetpack = Jetpack::init();
2943
2944
		if ( ! strlen( $module ) )
2945
			return false;
2946
2947
		if ( ! Jetpack::is_module( $module ) )
2948
			return false;
2949
2950
		// If it's already active, then don't do it again
2951
		$active = Jetpack::get_active_modules();
2952
		foreach ( $active as $act ) {
2953
			if ( $act == $module )
2954
				return true;
2955
		}
2956
2957
		$module_data = Jetpack::get_module( $module );
2958
2959
		if ( ! Jetpack::is_active() ) {
2960
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2961
				return false;
2962
2963
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2964
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2965
				return false;
2966
		}
2967
2968
		// Check and see if the old plugin is active
2969
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2970
			// Deactivate the old plugin
2971
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2972
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2973
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2974
				Jetpack::state( 'deactivated_plugins', $module );
2975
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2976
				exit;
2977
			}
2978
		}
2979
2980
		// Protect won't work with mis-configured IPs
2981
		if ( 'protect' === $module ) {
2982
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2983
			if ( ! jetpack_protect_get_ip() ) {
2984
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2985
				return false;
2986
			}
2987
		}
2988
2989
		if ( ! Jetpack_Plan::supports( $module ) ) {
2990
			return false;
2991
		}
2992
2993
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2994
		Jetpack::state( 'module', $module );
2995
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2996
2997
		Jetpack::catch_errors( true );
2998
		ob_start();
2999
		require Jetpack::get_module_path( $module );
3000
		/** This action is documented in class.jetpack.php */
3001
		do_action( 'jetpack_activate_module', $module );
3002
		$active[] = $module;
3003
		Jetpack::update_active_modules( $active );
3004
3005
		Jetpack::state( 'error', false ); // the override
3006
		ob_end_clean();
3007
		Jetpack::catch_errors( false );
3008
3009
		if ( $redirect ) {
3010
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3011
		}
3012
		if ( $exit ) {
3013
			exit;
3014
		}
3015
		return true;
3016
	}
3017
3018
	function activate_module_actions( $module ) {
3019
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3020
	}
3021
3022
	public static function deactivate_module( $module ) {
3023
		/**
3024
		 * Fires when a module is deactivated.
3025
		 *
3026
		 * @since 1.9.0
3027
		 *
3028
		 * @param string $module Module slug.
3029
		 */
3030
		do_action( 'jetpack_pre_deactivate_module', $module );
3031
3032
		$jetpack = Jetpack::init();
3033
3034
		$active = Jetpack::get_active_modules();
3035
		$new    = array_filter( array_diff( $active, (array) $module ) );
3036
3037
		return self::update_active_modules( $new );
3038
	}
3039
3040
	public static function enable_module_configurable( $module ) {
3041
		$module = Jetpack::get_module_slug( $module );
3042
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3043
	}
3044
3045
	/**
3046
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3047
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3048
	 *
3049
	 * @param string $module Module slug
3050
	 * @return string $url module configuration URL
3051
	 */
3052
	public static function module_configuration_url( $module ) {
3053
		$module = Jetpack::get_module_slug( $module );
3054
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3055
		/**
3056
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3057
		 *
3058
		 * @since 6.9.0
3059
		 *
3060
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3061
		 */
3062
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3063
3064
		return $url;
3065
	}
3066
3067
/* Installation */
3068
	public static function bail_on_activation( $message, $deactivate = true ) {
3069
?>
3070
<!doctype html>
3071
<html>
3072
<head>
3073
<meta charset="<?php bloginfo( 'charset' ); ?>">
3074
<style>
3075
* {
3076
	text-align: center;
3077
	margin: 0;
3078
	padding: 0;
3079
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3080
}
3081
p {
3082
	margin-top: 1em;
3083
	font-size: 18px;
3084
}
3085
</style>
3086
<body>
3087
<p><?php echo esc_html( $message ); ?></p>
3088
</body>
3089
</html>
3090
<?php
3091
		if ( $deactivate ) {
3092
			$plugins = get_option( 'active_plugins' );
3093
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3094
			$update  = false;
3095
			foreach ( $plugins as $i => $plugin ) {
3096
				if ( $plugin === $jetpack ) {
3097
					$plugins[$i] = false;
3098
					$update = true;
3099
				}
3100
			}
3101
3102
			if ( $update ) {
3103
				update_option( 'active_plugins', array_filter( $plugins ) );
3104
			}
3105
		}
3106
		exit;
3107
	}
3108
3109
	/**
3110
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3111
	 * @static
3112
	 */
3113
	public static function plugin_activation( $network_wide ) {
3114
		Jetpack_Options::update_option( 'activated', 1 );
3115
3116
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3117
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3118
		}
3119
3120
		if ( $network_wide )
3121
			Jetpack::state( 'network_nag', true );
3122
3123
		// For firing one-off events (notices) immediately after activation
3124
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3125
3126
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3127
3128
		Jetpack::plugin_initialize();
3129
	}
3130
3131
	public static function get_activation_source( $referer_url ) {
3132
3133
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3134
			return array( 'wp-cli', null );
3135
		}
3136
3137
		$referer = parse_url( $referer_url );
3138
3139
		$source_type = 'unknown';
3140
		$source_query = null;
3141
3142
		if ( ! is_array( $referer ) ) {
3143
			return array( $source_type, $source_query );
3144
		}
3145
3146
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3147
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3148
3149
		if ( isset( $referer['query'] ) ) {
3150
			parse_str( $referer['query'], $query_parts );
3151
		} else {
3152
			$query_parts = array();
3153
		}
3154
3155
		if ( $plugins_path === $referer['path'] ) {
3156
			$source_type = 'list';
3157
		} elseif ( $plugins_install_path === $referer['path'] ) {
3158
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3159
			switch( $tab ) {
3160
				case 'popular':
3161
					$source_type = 'popular';
3162
					break;
3163
				case 'recommended':
3164
					$source_type = 'recommended';
3165
					break;
3166
				case 'favorites':
3167
					$source_type = 'favorites';
3168
					break;
3169
				case 'search':
3170
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3171
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3172
					break;
3173
				default:
3174
					$source_type = 'featured';
3175
			}
3176
		}
3177
3178
		return array( $source_type, $source_query );
3179
	}
3180
3181
	/**
3182
	 * Runs before bumping version numbers up to a new version
3183
	 * @param  string $version    Version:timestamp
3184
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3185
	 * @return null              [description]
3186
	 */
3187
	public static function do_version_bump( $version, $old_version ) {
3188
		if ( ! $old_version ) { // For new sites
3189
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3190
		}
3191
	}
3192
3193
	/**
3194
	 * Sets the internal version number and activation state.
3195
	 * @static
3196
	 */
3197
	public static function plugin_initialize() {
3198
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3199
			Jetpack_Options::update_option( 'activated', 2 );
3200
		}
3201
3202 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3203
			$version = $old_version = JETPACK__VERSION . ':' . time();
3204
			/** This action is documented in class.jetpack.php */
3205
			do_action( 'updating_jetpack_version', $version, false );
3206
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3207
		}
3208
3209
		Jetpack::load_modules();
3210
3211
		Jetpack_Options::delete_option( 'do_activate' );
3212
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3213
	}
3214
3215
	/**
3216
	 * Removes all connection options
3217
	 * @static
3218
	 */
3219
	public static function plugin_deactivation( ) {
3220
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3221
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3222
			Jetpack_Network::init()->deactivate();
3223
		} else {
3224
			Jetpack::disconnect( false );
3225
			//Jetpack_Heartbeat::init()->deactivate();
3226
		}
3227
	}
3228
3229
	/**
3230
	 * Disconnects from the Jetpack servers.
3231
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3232
	 * @static
3233
	 */
3234
	public static function disconnect( $update_activated_state = true ) {
3235
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3236
		Jetpack::clean_nonces( true );
3237
3238
		// If the site is in an IDC because sync is not allowed,
3239
		// let's make sure to not disconnect the production site.
3240
		if ( ! self::validate_sync_error_idc_option() ) {
3241
			$tracking = new Tracking();
3242
			$tracking->record_user_event( 'disconnect_site', array() );
3243
			Jetpack::load_xml_rpc_client();
3244
			$xml = new Jetpack_IXR_Client();
3245
			$xml->query( 'jetpack.deregister' );
3246
		}
3247
3248
		Jetpack_Options::delete_option(
3249
			array(
3250
				'blog_token',
3251
				'user_token',
3252
				'user_tokens',
3253
				'master_user',
3254
				'time_diff',
3255
				'fallback_no_verify_ssl_certs',
3256
			)
3257
		);
3258
3259
		Jetpack_IDC::clear_all_idc_options();
3260
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3261
3262
		if ( $update_activated_state ) {
3263
			Jetpack_Options::update_option( 'activated', 4 );
3264
		}
3265
3266
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3267
			// Check then record unique disconnection if site has never been disconnected previously
3268
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3269
				$jetpack_unique_connection['disconnected'] = 1;
3270
			} else {
3271
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3272
					//track unique disconnect
3273
					$jetpack = Jetpack::init();
3274
3275
					$jetpack->stat( 'connections', 'unique-disconnect' );
3276
					$jetpack->do_stats( 'server_side' );
3277
				}
3278
				// increment number of times disconnected
3279
				$jetpack_unique_connection['disconnected'] += 1;
3280
			}
3281
3282
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3283
		}
3284
3285
		// Delete cached connected user data
3286
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3287
		delete_transient( $transient_key );
3288
3289
		// Delete all the sync related data. Since it could be taking up space.
3290
		Sender::get_instance()->uninstall();
3291
3292
		// Disable the Heartbeat cron
3293
		Jetpack_Heartbeat::init()->deactivate();
3294
	}
3295
3296
	/**
3297
	 * Unlinks the current user from the linked WordPress.com user
3298
	 */
3299
	public static function unlink_user( $user_id = null ) {
3300
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3301
			return false;
3302
3303
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3304
3305
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3306
			return false;
3307
3308
		if ( ! isset( $tokens[ $user_id ] ) )
3309
			return false;
3310
3311
		Jetpack::load_xml_rpc_client();
3312
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3313
		$xml->query( 'jetpack.unlink_user', $user_id );
3314
3315
		unset( $tokens[ $user_id ] );
3316
3317
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3318
3319
		/**
3320
		 * Fires after the current user has been unlinked from WordPress.com.
3321
		 *
3322
		 * @since 4.1.0
3323
		 *
3324
		 * @param int $user_id The current user's ID.
3325
		 */
3326
		do_action( 'jetpack_unlinked_user', $user_id );
3327
3328
		return true;
3329
	}
3330
3331
	/**
3332
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3333
	 */
3334
	public static function try_registration() {
3335
		// The user has agreed to the TOS at some point by now.
3336
		Jetpack_Options::update_option( 'tos_agreed', true );
3337
3338
		// Let's get some testing in beta versions and such.
3339
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3340
			// Before attempting to connect, let's make sure that the domains are viable.
3341
			$domains_to_check = array_unique( array(
3342
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3343
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3344
			) );
3345
			foreach ( $domains_to_check as $domain ) {
3346
				$result = self::connection()->is_usable_domain( $domain );
3347
				if ( is_wp_error( $result ) ) {
3348
					return $result;
3349
				}
3350
			}
3351
		}
3352
3353
		$result = Jetpack::register();
3354
3355
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3356
		if ( ! $result || is_wp_error( $result ) ) {
3357
			return $result;
3358
		} else {
3359
			return true;
3360
		}
3361
	}
3362
3363
	/**
3364
	 * Tracking an internal event log. Try not to put too much chaff in here.
3365
	 *
3366
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3367
	 */
3368
	public static function log( $code, $data = null ) {
3369
		// only grab the latest 200 entries
3370
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3371
3372
		// Append our event to the log
3373
		$log_entry = array(
3374
			'time'    => time(),
3375
			'user_id' => get_current_user_id(),
3376
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3377
			'code'    => $code,
3378
		);
3379
		// Don't bother storing it unless we've got some.
3380
		if ( ! is_null( $data ) ) {
3381
			$log_entry['data'] = $data;
3382
		}
3383
		$log[] = $log_entry;
3384
3385
		// Try add_option first, to make sure it's not autoloaded.
3386
		// @todo: Add an add_option method to Jetpack_Options
3387
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3388
			Jetpack_Options::update_option( 'log', $log );
3389
		}
3390
3391
		/**
3392
		 * Fires when Jetpack logs an internal event.
3393
		 *
3394
		 * @since 3.0.0
3395
		 *
3396
		 * @param array $log_entry {
3397
		 *	Array of details about the log entry.
3398
		 *
3399
		 *	@param string time Time of the event.
3400
		 *	@param int user_id ID of the user who trigerred the event.
3401
		 *	@param int blog_id Jetpack Blog ID.
3402
		 *	@param string code Unique name for the event.
3403
		 *	@param string data Data about the event.
3404
		 * }
3405
		 */
3406
		do_action( 'jetpack_log_entry', $log_entry );
3407
	}
3408
3409
	/**
3410
	 * Get the internal event log.
3411
	 *
3412
	 * @param $event (string) - only return the specific log events
3413
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3414
	 *
3415
	 * @return array of log events || WP_Error for invalid params
3416
	 */
3417
	public static function get_log( $event = false, $num = false ) {
3418
		if ( $event && ! is_string( $event ) ) {
3419
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
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...
3420
		}
3421
3422
		if ( $num && ! is_numeric( $num ) ) {
3423
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
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...
3424
		}
3425
3426
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3427
3428
		// If nothing set - act as it did before, otherwise let's start customizing the output
3429
		if ( ! $num && ! $event ) {
3430
			return $entire_log;
3431
		} else {
3432
			$entire_log = array_reverse( $entire_log );
3433
		}
3434
3435
		$custom_log_output = array();
3436
3437
		if ( $event ) {
3438
			foreach ( $entire_log as $log_event ) {
3439
				if ( $event == $log_event[ 'code' ] ) {
3440
					$custom_log_output[] = $log_event;
3441
				}
3442
			}
3443
		} else {
3444
			$custom_log_output = $entire_log;
3445
		}
3446
3447
		if ( $num ) {
3448
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3449
		}
3450
3451
		return $custom_log_output;
3452
	}
3453
3454
	/**
3455
	 * Log modification of important settings.
3456
	 */
3457
	public static function log_settings_change( $option, $old_value, $value ) {
3458
		switch( $option ) {
3459
			case 'jetpack_sync_non_public_post_stati':
3460
				self::log( $option, $value );
3461
				break;
3462
		}
3463
	}
3464
3465
	/**
3466
	 * Return stat data for WPCOM sync
3467
	 */
3468
	public static function get_stat_data( $encode = true, $extended = true ) {
3469
		$data = Jetpack_Heartbeat::generate_stats_array();
3470
3471
		if ( $extended ) {
3472
			$additional_data = self::get_additional_stat_data();
3473
			$data = array_merge( $data, $additional_data );
3474
		}
3475
3476
		if ( $encode ) {
3477
			return json_encode( $data );
3478
		}
3479
3480
		return $data;
3481
	}
3482
3483
	/**
3484
	 * Get additional stat data to sync to WPCOM
3485
	 */
3486
	public static function get_additional_stat_data( $prefix = '' ) {
3487
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3488
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3489
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3490
		$return["{$prefix}site-count"]     = 0;
3491
3492
		if ( function_exists( 'get_blog_count' ) ) {
3493
			$return["{$prefix}site-count"] = get_blog_count();
3494
		}
3495
		return $return;
3496
	}
3497
3498
	private static function get_site_user_count() {
3499
		global $wpdb;
3500
3501
		if ( function_exists( 'wp_is_large_network' ) ) {
3502
			if ( wp_is_large_network( 'users' ) ) {
3503
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3504
			}
3505
		}
3506 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3507
			// It wasn't there, so regenerate the data and save the transient
3508
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3509
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3510
		}
3511
		return $user_count;
3512
	}
3513
3514
	/* Admin Pages */
3515
3516
	function admin_init() {
3517
		// If the plugin is not connected, display a connect message.
3518
		if (
3519
			// the plugin was auto-activated and needs its candy
3520
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3521
		||
3522
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3523
			! Jetpack_Options::get_option( 'activated' )
3524
		) {
3525
			Jetpack::plugin_initialize();
3526
		}
3527
3528
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3529
			Jetpack_Connection_Banner::init();
3530
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3531
			// Upgrade: 1.1 -> 1.1.1
3532
			// Check and see if host can verify the Jetpack servers' SSL certificate
3533
			$args = array();
3534
			Client::_wp_remote_request(
3535
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3536
				$args,
3537
				true
3538
			);
3539
		}
3540
3541
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3542
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3543
		}
3544
3545
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3546
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3547
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3548
3549
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3550
			// Artificially throw errors in certain whitelisted cases during plugin activation
3551
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3552
		}
3553
3554
		// Add custom column in wp-admin/users.php to show whether user is linked.
3555
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3556
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3557
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3558
	}
3559
3560
	function admin_body_class( $admin_body_class = '' ) {
3561
		$classes = explode( ' ', trim( $admin_body_class ) );
3562
3563
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3564
3565
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3566
		return " $admin_body_class ";
3567
	}
3568
3569
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3570
		return $admin_body_class . ' jetpack-pagestyles ';
3571
	}
3572
3573
	/**
3574
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3575
	 * This function artificially throws errors for such cases (whitelisted).
3576
	 *
3577
	 * @param string $plugin The activated plugin.
3578
	 */
3579
	function throw_error_on_activate_plugin( $plugin ) {
3580
		$active_modules = Jetpack::get_active_modules();
3581
3582
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3583
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3584
			$throw = false;
3585
3586
			// Try and make sure it really was the stats plugin
3587
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3588
				if ( 'stats.php' == basename( $plugin ) ) {
3589
					$throw = true;
3590
				}
3591
			} else {
3592
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3593
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3594
					$throw = true;
3595
				}
3596
			}
3597
3598
			if ( $throw ) {
3599
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3600
			}
3601
		}
3602
	}
3603
3604
	function intercept_plugin_error_scrape_init() {
3605
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3606
	}
3607
3608
	function intercept_plugin_error_scrape( $action, $result ) {
3609
		if ( ! $result ) {
3610
			return;
3611
		}
3612
3613
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3614
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3615
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3616
			}
3617
		}
3618
	}
3619
3620
	function add_remote_request_handlers() {
3621
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3622
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3623
	}
3624
3625
	function remote_request_handlers() {
3626
		$action = current_filter();
3627
3628
		switch ( current_filter() ) {
3629
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3630
			$response = $this->upload_handler();
3631
			break;
3632
3633
		case 'wp_ajax_nopriv_jetpack_update_file' :
3634
			$response = $this->upload_handler( true );
3635
			break;
3636
		default :
3637
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
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...
3638
			break;
3639
		}
3640
3641
		if ( ! $response ) {
3642
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
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...
3643
		}
3644
3645
		if ( is_wp_error( $response ) ) {
3646
			$status_code       = $response->get_error_data();
0 ignored issues
show
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...
3647
			$error             = $response->get_error_code();
0 ignored issues
show
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...
3648
			$error_description = $response->get_error_message();
0 ignored issues
show
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...
3649
3650
			if ( ! is_int( $status_code ) ) {
3651
				$status_code = 400;
3652
			}
3653
3654
			status_header( $status_code );
3655
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3656
		}
3657
3658
		status_header( 200 );
3659
		if ( true === $response ) {
3660
			exit;
3661
		}
3662
3663
		die( json_encode( (object) $response ) );
3664
	}
3665
3666
	/**
3667
	 * Uploads a file gotten from the global $_FILES.
3668
	 * If `$update_media_item` is true and `post_id` is defined
3669
	 * the attachment file of the media item (gotten through of the post_id)
3670
	 * will be updated instead of add a new one.
3671
	 *
3672
	 * @param  boolean $update_media_item - update media attachment
3673
	 * @return array - An array describing the uploadind files process
3674
	 */
3675
	function upload_handler( $update_media_item = false ) {
3676
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3677
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
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...
3678
		}
3679
3680
		$user = wp_authenticate( '', '' );
3681
		if ( ! $user || is_wp_error( $user ) ) {
3682
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
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...
3683
		}
3684
3685
		wp_set_current_user( $user->ID );
3686
3687
		if ( ! current_user_can( 'upload_files' ) ) {
3688
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
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...
3689
		}
3690
3691
		if ( empty( $_FILES ) ) {
3692
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
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...
3693
		}
3694
3695
		foreach ( array_keys( $_FILES ) as $files_key ) {
3696
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3697
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
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...
3698
			}
3699
		}
3700
3701
		$media_keys = array_keys( $_FILES['media'] );
3702
3703
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3704
		if ( ! $token || is_wp_error( $token ) ) {
3705
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
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...
3706
		}
3707
3708
		$uploaded_files = array();
3709
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3710
		unset( $GLOBALS['post'] );
3711
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3712
			$file = array();
3713
			foreach ( $media_keys as $media_key ) {
3714
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3715
			}
3716
3717
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3718
3719
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3720
			if ( $hmac_provided !== $hmac_file ) {
3721
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3722
				continue;
3723
			}
3724
3725
			$_FILES['.jetpack.upload.'] = $file;
3726
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3727
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3728
				$post_id = 0;
3729
			}
3730
3731
			if ( $update_media_item ) {
3732
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3733
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
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...
3734
				}
3735
3736
				$media_array = $_FILES['media'];
3737
3738
				$file_array['name'] = $media_array['name'][0];
3739
				$file_array['type'] = $media_array['type'][0];
3740
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3741
				$file_array['error'] = $media_array['error'][0];
3742
				$file_array['size'] = $media_array['size'][0];
3743
3744
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3745
3746
				if ( is_wp_error( $edited_media_item ) ) {
3747
					return $edited_media_item;
3748
				}
3749
3750
				$response = (object) array(
3751
					'id'   => (string) $post_id,
3752
					'file' => (string) $edited_media_item->post_title,
3753
					'url'  => (string) wp_get_attachment_url( $post_id ),
3754
					'type' => (string) $edited_media_item->post_mime_type,
3755
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3756
				);
3757
3758
				return (array) array( $response );
3759
			}
3760
3761
			$attachment_id = media_handle_upload(
3762
				'.jetpack.upload.',
3763
				$post_id,
3764
				array(),
3765
				array(
3766
					'action' => 'jetpack_upload_file',
3767
				)
3768
			);
3769
3770
			if ( ! $attachment_id ) {
3771
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3772
			} elseif ( is_wp_error( $attachment_id ) ) {
3773
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3774
			} else {
3775
				$attachment = get_post( $attachment_id );
3776
				$uploaded_files[$index] = (object) array(
3777
					'id'   => (string) $attachment_id,
3778
					'file' => $attachment->post_title,
3779
					'url'  => wp_get_attachment_url( $attachment_id ),
3780
					'type' => $attachment->post_mime_type,
3781
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3782
				);
3783
				// Zip files uploads are not supported unless they are done for installation purposed
3784
				// lets delete them in case something goes wrong in this whole process
3785
				if ( 'application/zip' === $attachment->post_mime_type ) {
3786
					// Schedule a cleanup for 2 hours from now in case of failed install.
3787
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3788
				}
3789
			}
3790
		}
3791
		if ( ! is_null( $global_post ) ) {
3792
			$GLOBALS['post'] = $global_post;
3793
		}
3794
3795
		return $uploaded_files;
3796
	}
3797
3798
	/**
3799
	 * Add help to the Jetpack page
3800
	 *
3801
	 * @since Jetpack (1.2.3)
3802
	 * @return false if not the Jetpack page
3803
	 */
3804
	function admin_help() {
3805
		$current_screen = get_current_screen();
3806
3807
		// Overview
3808
		$current_screen->add_help_tab(
3809
			array(
3810
				'id'		=> 'home',
3811
				'title'		=> __( 'Home', 'jetpack' ),
3812
				'content'	=>
3813
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3814
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3815
					'<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>',
3816
			)
3817
		);
3818
3819
		// Screen Content
3820
		if ( current_user_can( 'manage_options' ) ) {
3821
			$current_screen->add_help_tab(
3822
				array(
3823
					'id'		=> 'settings',
3824
					'title'		=> __( 'Settings', 'jetpack' ),
3825
					'content'	=>
3826
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3827
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3828
						'<ol>' .
3829
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3830
							'<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>' .
3831
						'</ol>' .
3832
						'<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>'
3833
				)
3834
			);
3835
		}
3836
3837
		// Help Sidebar
3838
		$current_screen->set_help_sidebar(
3839
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3840
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3841
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3842
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3843
		);
3844
	}
3845
3846
	function admin_menu_css() {
3847
		wp_enqueue_style( 'jetpack-icons' );
3848
	}
3849
3850
	function admin_menu_order() {
3851
		return true;
3852
	}
3853
3854 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3855
		$jp_menu_order = array();
3856
3857
		foreach ( $menu_order as $index => $item ) {
3858
			if ( $item != 'jetpack' ) {
3859
				$jp_menu_order[] = $item;
3860
			}
3861
3862
			if ( $index == 0 ) {
3863
				$jp_menu_order[] = 'jetpack';
3864
			}
3865
		}
3866
3867
		return $jp_menu_order;
3868
	}
3869
3870
	function admin_banner_styles() {
3871
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3872
3873
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3874
			wp_register_style(
3875
				'jetpack-dops-style',
3876
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3877
				array(),
3878
				JETPACK__VERSION
3879
			);
3880
		}
3881
3882
		wp_enqueue_style(
3883
			'jetpack',
3884
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3885
			array( 'jetpack-dops-style' ),
3886
			 JETPACK__VERSION . '-20121016'
3887
		);
3888
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3889
		wp_style_add_data( 'jetpack', 'suffix', $min );
3890
	}
3891
3892
	function plugin_action_links( $actions ) {
3893
3894
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3895
3896
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3897
			return array_merge(
3898
				$jetpack_home,
3899
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3900
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3901
				$actions
3902
				);
3903
			}
3904
3905
		return array_merge( $jetpack_home, $actions );
3906
	}
3907
3908
	/*
3909
	 * Registration flow:
3910
	 * 1 - ::admin_page_load() action=register
3911
	 * 2 - ::try_registration()
3912
	 * 3 - ::register()
3913
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3914
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3915
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3916
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3917
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3918
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3919
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3920
	 *       jetpack_id, jetpack_secret, jetpack_public
3921
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3922
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3923
	 * 5 - user logs in with WP.com account
3924
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3925
	 *		- Jetpack_Client_Server::authorize()
3926
	 *		- Jetpack_Client_Server::get_token()
3927
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3928
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3929
	 *			- which responds with access_token, token_type, scope
3930
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3931
	 *		- Jetpack::activate_default_modules()
3932
	 *     		- Deactivates deprecated plugins
3933
	 *     		- Activates all default modules
3934
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3935
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3936
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3937
	 *     Done!
3938
	 */
3939
3940
	/**
3941
	 * Handles the page load events for the Jetpack admin page
3942
	 */
3943
	function admin_page_load() {
3944
		$error = false;
3945
3946
		// Make sure we have the right body class to hook stylings for subpages off of.
3947
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3948
3949
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3950
			// Should only be used in intermediate redirects to preserve state across redirects
3951
			Jetpack::restate();
3952
		}
3953
3954
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3955
			// @todo: Add validation against a known whitelist
3956
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3957
			// User clicked in the iframe to link their accounts
3958
			if ( ! Jetpack::is_user_connected() ) {
3959
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3960
3961
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3962
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3963
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3964
3965
				if ( isset( $_GET['notes_iframe'] ) )
3966
					$connect_url .= '&notes_iframe';
3967
				wp_redirect( $connect_url );
3968
				exit;
3969
			} else {
3970
				if ( ! isset( $_GET['calypso_env'] ) ) {
3971
					Jetpack::state( 'message', 'already_authorized' );
3972
					wp_safe_redirect( Jetpack::admin_url() );
3973
					exit;
3974
				} else {
3975
					$connect_url = $this->build_connect_url( true, false, $from );
3976
					$connect_url .= '&already_authorized=true';
3977
					wp_redirect( $connect_url );
3978
					exit;
3979
				}
3980
			}
3981
		}
3982
3983
3984
		if ( isset( $_GET['action'] ) ) {
3985
			switch ( $_GET['action'] ) {
3986
			case 'authorize':
3987
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3988
					Jetpack::state( 'message', 'already_authorized' );
3989
					wp_safe_redirect( Jetpack::admin_url() );
3990
					exit;
3991
				}
3992
				Jetpack::log( 'authorize' );
3993
				$client_server = new Jetpack_Client_Server;
3994
				$client_server->client_authorize();
3995
				exit;
3996
			case 'register' :
3997
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3998
					$error = 'cheatin';
3999
					break;
4000
				}
4001
				check_admin_referer( 'jetpack-register' );
4002
				Jetpack::log( 'register' );
4003
				Jetpack::maybe_set_version_option();
4004
				$registered = Jetpack::try_registration();
4005
				if ( is_wp_error( $registered ) ) {
4006
					$error = $registered->get_error_code();
0 ignored issues
show
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...
4007
					Jetpack::state( 'error', $error );
4008
					Jetpack::state( 'error', $registered->get_error_message() );
0 ignored issues
show
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...
4009
4010
					/**
4011
					 * Jetpack registration Error.
4012
					 *
4013
					 * @since 7.5.0
4014
					 *
4015
					 * @param string|int $error The error code.
4016
					 * @param \WP_Error $registered The error object.
4017
					 */
4018
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4019
					break;
4020
				}
4021
4022
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4023
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4024
4025
				/**
4026
				 * Jetpack registration Success.
4027
				 *
4028
				 * @since 7.5.0
4029
				 *
4030
				 * @param string $from 'from' GET parameter;
4031
				 */
4032
				do_action( 'jetpack_connection_register_success', $from );
4033
4034
				$url = $this->build_connect_url( true, $redirect, $from );
4035
4036
				if ( ! empty( $_GET['onboarding'] ) ) {
4037
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4038
				}
4039
4040
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4041
					$url = add_query_arg( 'auth_approved', 'true', $url );
4042
				}
4043
4044
				wp_redirect( $url );
4045
				exit;
4046
			case 'activate' :
4047
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4048
					$error = 'cheatin';
4049
					break;
4050
				}
4051
4052
				$module = stripslashes( $_GET['module'] );
4053
				check_admin_referer( "jetpack_activate-$module" );
4054
				Jetpack::log( 'activate', $module );
4055
				if ( ! Jetpack::activate_module( $module ) ) {
4056
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4057
				}
4058
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4059
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4060
				exit;
4061
			case 'activate_default_modules' :
4062
				check_admin_referer( 'activate_default_modules' );
4063
				Jetpack::log( 'activate_default_modules' );
4064
				Jetpack::restate();
4065
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4066
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4067
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4068
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4069
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4070
				exit;
4071
			case 'disconnect' :
4072
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4073
					$error = 'cheatin';
4074
					break;
4075
				}
4076
4077
				check_admin_referer( 'jetpack-disconnect' );
4078
				Jetpack::log( 'disconnect' );
4079
				Jetpack::disconnect();
4080
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4081
				exit;
4082
			case 'reconnect' :
4083
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4084
					$error = 'cheatin';
4085
					break;
4086
				}
4087
4088
				check_admin_referer( 'jetpack-reconnect' );
4089
				Jetpack::log( 'reconnect' );
4090
				$this->disconnect();
4091
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4092
				exit;
4093 View Code Duplication
			case 'deactivate' :
4094
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4095
					$error = 'cheatin';
4096
					break;
4097
				}
4098
4099
				$modules = stripslashes( $_GET['module'] );
4100
				check_admin_referer( "jetpack_deactivate-$modules" );
4101
				foreach ( explode( ',', $modules ) as $module ) {
4102
					Jetpack::log( 'deactivate', $module );
4103
					Jetpack::deactivate_module( $module );
4104
					Jetpack::state( 'message', 'module_deactivated' );
4105
				}
4106
				Jetpack::state( 'module', $modules );
4107
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4108
				exit;
4109
			case 'unlink' :
4110
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4111
				check_admin_referer( 'jetpack-unlink' );
4112
				Jetpack::log( 'unlink' );
4113
				$this->unlink_user();
4114
				Jetpack::state( 'message', 'unlinked' );
4115
				if ( 'sub-unlink' == $redirect ) {
4116
					wp_safe_redirect( admin_url() );
4117
				} else {
4118
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4119
				}
4120
				exit;
4121
			case 'onboard' :
4122
				if ( ! current_user_can( 'manage_options' ) ) {
4123
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4124
				} else {
4125
					Jetpack::create_onboarding_token();
4126
					$url = $this->build_connect_url( true );
4127
4128
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4129
						$url = add_query_arg( 'onboarding', $token, $url );
4130
					}
4131
4132
					$calypso_env = $this->get_calypso_env();
4133
					if ( ! empty( $calypso_env ) ) {
4134
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4135
					}
4136
4137
					wp_redirect( $url );
4138
					exit;
4139
				}
4140
				exit;
4141
			default:
4142
				/**
4143
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4144
				 *
4145
				 * @since 2.6.0
4146
				 *
4147
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4148
				 */
4149
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4150
			}
4151
		}
4152
4153
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4154
			self::activate_new_modules( true );
4155
		}
4156
4157
		$message_code = Jetpack::state( 'message' );
4158
		if ( Jetpack::state( 'optin-manage' ) ) {
4159
			$activated_manage = $message_code;
4160
			$message_code = 'jetpack-manage';
4161
		}
4162
4163
		switch ( $message_code ) {
4164
		case 'jetpack-manage':
4165
			$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>';
4166
			if ( $activated_manage ) {
4167
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4168
			}
4169
			break;
4170
4171
		}
4172
4173
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4174
4175
		if ( ! empty( $deactivated_plugins ) ) {
4176
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4177
			$deactivated_titles  = array();
4178
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4179
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4180
					continue;
4181
				}
4182
4183
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4184
			}
4185
4186
			if ( $deactivated_titles ) {
4187
				if ( $this->message ) {
4188
					$this->message .= "<br /><br />\n";
4189
				}
4190
4191
				$this->message .= wp_sprintf(
4192
					_n(
4193
						'Jetpack contains the most recent version of the old %l plugin.',
4194
						'Jetpack contains the most recent versions of the old %l plugins.',
4195
						count( $deactivated_titles ),
4196
						'jetpack'
4197
					),
4198
					$deactivated_titles
4199
				);
4200
4201
				$this->message .= "<br />\n";
4202
4203
				$this->message .= _n(
4204
					'The old version has been deactivated and can be removed from your site.',
4205
					'The old versions have been deactivated and can be removed from your site.',
4206
					count( $deactivated_titles ),
4207
					'jetpack'
4208
				);
4209
			}
4210
		}
4211
4212
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4213
4214
		if ( $this->message || $this->error || $this->privacy_checks ) {
4215
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4216
		}
4217
4218
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4219
	}
4220
4221
	function admin_notices() {
4222
4223
		if ( $this->error ) {
4224
?>
4225
<div id="message" class="jetpack-message jetpack-err">
4226
	<div class="squeezer">
4227
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4228
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4229
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4230
<?php	endif; ?>
4231
	</div>
4232
</div>
4233
<?php
4234
		}
4235
4236
		if ( $this->message ) {
4237
?>
4238
<div id="message" class="jetpack-message">
4239
	<div class="squeezer">
4240
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4241
	</div>
4242
</div>
4243
<?php
4244
		}
4245
4246
		if ( $this->privacy_checks ) :
4247
			$module_names = $module_slugs = array();
4248
4249
			$privacy_checks = explode( ',', $this->privacy_checks );
4250
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4251
			foreach ( $privacy_checks as $module_slug ) {
4252
				$module = Jetpack::get_module( $module_slug );
4253
				if ( ! $module ) {
4254
					continue;
4255
				}
4256
4257
				$module_slugs[] = $module_slug;
4258
				$module_names[] = "<strong>{$module['name']}</strong>";
4259
			}
4260
4261
			$module_slugs = join( ',', $module_slugs );
4262
?>
4263
<div id="message" class="jetpack-message jetpack-err">
4264
	<div class="squeezer">
4265
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4266
		<p><?php
4267
			echo wp_kses(
4268
				wptexturize(
4269
					wp_sprintf(
4270
						_nx(
4271
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4272
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4273
							count( $privacy_checks ),
4274
							'%l = list of Jetpack module/feature names',
4275
							'jetpack'
4276
						),
4277
						$module_names
4278
					)
4279
				),
4280
				array( 'strong' => true )
4281
			);
4282
4283
			echo "\n<br />\n";
4284
4285
			echo wp_kses(
4286
				sprintf(
4287
					_nx(
4288
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4289
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4290
						count( $privacy_checks ),
4291
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4292
						'jetpack'
4293
					),
4294
					wp_nonce_url(
4295
						Jetpack::admin_url(
4296
							array(
4297
								'page'   => 'jetpack',
4298
								'action' => 'deactivate',
4299
								'module' => urlencode( $module_slugs ),
4300
							)
4301
						),
4302
						"jetpack_deactivate-$module_slugs"
4303
					),
4304
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4305
				),
4306
				array( 'a' => array( 'href' => true, 'title' => true ) )
4307
			);
4308
		?></p>
4309
	</div>
4310
</div>
4311
<?php endif;
4312
	}
4313
4314
	/**
4315
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4316
	 */
4317
	function stat( $group, $detail ) {
4318
		if ( ! isset( $this->stats[ $group ] ) )
4319
			$this->stats[ $group ] = array();
4320
		$this->stats[ $group ][] = $detail;
4321
	}
4322
4323
	/**
4324
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4325
	 */
4326
	function do_stats( $method = '' ) {
4327
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4328
			foreach ( $this->stats as $group => $stats ) {
4329
				if ( is_array( $stats ) && count( $stats ) ) {
4330
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4331
					if ( 'server_side' === $method ) {
4332
						self::do_server_side_stat( $args );
4333
					} else {
4334
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4335
					}
4336
				}
4337
				unset( $this->stats[ $group ] );
4338
			}
4339
		}
4340
	}
4341
4342
	/**
4343
	 * Runs stats code for a one-off, server-side.
4344
	 *
4345
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4346
	 *
4347
	 * @return bool If it worked.
4348
	 */
4349
	static function do_server_side_stat( $args ) {
4350
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4351
		if ( is_wp_error( $response ) )
4352
			return false;
4353
4354
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4355
			return false;
4356
4357
		return true;
4358
	}
4359
4360
	/**
4361
	 * Builds the stats url.
4362
	 *
4363
	 * @param $args array|string The arguments to append to the URL.
4364
	 *
4365
	 * @return string The URL to be pinged.
4366
	 */
4367
	static function build_stats_url( $args ) {
4368
		$defaults = array(
4369
			'v'    => 'wpcom2',
4370
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4371
		);
4372
		$args     = wp_parse_args( $args, $defaults );
4373
		/**
4374
		 * Filter the URL used as the Stats tracking pixel.
4375
		 *
4376
		 * @since 2.3.2
4377
		 *
4378
		 * @param string $url Base URL used as the Stats tracking pixel.
4379
		 */
4380
		$base_url = apply_filters(
4381
			'jetpack_stats_base_url',
4382
			'https://pixel.wp.com/g.gif'
4383
		);
4384
		$url      = add_query_arg( $args, $base_url );
4385
		return $url;
4386
	}
4387
4388
	static function translate_current_user_to_role() {
4389
		foreach ( self::$capability_translations as $role => $cap ) {
4390
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4391
				return $role;
4392
			}
4393
		}
4394
4395
		return false;
4396
	}
4397
4398
	static function translate_user_to_role( $user ) {
4399
		foreach ( self::$capability_translations as $role => $cap ) {
4400
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4401
				return $role;
4402
			}
4403
		}
4404
4405
		return false;
4406
    }
4407
4408
	static function translate_role_to_cap( $role ) {
4409
		if ( ! isset( self::$capability_translations[$role] ) ) {
4410
			return false;
4411
		}
4412
4413
		return self::$capability_translations[$role];
4414
	}
4415
4416
	static function sign_role( $role, $user_id = null ) {
4417
		if ( empty( $user_id ) ) {
4418
			$user_id = (int) get_current_user_id();
4419
		}
4420
4421
		if ( ! $user_id  ) {
4422
			return false;
4423
		}
4424
4425
		$token = Jetpack_Data::get_access_token();
4426
		if ( ! $token || is_wp_error( $token ) ) {
4427
			return false;
4428
		}
4429
4430
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4431
	}
4432
4433
4434
	/**
4435
	 * Builds a URL to the Jetpack connection auth page
4436
	 *
4437
	 * @since 3.9.5
4438
	 *
4439
	 * @param bool $raw If true, URL will not be escaped.
4440
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4441
	 *                              If string, will be a custom redirect.
4442
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4443
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4444
	 *
4445
	 * @return string Connect URL
4446
	 */
4447
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4448
		$site_id = Jetpack_Options::get_option( 'id' );
4449
		$blog_token = Jetpack_Data::get_access_token();
4450
4451
		if ( $register || ! $blog_token || ! $site_id ) {
4452
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4453
4454
			if ( ! empty( $redirect ) ) {
4455
				$url = add_query_arg(
4456
					'redirect',
4457
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4458
					$url
4459
				);
4460
			}
4461
4462
			if( is_network_admin() ) {
4463
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4464
			}
4465
		} else {
4466
4467
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4468
			// because otherwise this logic can get us in to a loop.
4469
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4470
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4471
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4472
4473
				$response = Client::wpcom_json_api_request_as_blog(
4474
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4475
					'1.1'
4476
				);
4477
4478
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4479
4480
					// Generating a register URL instead to refresh the existing token
4481
					return $this->build_connect_url( $raw, $redirect, $from, true );
4482
				}
4483
			}
4484
4485
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4486
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4487
			}
4488
4489
			$role = self::translate_current_user_to_role();
4490
			$signed_role = self::sign_role( $role );
4491
4492
			$user = wp_get_current_user();
4493
4494
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4495
			$redirect = $redirect
4496
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4497
				: $jetpack_admin_page;
4498
4499
			if( isset( $_REQUEST['is_multisite'] ) ) {
4500
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4501
			}
4502
4503
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4504
4505
			/**
4506
			 * Filter the type of authorization.
4507
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4508
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4509
			 *
4510
			 * @since 4.3.3
4511
			 *
4512
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4513
			 */
4514
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4515
4516
4517
			$tracks = new Tracking();
4518
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4519
4520
			$args = urlencode_deep(
4521
				array(
4522
					'response_type' => 'code',
4523
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4524
					'redirect_uri'  => add_query_arg(
4525
						array(
4526
							'action'   => 'authorize',
4527
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4528
							'redirect' => urlencode( $redirect ),
4529
						),
4530
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4531
					),
4532
					'state'         => $user->ID,
4533
					'scope'         => $signed_role,
4534
					'user_email'    => $user->user_email,
4535
					'user_login'    => $user->user_login,
4536
					'is_active'     => Jetpack::is_active(),
4537
					'jp_version'    => JETPACK__VERSION,
4538
					'auth_type'     => $auth_type,
4539
					'secret'        => $secrets['secret_1'],
4540
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4541
					'blogname'      => get_option( 'blogname' ),
4542
					'site_url'      => site_url(),
4543
					'home_url'      => home_url(),
4544
					'site_icon'     => get_site_icon_url(),
4545
					'site_lang'     => get_locale(),
4546
					'_ui'           => $tracks_identity['_ui'],
4547
					'_ut'           => $tracks_identity['_ut'],
4548
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4549
				)
4550
			);
4551
4552
			self::apply_activation_source_to_args( $args );
4553
4554
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4555
		}
4556
4557
		if ( $from ) {
4558
			$url = add_query_arg( 'from', $from, $url );
4559
		}
4560
4561
		// Ensure that class to get the affiliate code is loaded
4562
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4563
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4564
		}
4565
		// Get affiliate code and add it to the URL
4566
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4567
4568
		$calypso_env = $this->get_calypso_env();
4569
4570
		if ( ! empty( $calypso_env ) ) {
4571
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4572
		}
4573
4574
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4575
	}
4576
4577
	/**
4578
	 * Get our assumed site creation date.
4579
	 * Calculated based on the earlier date of either:
4580
	 * - Earliest admin user registration date.
4581
	 * - Earliest date of post of any post type.
4582
	 *
4583
	 * @since 7.2.0
4584
	 *
4585
	 * @return string Assumed site creation date and time.
4586
	 */
4587
	public static function get_assumed_site_creation_date() {
4588
		$earliest_registered_users = get_users( array(
4589
			'role'    => 'administrator',
4590
			'orderby' => 'user_registered',
4591
			'order'   => 'ASC',
4592
			'fields'  => array( 'user_registered' ),
4593
			'number'  => 1,
4594
		) );
4595
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4596
4597
		$earliest_posts = get_posts( array(
4598
			'posts_per_page' => 1,
4599
			'post_type'      => 'any',
4600
			'post_status'    => 'any',
4601
			'orderby'        => 'date',
4602
			'order'          => 'ASC',
4603
		) );
4604
4605
		// If there are no posts at all, we'll count only on user registration date.
4606
		if ( $earliest_posts ) {
4607
			$earliest_post_date = $earliest_posts[0]->post_date;
4608
		} else {
4609
			$earliest_post_date = PHP_INT_MAX;
4610
		}
4611
4612
		return min( $earliest_registration_date, $earliest_post_date );
4613
	}
4614
4615
	public static function apply_activation_source_to_args( &$args ) {
4616
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4617
4618
		if ( $activation_source_name ) {
4619
			$args['_as'] = urlencode( $activation_source_name );
4620
		}
4621
4622
		if ( $activation_source_keyword ) {
4623
			$args['_ak'] = urlencode( $activation_source_keyword );
4624
		}
4625
	}
4626
4627
	function build_reconnect_url( $raw = false ) {
4628
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4629
		return $raw ? $url : esc_url( $url );
4630
	}
4631
4632
	public static function admin_url( $args = null ) {
4633
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4634
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4635
		return $url;
4636
	}
4637
4638
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4639
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4640
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4641
	}
4642
4643
	function dismiss_jetpack_notice() {
4644
4645
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4646
			return;
4647
		}
4648
4649
		switch( $_GET['jetpack-notice'] ) {
4650
			case 'dismiss':
4651
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4652
4653
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4654
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4655
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4656
				}
4657
				break;
4658
			case 'jetpack-protect-multisite-opt-out':
4659
4660
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4661
					// Don't show the banner again
4662
4663
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4664
					// redirect back to the page that had the notice
4665
					if ( wp_get_referer() ) {
4666
						wp_safe_redirect( wp_get_referer() );
4667
					} else {
4668
						// Take me to Jetpack
4669
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4670
					}
4671
				}
4672
				break;
4673
		}
4674
	}
4675
4676
	public static function sort_modules( $a, $b ) {
4677
		if ( $a['sort'] == $b['sort'] )
4678
			return 0;
4679
4680
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4681
	}
4682
4683
	function ajax_recheck_ssl() {
4684
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4685
		$result = Jetpack::permit_ssl( true );
4686
		wp_send_json( array(
4687
			'enabled' => $result,
4688
			'message' => get_transient( 'jetpack_https_test_message' )
4689
		) );
4690
	}
4691
4692
/* Client API */
4693
4694
	/**
4695
	 * Returns the requested Jetpack API URL
4696
	 *
4697
	 * @return string
4698
	 */
4699
	public static function api_url( $relative_url ) {
4700
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4701
	}
4702
4703
	/**
4704
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4705
	 */
4706
	public static function fix_url_for_bad_hosts( $url ) {
4707
		if ( 0 !== strpos( $url, 'https://' ) ) {
4708
			return $url;
4709
		}
4710
4711
		switch ( JETPACK_CLIENT__HTTPS ) {
4712
			case 'ALWAYS' :
4713
				return $url;
4714
			case 'NEVER' :
4715
				return set_url_scheme( $url, 'http' );
4716
			// default : case 'AUTO' :
4717
		}
4718
4719
		// we now return the unmodified SSL URL by default, as a security precaution
4720
		return $url;
4721
	}
4722
4723
	/**
4724
	 * Create a random secret for validating onboarding payload
4725
	 *
4726
	 * @return string Secret token
4727
	 */
4728
	public static function create_onboarding_token() {
4729
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4730
			$token = wp_generate_password( 32, false );
4731
			Jetpack_Options::update_option( 'onboarding', $token );
4732
		}
4733
4734
		return $token;
4735
	}
4736
4737
	/**
4738
	 * Remove the onboarding token
4739
	 *
4740
	 * @return bool True on success, false on failure
4741
	 */
4742
	public static function invalidate_onboarding_token() {
4743
		return Jetpack_Options::delete_option( 'onboarding' );
4744
	}
4745
4746
	/**
4747
	 * Validate an onboarding token for a specific action
4748
	 *
4749
	 * @return boolean True if token/action pair is accepted, false if not
4750
	 */
4751
	public static function validate_onboarding_token_action( $token, $action ) {
4752
		// Compare tokens, bail if tokens do not match
4753
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4754
			return false;
4755
		}
4756
4757
		// List of valid actions we can take
4758
		$valid_actions = array(
4759
			'/jetpack/v4/settings',
4760
		);
4761
4762
		// Whitelist the action
4763
		if ( ! in_array( $action, $valid_actions ) ) {
4764
			return false;
4765
		}
4766
4767
		return true;
4768
	}
4769
4770
	/**
4771
	 * Checks to see if the URL is using SSL to connect with Jetpack
4772
	 *
4773
	 * @since 2.3.3
4774
	 * @return boolean
4775
	 */
4776
	public static function permit_ssl( $force_recheck = false ) {
4777
		// Do some fancy tests to see if ssl is being supported
4778
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4779
			$message = '';
4780
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4781
				$ssl = 0;
4782
			} else {
4783
				switch ( JETPACK_CLIENT__HTTPS ) {
4784
					case 'NEVER':
4785
						$ssl = 0;
4786
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4787
						break;
4788
					case 'ALWAYS':
4789
					case 'AUTO':
4790
					default:
4791
						$ssl = 1;
4792
						break;
4793
				}
4794
4795
				// If it's not 'NEVER', test to see
4796
				if ( $ssl ) {
4797
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4798
						$ssl = 0;
4799
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4800
					} else {
4801
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4802
						if ( is_wp_error( $response ) ) {
4803
							$ssl = 0;
4804
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4805
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4806
							$ssl = 0;
4807
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4808
						}
4809
					}
4810
				}
4811
			}
4812
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4813
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4814
		}
4815
4816
		return (bool) $ssl;
4817
	}
4818
4819
	/*
4820
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4821
	 */
4822
	public function alert_auto_ssl_fail() {
4823
		if ( ! current_user_can( 'manage_options' ) )
4824
			return;
4825
4826
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4827
		?>
4828
4829
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4830
			<div class="jp-banner__content">
4831
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4832
				<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>
4833
				<p>
4834
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4835
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4836
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4837
				</p>
4838
				<p>
4839
					<?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' ),
4840
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4841
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4842
				</p>
4843
			</div>
4844
		</div>
4845
		<style>
4846
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4847
		</style>
4848
		<script type="text/javascript">
4849
			jQuery( document ).ready( function( $ ) {
4850
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4851
					var $this = $( this );
4852
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4853
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4854
					e.preventDefault();
4855
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4856
					$.post( ajaxurl, data )
4857
					  .done( function( response ) {
4858
					  	if ( response.enabled ) {
4859
					  		$( '#jetpack-ssl-warning' ).hide();
4860
					  	} else {
4861
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4862
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4863
					  	}
4864
					  }.bind( $this ) );
4865
				} );
4866
			} );
4867
		</script>
4868
4869
		<?php
4870
	}
4871
4872
	/**
4873
	 * Returns the Jetpack XML-RPC API
4874
	 *
4875
	 * @return string
4876
	 */
4877
	public static function xmlrpc_api_url() {
4878
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4879
		return untrailingslashit( $base ) . '/xmlrpc.php';
4880
	}
4881
4882
	public static function connection() {
4883
		return self::init()->connection_manager;
4884
	}
4885
4886
	/**
4887
	 * Creates two secret tokens and the end of life timestamp for them.
4888
	 *
4889
	 * Note these tokens are unique per call, NOT static per site for connecting.
4890
	 *
4891
	 * @since 2.6
4892
	 * @return array
4893
	 */
4894
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4895
		if ( false === $user_id ) {
4896
			$user_id = get_current_user_id();
4897
		}
4898
4899
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4900
	}
4901
4902
	public static function get_secrets( $action, $user_id ) {
4903
		$secrets = self::connection()->get_secrets( $action, $user_id );
4904
4905
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4906
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
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...
4907
		}
4908
4909
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4910
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
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...
4911
		}
4912
4913
		return $secrets;
4914
	}
4915
4916
	/**
4917
	 * @deprecated 7.5 Use Connection_Manager instead.
4918
	 *
4919
	 * @param $action
4920
	 * @param $user_id
4921
	 */
4922
	public static function delete_secrets( $action, $user_id ) {
4923
		return self::connection()->delete_secrets( $action, $user_id );
4924
	}
4925
4926
	/**
4927
	 * Builds the timeout limit for queries talking with the wpcom servers.
4928
	 *
4929
	 * Based on local php max_execution_time in php.ini
4930
	 *
4931
	 * @since 2.6
4932
	 * @return int
4933
	 * @deprecated
4934
	 **/
4935
	public function get_remote_query_timeout_limit() {
4936
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4937
		return Jetpack::get_max_execution_time();
4938
	}
4939
4940
	/**
4941
	 * Builds the timeout limit for queries talking with the wpcom servers.
4942
	 *
4943
	 * Based on local php max_execution_time in php.ini
4944
	 *
4945
	 * @since 5.4
4946
	 * @return int
4947
	 **/
4948
	public static function get_max_execution_time() {
4949
		$timeout = (int) ini_get( 'max_execution_time' );
4950
4951
		// Ensure exec time set in php.ini
4952
		if ( ! $timeout ) {
4953
			$timeout = 30;
4954
		}
4955
		return $timeout;
4956
	}
4957
4958
	/**
4959
	 * Sets a minimum request timeout, and returns the current timeout
4960
	 *
4961
	 * @since 5.4
4962
	 **/
4963
	public static function set_min_time_limit( $min_timeout ) {
4964
		$timeout = self::get_max_execution_time();
4965
		if ( $timeout < $min_timeout ) {
4966
			$timeout = $min_timeout;
4967
			set_time_limit( $timeout );
4968
		}
4969
		return $timeout;
4970
	}
4971
4972
4973
	/**
4974
	 * Takes the response from the Jetpack register new site endpoint and
4975
	 * verifies it worked properly.
4976
	 *
4977
	 * @since 2.6
4978
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4979
	 **/
4980
	public function validate_remote_register_response( $response ) {
4981
	  if ( is_wp_error( $response ) ) {
4982
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'register_http_request_failed'.

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

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

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

Loading history...
4983
		}
4984
4985
		$code   = wp_remote_retrieve_response_code( $response );
4986
		$entity = wp_remote_retrieve_body( $response );
4987
		if ( $entity )
4988
			$registration_response = json_decode( $entity );
4989
		else
4990
			$registration_response = false;
4991
4992
		$code_type = intval( $code / 100 );
4993
		if ( 5 == $code_type ) {
4994
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_5??'.

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

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

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

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

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

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

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

Loading history...
4997
		} elseif ( ! empty( $registration_response->error ) ) {
4998
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4999
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
5000
			} else {
5001
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5002
			}
5003
5004
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with (string) $registration_response->error.

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

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

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

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

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

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

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

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

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

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

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

Loading history...
5012
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5013
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

Loading history...
5014
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5015
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

Loading history...
5016
		}
5017
5018
	    return $registration_response;
5019
	}
5020
	/**
5021
	 * @return bool|WP_Error
5022
	 */
5023
	public static function register() {
5024
		$tracking = new Tracking();
5025
		$tracking->record_user_event( 'jpc_register_begin' );
5026
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5027
		$secrets = Jetpack::generate_secrets( 'register' );
5028
5029 View Code Duplication
		if (
5030
			empty( $secrets['secret_1'] ) ||
5031
			empty( $secrets['secret_2'] ) ||
5032
			empty( $secrets['exp'] )
5033
		) {
5034
			return new Jetpack_Error( 'missing_secrets' );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_secrets'.

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

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

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

Loading history...
5035
		}
5036
5037
		// better to try (and fail) to set a higher timeout than this system
5038
		// supports than to have register fail for more users than it should
5039
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5040
5041
		$gmt_offset = get_option( 'gmt_offset' );
5042
		if ( ! $gmt_offset ) {
5043
			$gmt_offset = 0;
5044
		}
5045
5046
		$stats_options = get_option( 'stats_options' );
5047
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5048
5049
		$tracks = new Tracking();
5050
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5051
5052
		$args = array(
5053
			'method'  => 'POST',
5054
			'body'    => array(
5055
				'siteurl'         => site_url(),
5056
				'home'            => home_url(),
5057
				'gmt_offset'      => $gmt_offset,
5058
				'timezone_string' => (string) get_option( 'timezone_string' ),
5059
				'site_name'       => (string) get_option( 'blogname' ),
5060
				'secret_1'        => $secrets['secret_1'],
5061
				'secret_2'        => $secrets['secret_2'],
5062
				'site_lang'       => get_locale(),
5063
				'timeout'         => $timeout,
5064
				'stats_id'        => $stats_id,
5065
				'state'           => get_current_user_id(),
5066
				'_ui'             => $tracks_identity['_ui'],
5067
				'_ut'             => $tracks_identity['_ut'],
5068
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5069
				'jetpack_version' => JETPACK__VERSION
5070
			),
5071
			'headers' => array(
5072
				'Accept' => 'application/json',
5073
			),
5074
			'timeout' => $timeout,
5075
		);
5076
5077
		self::apply_activation_source_to_args( $args['body'] );
5078
5079
		$response = Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5080
5081
		// Make sure the response is valid and does not contain any Jetpack errors
5082
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5083
		if ( is_wp_error( $registration_details ) ) {
5084
			return $registration_details;
5085
		} elseif ( ! $registration_details ) {
5086
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
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...
5087
		}
5088
5089 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5090
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_secret'.

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

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

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

Loading history...
5091
		}
5092
5093
		if ( isset( $registration_details->jetpack_public ) ) {
5094
			$jetpack_public = (int) $registration_details->jetpack_public;
5095
		} else {
5096
			$jetpack_public = false;
5097
		}
5098
5099
		Jetpack_Options::update_options(
5100
			array(
5101
				'id'         => (int)    $registration_details->jetpack_id,
5102
				'blog_token' => (string) $registration_details->jetpack_secret,
5103
				'public'     => $jetpack_public,
5104
			)
5105
		);
5106
5107
		/**
5108
		 * Fires when a site is registered on WordPress.com.
5109
		 *
5110
		 * @since 3.7.0
5111
		 *
5112
		 * @param int $json->jetpack_id Jetpack Blog ID.
5113
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5114
		 * @param int|bool $jetpack_public Is the site public.
5115
		 */
5116
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5117
5118
		$jetpack = Jetpack::init();
5119
5120
		return true;
5121
	}
5122
5123
	/**
5124
	 * If the db version is showing something other that what we've got now, bump it to current.
5125
	 *
5126
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5127
	 */
5128
	public static function maybe_set_version_option() {
5129
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5130
		if ( JETPACK__VERSION != $version ) {
5131
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5132
5133
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5134
				/** This action is documented in class.jetpack.php */
5135
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5136
			}
5137
5138
			return true;
5139
		}
5140
		return false;
5141
	}
5142
5143
/* Client Server API */
5144
5145
	/**
5146
	 * Loads the Jetpack XML-RPC client
5147
	 */
5148
	public static function load_xml_rpc_client() {
5149
		require_once ABSPATH . WPINC . '/class-IXR.php';
5150
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5151
	}
5152
5153
	/**
5154
	 * Resets the saved authentication state in between testing requests.
5155
	 */
5156
	public function reset_saved_auth_state() {
5157
		$this->xmlrpc_verification = null;
5158
		$this->rest_authentication_status = null;
5159
	}
5160
5161
	/**
5162
	 * Verifies the signature of the current request.
5163
	 *
5164
	 * @return false|array
5165
	 */
5166
	function verify_xml_rpc_signature() {
5167
		if ( is_null( $this->xmlrpc_verification ) ) {
5168
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
5169
5170
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
5171
				/**
5172
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
5173
				 *
5174
				 * Error codes:
5175
				 * - malformed_token
5176
				 * - malformed_user_id
5177
				 * - unknown_token
5178
				 * - could_not_sign
5179
				 * - invalid_nonce
5180
				 * - signature_mismatch
5181
				 *
5182
				 * @since 7.5.0
5183
				 *
5184
				 * @param WP_Error $signature_verification_error The verification error
5185
				 */
5186
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
5187
			}
5188
		}
5189
5190
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
5191
	}
5192
5193
	/**
5194
	 * Verifies the signature of the current request.
5195
	 *
5196
	 * This function has side effects and should not be used. Instead,
5197
	 * use the memoized version `->verify_xml_rpc_signature()`.
5198
	 *
5199
	 * @internal
5200
	 */
5201
	private function internal_verify_xml_rpc_signature() {
5202
		// It's not for us
5203
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5204
			return false;
5205
		}
5206
5207
		$signature_details = array(
5208
			'token'     => isset( $_GET['token'] )     ? wp_unslash( $_GET['token'] )     : '',
5209
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
5210
			'nonce'     => isset( $_GET['nonce'] )     ? wp_unslash( $_GET['nonce'] )     : '',
5211
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
5212
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
5213
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
5214
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
5215
		);
5216
5217
		@list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
5218
		if (
5219
			empty( $token_key )
5220
		||
5221
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5222
		) {
5223
			return new WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'malformed_token'.

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

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

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

Loading history...
5224
		}
5225
5226
		if ( '0' === $user_id ) {
5227
			$token_type = 'blog';
5228
			$user_id = 0;
5229
		} else {
5230
			$token_type = 'user';
5231
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5232
				return new WP_Error( 'malformed_user_id', 'Malformed user_id in request', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'malformed_user_id'.

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

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

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

Loading history...
5233
			}
5234
			$user_id = (int) $user_id;
5235
5236
			$user = new WP_User( $user_id );
5237
			if ( ! $user || ! $user->exists() ) {
5238
				return new WP_Error( 'unknown_user', sprintf( 'User %d does not exist', $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'unknown_user'.

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

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

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

Loading history...
5239
			}
5240
		}
5241
5242
		$token = Jetpack_Data::get_access_token( $user_id, $token_key, false );
0 ignored issues
show
$user_id is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
5243
		if ( is_wp_error( $token ) ) {
5244
			$token->add_data( compact( 'signature_details' ) );
5245
			return $token;
5246
		} elseif ( ! $token ) {
5247
			return new WP_Error( 'unknown_token', sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
5248
		}
5249
5250
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5251
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5252
			$post_data   = $_POST;
5253
			$file_hashes = array();
5254
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5255
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5256
					continue;
5257
				}
5258
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5259
				$file_hashes[$post_data_key] = $post_data_value;
5260
			}
5261
5262
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5263
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5264
				$post_data[$post_data_key] = $post_data_value;
5265
			}
5266
5267
			ksort( $post_data );
5268
5269
			$body = http_build_query( stripslashes_deep( $post_data ) );
5270
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5271
			$body = file_get_contents( 'php://input' );
5272
		} else {
5273
			$body = null;
5274
		}
5275
5276
		$signature = $jetpack_signature->sign_current_request(
5277
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5278
		);
5279
5280
		$signature_details['url'] = $jetpack_signature->current_request_url;
5281
5282
		if ( ! $signature ) {
5283
			return new WP_Error( 'could_not_sign', 'Unknown signature error', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'could_not_sign'.

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

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

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

Loading history...
5284
		} else if ( is_wp_error( $signature ) ) {
5285
			return $signature;
5286
		}
5287
5288
		$timestamp = (int) $_GET['timestamp'];
5289
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5290
5291
		// Use up the nonce regardless of whether the signature matches.
5292
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5293
			return new WP_Error( 'invalid_nonce', 'Could not add nonce', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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

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

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

Loading history...
5294
		}
5295
5296
		// Be careful about what you do with this debugging data.
5297
		// If a malicious requester has access to the expected signature,
5298
		// bad things might be possible.
5299
		$signature_details['expected'] = $signature;
5300
5301
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5302
			return new WP_Error( 'signature_mismatch', 'Signature mismatch', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'signature_mismatch'.

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7078
		} else {
7079
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7080
		}
7081
7082
		// Since this is a fresh connection, be sure to clear out IDC options
7083
		Jetpack_IDC::clear_all_idc_options();
7084
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7085
7086
		// Start nonce cleaner
7087
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7088
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7089
7090
		if ( $send_state_messages ) {
7091
			Jetpack::state( 'message', 'authorized' );
7092
		}
7093
	}
7094
7095
	/**
7096
	 * Returns a boolean for whether backups UI should be displayed or not.
7097
	 *
7098
	 * @return bool Should backups UI be displayed?
7099
	 */
7100
	public static function show_backups_ui() {
7101
		/**
7102
		 * Whether UI for backups should be displayed.
7103
		 *
7104
		 * @since 6.5.0
7105
		 *
7106
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7107
		 */
7108
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7109
	}
7110
7111
	/*
7112
	 * Deprecated manage functions
7113
	 */
7114
	function prepare_manage_jetpack_notice() {
7115
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7116
	}
7117
	function manage_activate_screen() {
7118
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7119
	}
7120
	function admin_jetpack_manage_notice() {
7121
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7122
	}
7123
	function opt_out_jetpack_manage_url() {
7124
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7125
	}
7126
	function opt_in_jetpack_manage_url() {
7127
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7128
	}
7129
	function opt_in_jetpack_manage_notice() {
7130
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7131
	}
7132
	function can_display_jetpack_manage_notice() {
7133
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7134
	}
7135
7136
	/**
7137
	 * Clean leftoveruser meta.
7138
	 *
7139
	 * Delete Jetpack-related user meta when it is no longer needed.
7140
	 *
7141
	 * @since 7.3.0
7142
	 *
7143
	 * @param int $user_id User ID being updated.
7144
	 */
7145
	public static function user_meta_cleanup( $user_id ) {
7146
		$meta_keys = array(
7147
			// AtD removed from Jetpack 7.3
7148
			'AtD_options',
7149
			'AtD_check_when',
7150
			'AtD_guess_lang',
7151
			'AtD_ignored_phrases',
7152
		);
7153
7154
		foreach ( $meta_keys as $meta_key ) {
7155
			if ( get_user_meta( $user_id, $meta_key ) ) {
7156
				delete_user_meta( $user_id, $meta_key );
7157
			}
7158
		}
7159
	}
7160
7161
	function is_active_and_not_development_mode( $maybe ) {
7162
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7163
			return false;
7164
		}
7165
		return true;
7166
	}
7167
7168
}
7169